httpd.js 142 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. /*
  5. * An implementation of an HTTP server both as a loadable script and as an XPCOM
  6. * component. See the accompanying README file for user documentation on
  7. * httpd.js.
  8. */
  9. module.metadata = {
  10. "stability": "experimental"
  11. };
  12. const { components, CC, Cc, Ci, Cr, Cu } = require("chrome");
  13. Cu.import("resource://gre/modules/XPCOMUtils.jsm");
  14. const PR_UINT32_MAX = Math.pow(2, 32) - 1;
  15. /** True if debugging output is enabled, false otherwise. */
  16. var DEBUG = false; // non-const *only* so tweakable in server tests
  17. /** True if debugging output should be timestamped. */
  18. var DEBUG_TIMESTAMP = false; // non-const so tweakable in server tests
  19. var gGlobalObject = Cc["@mozilla.org/systemprincipal;1"].createInstance();
  20. /**
  21. * Asserts that the given condition holds. If it doesn't, the given message is
  22. * dumped, a stack trace is printed, and an exception is thrown to attempt to
  23. * stop execution (which unfortunately must rely upon the exception not being
  24. * accidentally swallowed by the code that uses it).
  25. */
  26. function NS_ASSERT(cond, msg)
  27. {
  28. if (DEBUG && !cond)
  29. {
  30. dumpn("###!!!");
  31. dumpn("###!!! ASSERTION" + (msg ? ": " + msg : "!"));
  32. dumpn("###!!! Stack follows:");
  33. var stack = new Error().stack.split(/\n/);
  34. dumpn(stack.map(function(val) { return "###!!! " + val; }).join("\n"));
  35. throw Cr.NS_ERROR_ABORT;
  36. }
  37. }
  38. /** Constructs an HTTP error object. */
  39. function HttpError(code, description)
  40. {
  41. this.code = code;
  42. this.description = description;
  43. }
  44. HttpError.prototype =
  45. {
  46. toString: function()
  47. {
  48. return this.code + " " + this.description;
  49. }
  50. };
  51. /**
  52. * Errors thrown to trigger specific HTTP server responses.
  53. */
  54. const HTTP_400 = new HttpError(400, "Bad Request");
  55. const HTTP_401 = new HttpError(401, "Unauthorized");
  56. const HTTP_402 = new HttpError(402, "Payment Required");
  57. const HTTP_403 = new HttpError(403, "Forbidden");
  58. const HTTP_404 = new HttpError(404, "Not Found");
  59. const HTTP_405 = new HttpError(405, "Method Not Allowed");
  60. const HTTP_406 = new HttpError(406, "Not Acceptable");
  61. const HTTP_407 = new HttpError(407, "Proxy Authentication Required");
  62. const HTTP_408 = new HttpError(408, "Request Timeout");
  63. const HTTP_409 = new HttpError(409, "Conflict");
  64. const HTTP_410 = new HttpError(410, "Gone");
  65. const HTTP_411 = new HttpError(411, "Length Required");
  66. const HTTP_412 = new HttpError(412, "Precondition Failed");
  67. const HTTP_413 = new HttpError(413, "Request Entity Too Large");
  68. const HTTP_414 = new HttpError(414, "Request-URI Too Long");
  69. const HTTP_415 = new HttpError(415, "Unsupported Media Type");
  70. const HTTP_417 = new HttpError(417, "Expectation Failed");
  71. const HTTP_500 = new HttpError(500, "Internal Server Error");
  72. const HTTP_501 = new HttpError(501, "Not Implemented");
  73. const HTTP_502 = new HttpError(502, "Bad Gateway");
  74. const HTTP_503 = new HttpError(503, "Service Unavailable");
  75. const HTTP_504 = new HttpError(504, "Gateway Timeout");
  76. const HTTP_505 = new HttpError(505, "HTTP Version Not Supported");
  77. /** Creates a hash with fields corresponding to the values in arr. */
  78. function array2obj(arr)
  79. {
  80. var obj = {};
  81. for (var i = 0; i < arr.length; i++)
  82. obj[arr[i]] = arr[i];
  83. return obj;
  84. }
  85. /** Returns an array of the integers x through y, inclusive. */
  86. function range(x, y)
  87. {
  88. var arr = [];
  89. for (var i = x; i <= y; i++)
  90. arr.push(i);
  91. return arr;
  92. }
  93. /** An object (hash) whose fields are the numbers of all HTTP error codes. */
  94. const HTTP_ERROR_CODES = array2obj(range(400, 417).concat(range(500, 505)));
  95. /**
  96. * The character used to distinguish hidden files from non-hidden files, a la
  97. * the leading dot in Apache. Since that mechanism also hides files from
  98. * easy display in LXR, ls output, etc. however, we choose instead to use a
  99. * suffix character. If a requested file ends with it, we append another
  100. * when getting the file on the server. If it doesn't, we just look up that
  101. * file. Therefore, any file whose name ends with exactly one of the character
  102. * is "hidden" and available for use by the server.
  103. */
  104. const HIDDEN_CHAR = "^";
  105. /**
  106. * The file name suffix indicating the file containing overridden headers for
  107. * a requested file.
  108. */
  109. const HEADERS_SUFFIX = HIDDEN_CHAR + "headers" + HIDDEN_CHAR;
  110. /** Type used to denote SJS scripts for CGI-like functionality. */
  111. const SJS_TYPE = "sjs";
  112. /** Base for relative timestamps produced by dumpn(). */
  113. var firstStamp = 0;
  114. /** dump(str) with a trailing "\n" -- only outputs if DEBUG. */
  115. function dumpn(str)
  116. {
  117. if (DEBUG)
  118. {
  119. var prefix = "HTTPD-INFO | ";
  120. if (DEBUG_TIMESTAMP)
  121. {
  122. if (firstStamp === 0)
  123. firstStamp = Date.now();
  124. var elapsed = Date.now() - firstStamp; // milliseconds
  125. var min = Math.floor(elapsed / 60000);
  126. var sec = (elapsed % 60000) / 1000;
  127. if (sec < 10)
  128. prefix += min + ":0" + sec.toFixed(3) + " | ";
  129. else
  130. prefix += min + ":" + sec.toFixed(3) + " | ";
  131. }
  132. dump(prefix + str + "\n");
  133. }
  134. }
  135. /** Dumps the current JS stack if DEBUG. */
  136. function dumpStack()
  137. {
  138. // peel off the frames for dumpStack() and Error()
  139. var stack = new Error().stack.split(/\n/).slice(2);
  140. stack.forEach(dumpn);
  141. }
  142. /** The XPCOM thread manager. */
  143. var gThreadManager = null;
  144. /** The XPCOM prefs service. */
  145. var gRootPrefBranch = null;
  146. function getRootPrefBranch()
  147. {
  148. if (!gRootPrefBranch)
  149. {
  150. gRootPrefBranch = Cc["@mozilla.org/preferences-service;1"]
  151. .getService(Ci.nsIPrefBranch);
  152. }
  153. return gRootPrefBranch;
  154. }
  155. /**
  156. * JavaScript constructors for commonly-used classes; precreating these is a
  157. * speedup over doing the same from base principles. See the docs at
  158. * http://developer.mozilla.org/en/docs/components.Constructor for details.
  159. */
  160. const ServerSocket = CC("@mozilla.org/network/server-socket;1",
  161. "nsIServerSocket",
  162. "init");
  163. const ScriptableInputStream = CC("@mozilla.org/scriptableinputstream;1",
  164. "nsIScriptableInputStream",
  165. "init");
  166. const Pipe = CC("@mozilla.org/pipe;1",
  167. "nsIPipe",
  168. "init");
  169. const FileInputStream = CC("@mozilla.org/network/file-input-stream;1",
  170. "nsIFileInputStream",
  171. "init");
  172. const ConverterInputStream = CC("@mozilla.org/intl/converter-input-stream;1",
  173. "nsIConverterInputStream",
  174. "init");
  175. const WritablePropertyBag = CC("@mozilla.org/hash-property-bag;1",
  176. "nsIWritablePropertyBag2");
  177. const SupportsString = CC("@mozilla.org/supports-string;1",
  178. "nsISupportsString");
  179. /* These two are non-const only so a test can overwrite them. */
  180. var BinaryInputStream = CC("@mozilla.org/binaryinputstream;1",
  181. "nsIBinaryInputStream",
  182. "setInputStream");
  183. var BinaryOutputStream = CC("@mozilla.org/binaryoutputstream;1",
  184. "nsIBinaryOutputStream",
  185. "setOutputStream");
  186. /**
  187. * Returns the RFC 822/1123 representation of a date.
  188. *
  189. * @param date : Number
  190. * the date, in milliseconds from midnight (00:00:00), January 1, 1970 GMT
  191. * @returns string
  192. * the representation of the given date
  193. */
  194. function toDateString(date)
  195. {
  196. //
  197. // rfc1123-date = wkday "," SP date1 SP time SP "GMT"
  198. // date1 = 2DIGIT SP month SP 4DIGIT
  199. // ; day month year (e.g., 02 Jun 1982)
  200. // time = 2DIGIT ":" 2DIGIT ":" 2DIGIT
  201. // ; 00:00:00 - 23:59:59
  202. // wkday = "Mon" | "Tue" | "Wed"
  203. // | "Thu" | "Fri" | "Sat" | "Sun"
  204. // month = "Jan" | "Feb" | "Mar" | "Apr"
  205. // | "May" | "Jun" | "Jul" | "Aug"
  206. // | "Sep" | "Oct" | "Nov" | "Dec"
  207. //
  208. const wkdayStrings = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  209. const monthStrings = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
  210. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  211. /**
  212. * Processes a date and returns the encoded UTC time as a string according to
  213. * the format specified in RFC 2616.
  214. *
  215. * @param date : Date
  216. * the date to process
  217. * @returns string
  218. * a string of the form "HH:MM:SS", ranging from "00:00:00" to "23:59:59"
  219. */
  220. function toTime(date)
  221. {
  222. var hrs = date.getUTCHours();
  223. var rv = (hrs < 10) ? "0" + hrs : hrs;
  224. var mins = date.getUTCMinutes();
  225. rv += ":";
  226. rv += (mins < 10) ? "0" + mins : mins;
  227. var secs = date.getUTCSeconds();
  228. rv += ":";
  229. rv += (secs < 10) ? "0" + secs : secs;
  230. return rv;
  231. }
  232. /**
  233. * Processes a date and returns the encoded UTC date as a string according to
  234. * the date1 format specified in RFC 2616.
  235. *
  236. * @param date : Date
  237. * the date to process
  238. * @returns string
  239. * a string of the form "HH:MM:SS", ranging from "00:00:00" to "23:59:59"
  240. */
  241. function toDate1(date)
  242. {
  243. var day = date.getUTCDate();
  244. var month = date.getUTCMonth();
  245. var year = date.getUTCFullYear();
  246. var rv = (day < 10) ? "0" + day : day;
  247. rv += " " + monthStrings[month];
  248. rv += " " + year;
  249. return rv;
  250. }
  251. date = new Date(date);
  252. const fmtString = "%wkday%, %date1% %time% GMT";
  253. var rv = fmtString.replace("%wkday%", wkdayStrings[date.getUTCDay()]);
  254. rv = rv.replace("%time%", toTime(date));
  255. return rv.replace("%date1%", toDate1(date));
  256. }
  257. /**
  258. * Prints out a human-readable representation of the object o and its fields,
  259. * omitting those whose names begin with "_" if showMembers != true (to ignore
  260. * "private" properties exposed via getters/setters).
  261. */
  262. function printObj(o, showMembers)
  263. {
  264. var s = "******************************\n";
  265. s += "o = {\n";
  266. for (var i in o)
  267. {
  268. if (typeof(i) != "string" ||
  269. (showMembers || (i.length > 0 && i[0] != "_")))
  270. s+= " " + i + ": " + o[i] + ",\n";
  271. }
  272. s += " };\n";
  273. s += "******************************";
  274. dumpn(s);
  275. }
  276. /**
  277. * Instantiates a new HTTP server.
  278. */
  279. function nsHttpServer()
  280. {
  281. if (!gThreadManager)
  282. gThreadManager = Cc["@mozilla.org/thread-manager;1"].getService();
  283. /** The port on which this server listens. */
  284. this._port = undefined;
  285. /** The socket associated with this. */
  286. this._socket = null;
  287. /** The handler used to process requests to this server. */
  288. this._handler = new ServerHandler(this);
  289. /** Naming information for this server. */
  290. this._identity = new ServerIdentity();
  291. /**
  292. * Indicates when the server is to be shut down at the end of the request.
  293. */
  294. this._doQuit = false;
  295. /**
  296. * True if the socket in this is closed (and closure notifications have been
  297. * sent and processed if the socket was ever opened), false otherwise.
  298. */
  299. this._socketClosed = true;
  300. /**
  301. * Used for tracking existing connections and ensuring that all connections
  302. * are properly cleaned up before server shutdown; increases by 1 for every
  303. * new incoming connection.
  304. */
  305. this._connectionGen = 0;
  306. /**
  307. * Hash of all open connections, indexed by connection number at time of
  308. * creation.
  309. */
  310. this._connections = {};
  311. }
  312. nsHttpServer.prototype =
  313. {
  314. classID: components.ID("{54ef6f81-30af-4b1d-ac55-8ba811293e41}"),
  315. // NSISERVERSOCKETLISTENER
  316. /**
  317. * Processes an incoming request coming in on the given socket and contained
  318. * in the given transport.
  319. *
  320. * @param socket : nsIServerSocket
  321. * the socket through which the request was served
  322. * @param trans : nsISocketTransport
  323. * the transport for the request/response
  324. * @see nsIServerSocketListener.onSocketAccepted
  325. */
  326. onSocketAccepted: function(socket, trans)
  327. {
  328. dumpn("*** onSocketAccepted(socket=" + socket + ", trans=" + trans + ")");
  329. dumpn(">>> new connection on " + trans.host + ":" + trans.port);
  330. const SEGMENT_SIZE = 8192;
  331. const SEGMENT_COUNT = 1024;
  332. try
  333. {
  334. var input = trans.openInputStream(0, SEGMENT_SIZE, SEGMENT_COUNT)
  335. .QueryInterface(Ci.nsIAsyncInputStream);
  336. var output = trans.openOutputStream(0, 0, 0);
  337. }
  338. catch (e)
  339. {
  340. dumpn("*** error opening transport streams: " + e);
  341. trans.close(Cr.NS_BINDING_ABORTED);
  342. return;
  343. }
  344. var connectionNumber = ++this._connectionGen;
  345. try
  346. {
  347. var conn = new Connection(input, output, this, socket.port, trans.port,
  348. connectionNumber);
  349. var reader = new RequestReader(conn);
  350. // XXX add request timeout functionality here!
  351. // Note: must use main thread here, or we might get a GC that will cause
  352. // threadsafety assertions. We really need to fix XPConnect so that
  353. // you can actually do things in multi-threaded JS. :-(
  354. input.asyncWait(reader, 0, 0, gThreadManager.mainThread);
  355. }
  356. catch (e)
  357. {
  358. // Assume this connection can't be salvaged and bail on it completely;
  359. // don't attempt to close it so that we can assert that any connection
  360. // being closed is in this._connections.
  361. dumpn("*** error in initial request-processing stages: " + e);
  362. trans.close(Cr.NS_BINDING_ABORTED);
  363. return;
  364. }
  365. this._connections[connectionNumber] = conn;
  366. dumpn("*** starting connection " + connectionNumber);
  367. },
  368. /**
  369. * Called when the socket associated with this is closed.
  370. *
  371. * @param socket : nsIServerSocket
  372. * the socket being closed
  373. * @param status : nsresult
  374. * the reason the socket stopped listening (NS_BINDING_ABORTED if the server
  375. * was stopped using nsIHttpServer.stop)
  376. * @see nsIServerSocketListener.onStopListening
  377. */
  378. onStopListening: function(socket, status)
  379. {
  380. dumpn(">>> shutting down server on port " + socket.port);
  381. this._socketClosed = true;
  382. if (!this._hasOpenConnections())
  383. {
  384. dumpn("*** no open connections, notifying async from onStopListening");
  385. // Notify asynchronously so that any pending teardown in stop() has a
  386. // chance to run first.
  387. var self = this;
  388. var stopEvent =
  389. {
  390. run: function()
  391. {
  392. dumpn("*** _notifyStopped async callback");
  393. self._notifyStopped();
  394. }
  395. };
  396. gThreadManager.currentThread
  397. .dispatch(stopEvent, Ci.nsIThread.DISPATCH_NORMAL);
  398. }
  399. },
  400. // NSIHTTPSERVER
  401. //
  402. // see nsIHttpServer.start
  403. //
  404. start: function(port)
  405. {
  406. this._start(port, "localhost")
  407. },
  408. _start: function(port, host)
  409. {
  410. if (this._socket)
  411. throw Cr.NS_ERROR_ALREADY_INITIALIZED;
  412. this._port = port;
  413. this._doQuit = this._socketClosed = false;
  414. this._host = host;
  415. // The listen queue needs to be long enough to handle
  416. // network.http.max-persistent-connections-per-server concurrent connections,
  417. // plus a safety margin in case some other process is talking to
  418. // the server as well.
  419. var prefs = getRootPrefBranch();
  420. var maxConnections;
  421. try {
  422. // Bug 776860: The original pref was removed in favor of this new one:
  423. maxConnections = prefs.getIntPref("network.http.max-persistent-connections-per-server") + 5;
  424. }
  425. catch(e) {
  426. maxConnections = prefs.getIntPref("network.http.max-connections-per-server") + 5;
  427. }
  428. try
  429. {
  430. var loopback = true;
  431. if (this._host != "127.0.0.1" && this._host != "localhost") {
  432. var loopback = false;
  433. }
  434. var socket = new ServerSocket(this._port,
  435. loopback, // true = localhost, false = everybody
  436. maxConnections);
  437. dumpn(">>> listening on port " + socket.port + ", " + maxConnections +
  438. " pending connections");
  439. socket.asyncListen(this);
  440. this._identity._initialize(socket.port, host, true);
  441. this._socket = socket;
  442. }
  443. catch (e)
  444. {
  445. dumpn("!!! could not start server on port " + port + ": " + e);
  446. throw Cr.NS_ERROR_NOT_AVAILABLE;
  447. }
  448. },
  449. //
  450. // see nsIHttpServer.stop
  451. //
  452. stop: function(callback)
  453. {
  454. if (!callback)
  455. throw Cr.NS_ERROR_NULL_POINTER;
  456. if (!this._socket)
  457. throw Cr.NS_ERROR_UNEXPECTED;
  458. this._stopCallback = typeof callback === "function"
  459. ? callback
  460. : function() { callback.onStopped(); };
  461. dumpn(">>> stopping listening on port " + this._socket.port);
  462. this._socket.close();
  463. this._socket = null;
  464. // We can't have this identity any more, and the port on which we're running
  465. // this server now could be meaningless the next time around.
  466. this._identity._teardown();
  467. this._doQuit = false;
  468. // socket-close notification and pending request completion happen async
  469. },
  470. //
  471. // see nsIHttpServer.registerFile
  472. //
  473. registerFile: function(path, file)
  474. {
  475. if (file && (!file.exists() || file.isDirectory()))
  476. throw Cr.NS_ERROR_INVALID_ARG;
  477. this._handler.registerFile(path, file);
  478. },
  479. //
  480. // see nsIHttpServer.registerDirectory
  481. //
  482. registerDirectory: function(path, directory)
  483. {
  484. // XXX true path validation!
  485. if (path.charAt(0) != "/" ||
  486. path.charAt(path.length - 1) != "/" ||
  487. (directory &&
  488. (!directory.exists() || !directory.isDirectory())))
  489. throw Cr.NS_ERROR_INVALID_ARG;
  490. // XXX determine behavior of nonexistent /foo/bar when a /foo/bar/ mapping
  491. // exists!
  492. this._handler.registerDirectory(path, directory);
  493. },
  494. //
  495. // see nsIHttpServer.registerPathHandler
  496. //
  497. registerPathHandler: function(path, handler)
  498. {
  499. this._handler.registerPathHandler(path, handler);
  500. },
  501. //
  502. // see nsIHttpServer.registerPrefixHandler
  503. //
  504. registerPrefixHandler: function(prefix, handler)
  505. {
  506. this._handler.registerPrefixHandler(prefix, handler);
  507. },
  508. //
  509. // see nsIHttpServer.registerErrorHandler
  510. //
  511. registerErrorHandler: function(code, handler)
  512. {
  513. this._handler.registerErrorHandler(code, handler);
  514. },
  515. //
  516. // see nsIHttpServer.setIndexHandler
  517. //
  518. setIndexHandler: function(handler)
  519. {
  520. this._handler.setIndexHandler(handler);
  521. },
  522. //
  523. // see nsIHttpServer.registerContentType
  524. //
  525. registerContentType: function(ext, type)
  526. {
  527. this._handler.registerContentType(ext, type);
  528. },
  529. //
  530. // see nsIHttpServer.serverIdentity
  531. //
  532. get identity()
  533. {
  534. return this._identity;
  535. },
  536. //
  537. // see nsIHttpServer.getState
  538. //
  539. getState: function(path, k)
  540. {
  541. return this._handler._getState(path, k);
  542. },
  543. //
  544. // see nsIHttpServer.setState
  545. //
  546. setState: function(path, k, v)
  547. {
  548. return this._handler._setState(path, k, v);
  549. },
  550. //
  551. // see nsIHttpServer.getSharedState
  552. //
  553. getSharedState: function(k)
  554. {
  555. return this._handler._getSharedState(k);
  556. },
  557. //
  558. // see nsIHttpServer.setSharedState
  559. //
  560. setSharedState: function(k, v)
  561. {
  562. return this._handler._setSharedState(k, v);
  563. },
  564. //
  565. // see nsIHttpServer.getObjectState
  566. //
  567. getObjectState: function(k)
  568. {
  569. return this._handler._getObjectState(k);
  570. },
  571. //
  572. // see nsIHttpServer.setObjectState
  573. //
  574. setObjectState: function(k, v)
  575. {
  576. return this._handler._setObjectState(k, v);
  577. },
  578. // NSISUPPORTS
  579. //
  580. // see nsISupports.QueryInterface
  581. //
  582. QueryInterface: function(iid)
  583. {
  584. if (iid.equals(Ci.nsIServerSocketListener) || iid.equals(Ci.nsISupports))
  585. return this;
  586. throw Cr.NS_ERROR_NO_INTERFACE;
  587. },
  588. // NON-XPCOM PUBLIC API
  589. /**
  590. * Returns true iff this server is not running (and is not in the process of
  591. * serving any requests still to be processed when the server was last
  592. * stopped after being run).
  593. */
  594. isStopped: function()
  595. {
  596. return this._socketClosed && !this._hasOpenConnections();
  597. },
  598. // PRIVATE IMPLEMENTATION
  599. /** True if this server has any open connections to it, false otherwise. */
  600. _hasOpenConnections: function()
  601. {
  602. //
  603. // If we have any open connections, they're tracked as numeric properties on
  604. // |this._connections|. The non-standard __count__ property could be used
  605. // to check whether there are any properties, but standard-wise, even
  606. // looking forward to ES5, there's no less ugly yet still O(1) way to do
  607. // this.
  608. //
  609. for (var n in this._connections)
  610. return true;
  611. return false;
  612. },
  613. /** Calls the server-stopped callback provided when stop() was called. */
  614. _notifyStopped: function()
  615. {
  616. NS_ASSERT(this._stopCallback !== null, "double-notifying?");
  617. NS_ASSERT(!this._hasOpenConnections(), "should be done serving by now");
  618. //
  619. // NB: We have to grab this now, null out the member, *then* call the
  620. // callback here, or otherwise the callback could (indirectly) futz with
  621. // this._stopCallback by starting and immediately stopping this, at
  622. // which point we'd be nulling out a field we no longer have a right to
  623. // modify.
  624. //
  625. var callback = this._stopCallback;
  626. this._stopCallback = null;
  627. try
  628. {
  629. callback();
  630. }
  631. catch (e)
  632. {
  633. // not throwing because this is specified as being usually (but not
  634. // always) asynchronous
  635. dump("!!! error running onStopped callback: " + e + "\n");
  636. }
  637. },
  638. /**
  639. * Notifies this server that the given connection has been closed.
  640. *
  641. * @param connection : Connection
  642. * the connection that was closed
  643. */
  644. _connectionClosed: function(connection)
  645. {
  646. NS_ASSERT(connection.number in this._connections,
  647. "closing a connection " + this + " that we never added to the " +
  648. "set of open connections?");
  649. NS_ASSERT(this._connections[connection.number] === connection,
  650. "connection number mismatch? " +
  651. this._connections[connection.number]);
  652. delete this._connections[connection.number];
  653. // Fire a pending server-stopped notification if it's our responsibility.
  654. if (!this._hasOpenConnections() && this._socketClosed)
  655. this._notifyStopped();
  656. },
  657. /**
  658. * Requests that the server be shut down when possible.
  659. */
  660. _requestQuit: function()
  661. {
  662. dumpn(">>> requesting a quit");
  663. dumpStack();
  664. this._doQuit = true;
  665. }
  666. };
  667. //
  668. // RFC 2396 section 3.2.2:
  669. //
  670. // host = hostname | IPv4address
  671. // hostname = *( domainlabel "." ) toplabel [ "." ]
  672. // domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum
  673. // toplabel = alpha | alpha *( alphanum | "-" ) alphanum
  674. // IPv4address = 1*digit "." 1*digit "." 1*digit "." 1*digit
  675. //
  676. const HOST_REGEX =
  677. new RegExp("^(?:" +
  678. // *( domainlabel "." )
  679. "(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)*" +
  680. // toplabel
  681. "[a-z](?:[a-z0-9-]*[a-z0-9])?" +
  682. "|" +
  683. // IPv4 address
  684. "\\d+\\.\\d+\\.\\d+\\.\\d+" +
  685. ")$",
  686. "i");
  687. /**
  688. * Represents the identity of a server. An identity consists of a set of
  689. * (scheme, host, port) tuples denoted as locations (allowing a single server to
  690. * serve multiple sites or to be used behind both HTTP and HTTPS proxies for any
  691. * host/port). Any incoming request must be to one of these locations, or it
  692. * will be rejected with an HTTP 400 error. One location, denoted as the
  693. * primary location, is the location assigned in contexts where a location
  694. * cannot otherwise be endogenously derived, such as for HTTP/1.0 requests.
  695. *
  696. * A single identity may contain at most one location per unique host/port pair;
  697. * other than that, no restrictions are placed upon what locations may
  698. * constitute an identity.
  699. */
  700. function ServerIdentity()
  701. {
  702. /** The scheme of the primary location. */
  703. this._primaryScheme = "http";
  704. /** The hostname of the primary location. */
  705. this._primaryHost = "127.0.0.1"
  706. /** The port number of the primary location. */
  707. this._primaryPort = -1;
  708. /**
  709. * The current port number for the corresponding server, stored so that a new
  710. * primary location can always be set if the current one is removed.
  711. */
  712. this._defaultPort = -1;
  713. /**
  714. * Maps hosts to maps of ports to schemes, e.g. the following would represent
  715. * https://example.com:789/ and http://example.org/:
  716. *
  717. * {
  718. * "xexample.com": { 789: "https" },
  719. * "xexample.org": { 80: "http" }
  720. * }
  721. *
  722. * Note the "x" prefix on hostnames, which prevents collisions with special
  723. * JS names like "prototype".
  724. */
  725. this._locations = { "xlocalhost": {} };
  726. }
  727. ServerIdentity.prototype =
  728. {
  729. // NSIHTTPSERVERIDENTITY
  730. //
  731. // see nsIHttpServerIdentity.primaryScheme
  732. //
  733. get primaryScheme()
  734. {
  735. if (this._primaryPort === -1)
  736. throw Cr.NS_ERROR_NOT_INITIALIZED;
  737. return this._primaryScheme;
  738. },
  739. //
  740. // see nsIHttpServerIdentity.primaryHost
  741. //
  742. get primaryHost()
  743. {
  744. if (this._primaryPort === -1)
  745. throw Cr.NS_ERROR_NOT_INITIALIZED;
  746. return this._primaryHost;
  747. },
  748. //
  749. // see nsIHttpServerIdentity.primaryPort
  750. //
  751. get primaryPort()
  752. {
  753. if (this._primaryPort === -1)
  754. throw Cr.NS_ERROR_NOT_INITIALIZED;
  755. return this._primaryPort;
  756. },
  757. //
  758. // see nsIHttpServerIdentity.add
  759. //
  760. add: function(scheme, host, port)
  761. {
  762. this._validate(scheme, host, port);
  763. var entry = this._locations["x" + host];
  764. if (!entry)
  765. this._locations["x" + host] = entry = {};
  766. entry[port] = scheme;
  767. },
  768. //
  769. // see nsIHttpServerIdentity.remove
  770. //
  771. remove: function(scheme, host, port)
  772. {
  773. this._validate(scheme, host, port);
  774. var entry = this._locations["x" + host];
  775. if (!entry)
  776. return false;
  777. var present = port in entry;
  778. delete entry[port];
  779. if (this._primaryScheme == scheme &&
  780. this._primaryHost == host &&
  781. this._primaryPort == port &&
  782. this._defaultPort !== -1)
  783. {
  784. // Always keep at least one identity in existence at any time, unless
  785. // we're in the process of shutting down (the last condition above).
  786. this._primaryPort = -1;
  787. this._initialize(this._defaultPort, host, false);
  788. }
  789. return present;
  790. },
  791. //
  792. // see nsIHttpServerIdentity.has
  793. //
  794. has: function(scheme, host, port)
  795. {
  796. this._validate(scheme, host, port);
  797. return "x" + host in this._locations &&
  798. scheme === this._locations["x" + host][port];
  799. },
  800. //
  801. // see nsIHttpServerIdentity.has
  802. //
  803. getScheme: function(host, port)
  804. {
  805. this._validate("http", host, port);
  806. var entry = this._locations["x" + host];
  807. if (!entry)
  808. return "";
  809. return entry[port] || "";
  810. },
  811. //
  812. // see nsIHttpServerIdentity.setPrimary
  813. //
  814. setPrimary: function(scheme, host, port)
  815. {
  816. this._validate(scheme, host, port);
  817. this.add(scheme, host, port);
  818. this._primaryScheme = scheme;
  819. this._primaryHost = host;
  820. this._primaryPort = port;
  821. },
  822. // NSISUPPORTS
  823. //
  824. // see nsISupports.QueryInterface
  825. //
  826. QueryInterface: function(iid)
  827. {
  828. if (iid.equals(Ci.nsIHttpServerIdentity) || iid.equals(Ci.nsISupports))
  829. return this;
  830. throw Cr.NS_ERROR_NO_INTERFACE;
  831. },
  832. // PRIVATE IMPLEMENTATION
  833. /**
  834. * Initializes the primary name for the corresponding server, based on the
  835. * provided port number.
  836. */
  837. _initialize: function(port, host, addSecondaryDefault)
  838. {
  839. this._host = host;
  840. if (this._primaryPort !== -1)
  841. this.add("http", host, port);
  842. else
  843. this.setPrimary("http", "localhost", port);
  844. this._defaultPort = port;
  845. // Only add this if we're being called at server startup
  846. if (addSecondaryDefault && host != "127.0.0.1")
  847. this.add("http", "127.0.0.1", port);
  848. },
  849. /**
  850. * Called at server shutdown time, unsets the primary location only if it was
  851. * the default-assigned location and removes the default location from the
  852. * set of locations used.
  853. */
  854. _teardown: function()
  855. {
  856. if (this._host != "127.0.0.1") {
  857. // Not the default primary location, nothing special to do here
  858. this.remove("http", "127.0.0.1", this._defaultPort);
  859. }
  860. // This is a *very* tricky bit of reasoning here; make absolutely sure the
  861. // tests for this code pass before you commit changes to it.
  862. if (this._primaryScheme == "http" &&
  863. this._primaryHost == this._host &&
  864. this._primaryPort == this._defaultPort)
  865. {
  866. // Make sure we don't trigger the readding logic in .remove(), then remove
  867. // the default location.
  868. var port = this._defaultPort;
  869. this._defaultPort = -1;
  870. this.remove("http", this._host, port);
  871. // Ensure a server start triggers the setPrimary() path in ._initialize()
  872. this._primaryPort = -1;
  873. }
  874. else
  875. {
  876. // No reason not to remove directly as it's not our primary location
  877. this.remove("http", this._host, this._defaultPort);
  878. }
  879. },
  880. /**
  881. * Ensures scheme, host, and port are all valid with respect to RFC 2396.
  882. *
  883. * @throws NS_ERROR_ILLEGAL_VALUE
  884. * if any argument doesn't match the corresponding production
  885. */
  886. _validate: function(scheme, host, port)
  887. {
  888. if (scheme !== "http" && scheme !== "https")
  889. {
  890. dumpn("*** server only supports http/https schemes: '" + scheme + "'");
  891. dumpStack();
  892. throw Cr.NS_ERROR_ILLEGAL_VALUE;
  893. }
  894. if (!HOST_REGEX.test(host))
  895. {
  896. dumpn("*** unexpected host: '" + host + "'");
  897. throw Cr.NS_ERROR_ILLEGAL_VALUE;
  898. }
  899. if (port < 0 || port > 65535)
  900. {
  901. dumpn("*** unexpected port: '" + port + "'");
  902. throw Cr.NS_ERROR_ILLEGAL_VALUE;
  903. }
  904. }
  905. };
  906. /**
  907. * Represents a connection to the server (and possibly in the future the thread
  908. * on which the connection is processed).
  909. *
  910. * @param input : nsIInputStream
  911. * stream from which incoming data on the connection is read
  912. * @param output : nsIOutputStream
  913. * stream to write data out the connection
  914. * @param server : nsHttpServer
  915. * the server handling the connection
  916. * @param port : int
  917. * the port on which the server is running
  918. * @param outgoingPort : int
  919. * the outgoing port used by this connection
  920. * @param number : uint
  921. * a serial number used to uniquely identify this connection
  922. */
  923. function Connection(input, output, server, port, outgoingPort, number)
  924. {
  925. dumpn("*** opening new connection " + number + " on port " + outgoingPort);
  926. /** Stream of incoming data. */
  927. this.input = input;
  928. /** Stream for outgoing data. */
  929. this.output = output;
  930. /** The server associated with this request. */
  931. this.server = server;
  932. /** The port on which the server is running. */
  933. this.port = port;
  934. /** The outgoing poort used by this connection. */
  935. this._outgoingPort = outgoingPort;
  936. /** The serial number of this connection. */
  937. this.number = number;
  938. /**
  939. * The request for which a response is being generated, null if the
  940. * incoming request has not been fully received or if it had errors.
  941. */
  942. this.request = null;
  943. /** State variables for debugging. */
  944. this._closed = this._processed = false;
  945. }
  946. Connection.prototype =
  947. {
  948. /** Closes this connection's input/output streams. */
  949. close: function()
  950. {
  951. dumpn("*** closing connection " + this.number +
  952. " on port " + this._outgoingPort);
  953. this.input.close();
  954. this.output.close();
  955. this._closed = true;
  956. var server = this.server;
  957. server._connectionClosed(this);
  958. // If an error triggered a server shutdown, act on it now
  959. if (server._doQuit)
  960. server.stop(function() { /* not like we can do anything better */ });
  961. },
  962. /**
  963. * Initiates processing of this connection, using the data in the given
  964. * request.
  965. *
  966. * @param request : Request
  967. * the request which should be processed
  968. */
  969. process: function(request)
  970. {
  971. NS_ASSERT(!this._closed && !this._processed);
  972. this._processed = true;
  973. this.request = request;
  974. this.server._handler.handleResponse(this);
  975. },
  976. /**
  977. * Initiates processing of this connection, generating a response with the
  978. * given HTTP error code.
  979. *
  980. * @param code : uint
  981. * an HTTP code, so in the range [0, 1000)
  982. * @param request : Request
  983. * incomplete data about the incoming request (since there were errors
  984. * during its processing
  985. */
  986. processError: function(code, request)
  987. {
  988. NS_ASSERT(!this._closed && !this._processed);
  989. this._processed = true;
  990. this.request = request;
  991. this.server._handler.handleError(code, this);
  992. },
  993. /** Converts this to a string for debugging purposes. */
  994. toString: function()
  995. {
  996. return "<Connection(" + this.number +
  997. (this.request ? ", " + this.request.path : "") +"): " +
  998. (this._closed ? "closed" : "open") + ">";
  999. }
  1000. };
  1001. /** Returns an array of count bytes from the given input stream. */
  1002. function readBytes(inputStream, count)
  1003. {
  1004. return new BinaryInputStream(inputStream).readByteArray(count);
  1005. }
  1006. /** Request reader processing states; see RequestReader for details. */
  1007. const READER_IN_REQUEST_LINE = 0;
  1008. const READER_IN_HEADERS = 1;
  1009. const READER_IN_BODY = 2;
  1010. const READER_FINISHED = 3;
  1011. /**
  1012. * Reads incoming request data asynchronously, does any necessary preprocessing,
  1013. * and forwards it to the request handler. Processing occurs in three states:
  1014. *
  1015. * READER_IN_REQUEST_LINE Reading the request's status line
  1016. * READER_IN_HEADERS Reading headers in the request
  1017. * READER_IN_BODY Reading the body of the request
  1018. * READER_FINISHED Entire request has been read and processed
  1019. *
  1020. * During the first two stages, initial metadata about the request is gathered
  1021. * into a Request object. Once the status line and headers have been processed,
  1022. * we start processing the body of the request into the Request. Finally, when
  1023. * the entire body has been read, we create a Response and hand it off to the
  1024. * ServerHandler to be given to the appropriate request handler.
  1025. *
  1026. * @param connection : Connection
  1027. * the connection for the request being read
  1028. */
  1029. function RequestReader(connection)
  1030. {
  1031. /** Connection metadata for this request. */
  1032. this._connection = connection;
  1033. /**
  1034. * A container providing line-by-line access to the raw bytes that make up the
  1035. * data which has been read from the connection but has not yet been acted
  1036. * upon (by passing it to the request handler or by extracting request
  1037. * metadata from it).
  1038. */
  1039. this._data = new LineData();
  1040. /**
  1041. * The amount of data remaining to be read from the body of this request.
  1042. * After all headers in the request have been read this is the value in the
  1043. * Content-Length header, but as the body is read its value decreases to zero.
  1044. */
  1045. this._contentLength = 0;
  1046. /** The current state of parsing the incoming request. */
  1047. this._state = READER_IN_REQUEST_LINE;
  1048. /** Metadata constructed from the incoming request for the request handler. */
  1049. this._metadata = new Request(connection.port);
  1050. /**
  1051. * Used to preserve state if we run out of line data midway through a
  1052. * multi-line header. _lastHeaderName stores the name of the header, while
  1053. * _lastHeaderValue stores the value we've seen so far for the header.
  1054. *
  1055. * These fields are always either both undefined or both strings.
  1056. */
  1057. this._lastHeaderName = this._lastHeaderValue = undefined;
  1058. }
  1059. RequestReader.prototype =
  1060. {
  1061. // NSIINPUTSTREAMCALLBACK
  1062. /**
  1063. * Called when more data from the incoming request is available. This method
  1064. * then reads the available data from input and deals with that data as
  1065. * necessary, depending upon the syntax of already-downloaded data.
  1066. *
  1067. * @param input : nsIAsyncInputStream
  1068. * the stream of incoming data from the connection
  1069. */
  1070. onInputStreamReady: function(input)
  1071. {
  1072. dumpn("*** onInputStreamReady(input=" + input + ") on thread " +
  1073. gThreadManager.currentThread + " (main is " +
  1074. gThreadManager.mainThread + ")");
  1075. dumpn("*** this._state == " + this._state);
  1076. // Handle cases where we get more data after a request error has been
  1077. // discovered but *before* we can close the connection.
  1078. var data = this._data;
  1079. if (!data)
  1080. return;
  1081. try
  1082. {
  1083. data.appendBytes(readBytes(input, input.available()));
  1084. }
  1085. catch (e)
  1086. {
  1087. if (streamClosed(e))
  1088. {
  1089. dumpn("*** WARNING: unexpected error when reading from socket; will " +
  1090. "be treated as if the input stream had been closed");
  1091. dumpn("*** WARNING: actual error was: " + e);
  1092. }
  1093. // We've lost a race -- input has been closed, but we're still expecting
  1094. // to read more data. available() will throw in this case, and since
  1095. // we're dead in the water now, destroy the connection.
  1096. dumpn("*** onInputStreamReady called on a closed input, destroying " +
  1097. "connection");
  1098. this._connection.close();
  1099. return;
  1100. }
  1101. switch (this._state)
  1102. {
  1103. default:
  1104. NS_ASSERT(false, "invalid state: " + this._state);
  1105. break;
  1106. case READER_IN_REQUEST_LINE:
  1107. if (!this._processRequestLine())
  1108. break;
  1109. /* fall through */
  1110. case READER_IN_HEADERS:
  1111. if (!this._processHeaders())
  1112. break;
  1113. /* fall through */
  1114. case READER_IN_BODY:
  1115. this._processBody();
  1116. }
  1117. if (this._state != READER_FINISHED)
  1118. input.asyncWait(this, 0, 0, gThreadManager.currentThread);
  1119. },
  1120. //
  1121. // see nsISupports.QueryInterface
  1122. //
  1123. QueryInterface: function(aIID)
  1124. {
  1125. if (aIID.equals(Ci.nsIInputStreamCallback) ||
  1126. aIID.equals(Ci.nsISupports))
  1127. return this;
  1128. throw Cr.NS_ERROR_NO_INTERFACE;
  1129. },
  1130. // PRIVATE API
  1131. /**
  1132. * Processes unprocessed, downloaded data as a request line.
  1133. *
  1134. * @returns boolean
  1135. * true iff the request line has been fully processed
  1136. */
  1137. _processRequestLine: function()
  1138. {
  1139. NS_ASSERT(this._state == READER_IN_REQUEST_LINE);
  1140. // Servers SHOULD ignore any empty line(s) received where a Request-Line
  1141. // is expected (section 4.1).
  1142. var data = this._data;
  1143. var line = {};
  1144. var readSuccess;
  1145. while ((readSuccess = data.readLine(line)) && line.value == "")
  1146. dumpn("*** ignoring beginning blank line...");
  1147. // if we don't have a full line, wait until we do
  1148. if (!readSuccess)
  1149. return false;
  1150. // we have the first non-blank line
  1151. try
  1152. {
  1153. this._parseRequestLine(line.value);
  1154. this._state = READER_IN_HEADERS;
  1155. return true;
  1156. }
  1157. catch (e)
  1158. {
  1159. this._handleError(e);
  1160. return false;
  1161. }
  1162. },
  1163. /**
  1164. * Processes stored data, assuming it is either at the beginning or in
  1165. * the middle of processing request headers.
  1166. *
  1167. * @returns boolean
  1168. * true iff header data in the request has been fully processed
  1169. */
  1170. _processHeaders: function()
  1171. {
  1172. NS_ASSERT(this._state == READER_IN_HEADERS);
  1173. // XXX things to fix here:
  1174. //
  1175. // - need to support RFC 2047-encoded non-US-ASCII characters
  1176. try
  1177. {
  1178. var done = this._parseHeaders();
  1179. if (done)
  1180. {
  1181. var request = this._metadata;
  1182. // XXX this is wrong for requests with transfer-encodings applied to
  1183. // them, particularly chunked (which by its nature can have no
  1184. // meaningful Content-Length header)!
  1185. this._contentLength = request.hasHeader("Content-Length")
  1186. ? parseInt(request.getHeader("Content-Length"), 10)
  1187. : 0;
  1188. dumpn("_processHeaders, Content-length=" + this._contentLength);
  1189. this._state = READER_IN_BODY;
  1190. }
  1191. return done;
  1192. }
  1193. catch (e)
  1194. {
  1195. this._handleError(e);
  1196. return false;
  1197. }
  1198. },
  1199. /**
  1200. * Processes stored data, assuming it is either at the beginning or in
  1201. * the middle of processing the request body.
  1202. *
  1203. * @returns boolean
  1204. * true iff the request body has been fully processed
  1205. */
  1206. _processBody: function()
  1207. {
  1208. NS_ASSERT(this._state == READER_IN_BODY);
  1209. // XXX handle chunked transfer-coding request bodies!
  1210. try
  1211. {
  1212. if (this._contentLength > 0)
  1213. {
  1214. var data = this._data.purge();
  1215. var count = Math.min(data.length, this._contentLength);
  1216. dumpn("*** loading data=" + data + " len=" + data.length +
  1217. " excess=" + (data.length - count));
  1218. var bos = new BinaryOutputStream(this._metadata._bodyOutputStream);
  1219. bos.writeByteArray(data, count);
  1220. this._contentLength -= count;
  1221. }
  1222. dumpn("*** remaining body data len=" + this._contentLength);
  1223. if (this._contentLength == 0)
  1224. {
  1225. this._validateRequest();
  1226. this._state = READER_FINISHED;
  1227. this._handleResponse();
  1228. return true;
  1229. }
  1230. return false;
  1231. }
  1232. catch (e)
  1233. {
  1234. this._handleError(e);
  1235. return false;
  1236. }
  1237. },
  1238. /**
  1239. * Does various post-header checks on the data in this request.
  1240. *
  1241. * @throws : HttpError
  1242. * if the request was malformed in some way
  1243. */
  1244. _validateRequest: function()
  1245. {
  1246. NS_ASSERT(this._state == READER_IN_BODY);
  1247. dumpn("*** _validateRequest");
  1248. var metadata = this._metadata;
  1249. var headers = metadata._headers;
  1250. // 19.6.1.1 -- servers MUST report 400 to HTTP/1.1 requests w/o Host header
  1251. var identity = this._connection.server.identity;
  1252. if (metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_1))
  1253. {
  1254. if (!headers.hasHeader("Host"))
  1255. {
  1256. dumpn("*** malformed HTTP/1.1 or greater request with no Host header!");
  1257. throw HTTP_400;
  1258. }
  1259. // If the Request-URI wasn't absolute, then we need to determine our host.
  1260. // We have to determine what scheme was used to access us based on the
  1261. // server identity data at this point, because the request just doesn't
  1262. // contain enough data on its own to do this, sadly.
  1263. if (!metadata._host)
  1264. {
  1265. var host, port;
  1266. var hostPort = headers.getHeader("Host");
  1267. var colon = hostPort.indexOf(":");
  1268. if (colon < 0)
  1269. {
  1270. host = hostPort;
  1271. port = "";
  1272. }
  1273. else
  1274. {
  1275. host = hostPort.substring(0, colon);
  1276. port = hostPort.substring(colon + 1);
  1277. }
  1278. // NB: We allow an empty port here because, oddly, a colon may be
  1279. // present even without a port number, e.g. "example.com:"; in this
  1280. // case the default port applies.
  1281. if (!HOST_REGEX.test(host) || !/^\d*$/.test(port))
  1282. {
  1283. dumpn("*** malformed hostname (" + hostPort + ") in Host " +
  1284. "header, 400 time");
  1285. throw HTTP_400;
  1286. }
  1287. // If we're not given a port, we're stuck, because we don't know what
  1288. // scheme to use to look up the correct port here, in general. Since
  1289. // the HTTPS case requires a tunnel/proxy and thus requires that the
  1290. // requested URI be absolute (and thus contain the necessary
  1291. // information), let's assume HTTP will prevail and use that.
  1292. port = +port || 80;
  1293. var scheme = identity.getScheme(host, port);
  1294. if (!scheme)
  1295. {
  1296. dumpn("*** unrecognized hostname (" + hostPort + ") in Host " +
  1297. "header, 400 time");
  1298. throw HTTP_400;
  1299. }
  1300. metadata._scheme = scheme;
  1301. metadata._host = host;
  1302. metadata._port = port;
  1303. }
  1304. }
  1305. else
  1306. {
  1307. NS_ASSERT(metadata._host === undefined,
  1308. "HTTP/1.0 doesn't allow absolute paths in the request line!");
  1309. metadata._scheme = identity.primaryScheme;
  1310. metadata._host = identity.primaryHost;
  1311. metadata._port = identity.primaryPort;
  1312. }
  1313. NS_ASSERT(identity.has(metadata._scheme, metadata._host, metadata._port),
  1314. "must have a location we recognize by now!");
  1315. },
  1316. /**
  1317. * Handles responses in case of error, either in the server or in the request.
  1318. *
  1319. * @param e
  1320. * the specific error encountered, which is an HttpError in the case where
  1321. * the request is in some way invalid or cannot be fulfilled; if this isn't
  1322. * an HttpError we're going to be paranoid and shut down, because that
  1323. * shouldn't happen, ever
  1324. */
  1325. _handleError: function(e)
  1326. {
  1327. // Don't fall back into normal processing!
  1328. this._state = READER_FINISHED;
  1329. var server = this._connection.server;
  1330. if (e instanceof HttpError)
  1331. {
  1332. var code = e.code;
  1333. }
  1334. else
  1335. {
  1336. dumpn("!!! UNEXPECTED ERROR: " + e +
  1337. (e.lineNumber ? ", line " + e.lineNumber : ""));
  1338. // no idea what happened -- be paranoid and shut down
  1339. code = 500;
  1340. server._requestQuit();
  1341. }
  1342. // make attempted reuse of data an error
  1343. this._data = null;
  1344. this._connection.processError(code, this._metadata);
  1345. },
  1346. /**
  1347. * Now that we've read the request line and headers, we can actually hand off
  1348. * the request to be handled.
  1349. *
  1350. * This method is called once per request, after the request line and all
  1351. * headers and the body, if any, have been received.
  1352. */
  1353. _handleResponse: function()
  1354. {
  1355. NS_ASSERT(this._state == READER_FINISHED);
  1356. // We don't need the line-based data any more, so make attempted reuse an
  1357. // error.
  1358. this._data = null;
  1359. this._connection.process(this._metadata);
  1360. },
  1361. // PARSING
  1362. /**
  1363. * Parses the request line for the HTTP request associated with this.
  1364. *
  1365. * @param line : string
  1366. * the request line
  1367. */
  1368. _parseRequestLine: function(line)
  1369. {
  1370. NS_ASSERT(this._state == READER_IN_REQUEST_LINE);
  1371. dumpn("*** _parseRequestLine('" + line + "')");
  1372. var metadata = this._metadata;
  1373. // clients and servers SHOULD accept any amount of SP or HT characters
  1374. // between fields, even though only a single SP is required (section 19.3)
  1375. var request = line.split(/[ \t]+/);
  1376. if (!request || request.length != 3)
  1377. throw HTTP_400;
  1378. metadata._method = request[0];
  1379. // get the HTTP version
  1380. var ver = request[2];
  1381. var match = ver.match(/^HTTP\/(\d+\.\d+)$/);
  1382. if (!match)
  1383. throw HTTP_400;
  1384. // determine HTTP version
  1385. try
  1386. {
  1387. metadata._httpVersion = new nsHttpVersion(match[1]);
  1388. if (!metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_0))
  1389. throw "unsupported HTTP version";
  1390. }
  1391. catch (e)
  1392. {
  1393. // we support HTTP/1.0 and HTTP/1.1 only
  1394. throw HTTP_501;
  1395. }
  1396. var fullPath = request[1];
  1397. var serverIdentity = this._connection.server.identity;
  1398. var scheme, host, port;
  1399. if (fullPath.charAt(0) != "/")
  1400. {
  1401. // No absolute paths in the request line in HTTP prior to 1.1
  1402. if (!metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_1))
  1403. throw HTTP_400;
  1404. try
  1405. {
  1406. var uri = Cc["@mozilla.org/network/io-service;1"]
  1407. .getService(Ci.nsIIOService)
  1408. .newURI(fullPath, null, null);
  1409. fullPath = uri.path;
  1410. scheme = uri.scheme;
  1411. host = metadata._host = uri.asciiHost;
  1412. port = uri.port;
  1413. if (port === -1)
  1414. {
  1415. if (scheme === "http")
  1416. port = 80;
  1417. else if (scheme === "https")
  1418. port = 443;
  1419. else
  1420. throw HTTP_400;
  1421. }
  1422. }
  1423. catch (e)
  1424. {
  1425. // If the host is not a valid host on the server, the response MUST be a
  1426. // 400 (Bad Request) error message (section 5.2). Alternately, the URI
  1427. // is malformed.
  1428. throw HTTP_400;
  1429. }
  1430. if (!serverIdentity.has(scheme, host, port) || fullPath.charAt(0) != "/")
  1431. throw HTTP_400;
  1432. }
  1433. var splitter = fullPath.indexOf("?");
  1434. if (splitter < 0)
  1435. {
  1436. // _queryString already set in ctor
  1437. metadata._path = fullPath;
  1438. }
  1439. else
  1440. {
  1441. metadata._path = fullPath.substring(0, splitter);
  1442. metadata._queryString = fullPath.substring(splitter + 1);
  1443. }
  1444. metadata._scheme = scheme;
  1445. metadata._host = host;
  1446. metadata._port = port;
  1447. },
  1448. /**
  1449. * Parses all available HTTP headers in this until the header-ending CRLFCRLF,
  1450. * adding them to the store of headers in the request.
  1451. *
  1452. * @throws
  1453. * HTTP_400 if the headers are malformed
  1454. * @returns boolean
  1455. * true if all headers have now been processed, false otherwise
  1456. */
  1457. _parseHeaders: function()
  1458. {
  1459. NS_ASSERT(this._state == READER_IN_HEADERS);
  1460. dumpn("*** _parseHeaders");
  1461. var data = this._data;
  1462. var headers = this._metadata._headers;
  1463. var lastName = this._lastHeaderName;
  1464. var lastVal = this._lastHeaderValue;
  1465. var line = {};
  1466. while (true)
  1467. {
  1468. NS_ASSERT(!((lastVal === undefined) ^ (lastName === undefined)),
  1469. lastName === undefined ?
  1470. "lastVal without lastName? lastVal: '" + lastVal + "'" :
  1471. "lastName without lastVal? lastName: '" + lastName + "'");
  1472. if (!data.readLine(line))
  1473. {
  1474. // save any data we have from the header we might still be processing
  1475. this._lastHeaderName = lastName;
  1476. this._lastHeaderValue = lastVal;
  1477. return false;
  1478. }
  1479. var lineText = line.value;
  1480. var firstChar = lineText.charAt(0);
  1481. // blank line means end of headers
  1482. if (lineText == "")
  1483. {
  1484. // we're finished with the previous header
  1485. if (lastName)
  1486. {
  1487. try
  1488. {
  1489. headers.setHeader(lastName, lastVal, true);
  1490. }
  1491. catch (e)
  1492. {
  1493. dumpn("*** e == " + e);
  1494. throw HTTP_400;
  1495. }
  1496. }
  1497. else
  1498. {
  1499. // no headers in request -- valid for HTTP/1.0 requests
  1500. }
  1501. // either way, we're done processing headers
  1502. this._state = READER_IN_BODY;
  1503. return true;
  1504. }
  1505. else if (firstChar == " " || firstChar == "\t")
  1506. {
  1507. // multi-line header if we've already seen a header line
  1508. if (!lastName)
  1509. {
  1510. // we don't have a header to continue!
  1511. throw HTTP_400;
  1512. }
  1513. // append this line's text to the value; starts with SP/HT, so no need
  1514. // for separating whitespace
  1515. lastVal += lineText;
  1516. }
  1517. else
  1518. {
  1519. // we have a new header, so set the old one (if one existed)
  1520. if (lastName)
  1521. {
  1522. try
  1523. {
  1524. headers.setHeader(lastName, lastVal, true);
  1525. }
  1526. catch (e)
  1527. {
  1528. dumpn("*** e == " + e);
  1529. throw HTTP_400;
  1530. }
  1531. }
  1532. var colon = lineText.indexOf(":"); // first colon must be splitter
  1533. if (colon < 1)
  1534. {
  1535. // no colon or missing header field-name
  1536. throw HTTP_400;
  1537. }
  1538. // set header name, value (to be set in the next loop, usually)
  1539. lastName = lineText.substring(0, colon);
  1540. lastVal = lineText.substring(colon + 1);
  1541. } // empty, continuation, start of header
  1542. } // while (true)
  1543. }
  1544. };
  1545. /** The character codes for CR and LF. */
  1546. const CR = 0x0D, LF = 0x0A;
  1547. /**
  1548. * Calculates the number of characters before the first CRLF pair in array, or
  1549. * -1 if the array contains no CRLF pair.
  1550. *
  1551. * @param array : Array
  1552. * an array of numbers in the range [0, 256), each representing a single
  1553. * character; the first CRLF is the lowest index i where
  1554. * |array[i] == "\r".charCodeAt(0)| and |array[i+1] == "\n".charCodeAt(0)|,
  1555. * if such an |i| exists, and -1 otherwise
  1556. * @returns int
  1557. * the index of the first CRLF if any were present, -1 otherwise
  1558. */
  1559. function findCRLF(array)
  1560. {
  1561. for (var i = array.indexOf(CR); i >= 0; i = array.indexOf(CR, i + 1))
  1562. {
  1563. if (array[i + 1] == LF)
  1564. return i;
  1565. }
  1566. return -1;
  1567. }
  1568. /**
  1569. * A container which provides line-by-line access to the arrays of bytes with
  1570. * which it is seeded.
  1571. */
  1572. function LineData()
  1573. {
  1574. /** An array of queued bytes from which to get line-based characters. */
  1575. this._data = [];
  1576. }
  1577. LineData.prototype =
  1578. {
  1579. /**
  1580. * Appends the bytes in the given array to the internal data cache maintained
  1581. * by this.
  1582. */
  1583. appendBytes: function(bytes)
  1584. {
  1585. Array.prototype.push.apply(this._data, bytes);
  1586. },
  1587. /**
  1588. * Removes and returns a line of data, delimited by CRLF, from this.
  1589. *
  1590. * @param out
  1591. * an object whose "value" property will be set to the first line of text
  1592. * present in this, sans CRLF, if this contains a full CRLF-delimited line
  1593. * of text; if this doesn't contain enough data, the value of the property
  1594. * is undefined
  1595. * @returns boolean
  1596. * true if a full line of data could be read from the data in this, false
  1597. * otherwise
  1598. */
  1599. readLine: function(out)
  1600. {
  1601. var data = this._data;
  1602. var length = findCRLF(data);
  1603. if (length < 0)
  1604. return false;
  1605. //
  1606. // We have the index of the CR, so remove all the characters, including
  1607. // CRLF, from the array with splice, and convert the removed array into the
  1608. // corresponding string, from which we then strip the trailing CRLF.
  1609. //
  1610. // Getting the line in this matter acknowledges that substring is an O(1)
  1611. // operation in SpiderMonkey because strings are immutable, whereas two
  1612. // splices, both from the beginning of the data, are less likely to be as
  1613. // cheap as a single splice plus two extra character conversions.
  1614. //
  1615. var line = String.fromCharCode.apply(null, data.splice(0, length + 2));
  1616. out.value = line.substring(0, length);
  1617. return true;
  1618. },
  1619. /**
  1620. * Removes the bytes currently within this and returns them in an array.
  1621. *
  1622. * @returns Array
  1623. * the bytes within this when this method is called
  1624. */
  1625. purge: function()
  1626. {
  1627. var data = this._data;
  1628. this._data = [];
  1629. return data;
  1630. }
  1631. };
  1632. /**
  1633. * Creates a request-handling function for an nsIHttpRequestHandler object.
  1634. */
  1635. function createHandlerFunc(handler)
  1636. {
  1637. return function(metadata, response) { handler.handle(metadata, response); };
  1638. }
  1639. /**
  1640. * The default handler for directories; writes an HTML response containing a
  1641. * slightly-formatted directory listing.
  1642. */
  1643. function defaultIndexHandler(metadata, response)
  1644. {
  1645. response.setHeader("Content-Type", "text/html", false);
  1646. var path = htmlEscape(decodeURI(metadata.path));
  1647. //
  1648. // Just do a very basic bit of directory listings -- no need for too much
  1649. // fanciness, especially since we don't have a style sheet in which we can
  1650. // stick rules (don't want to pollute the default path-space).
  1651. //
  1652. var body = '<html>\
  1653. <head>\
  1654. <title>' + path + '</title>\
  1655. </head>\
  1656. <body>\
  1657. <h1>' + path + '</h1>\
  1658. <ol style="list-style-type: none">';
  1659. var directory = metadata.getProperty("directory").QueryInterface(Ci.nsILocalFile);
  1660. NS_ASSERT(directory && directory.isDirectory());
  1661. var fileList = [];
  1662. var files = directory.directoryEntries;
  1663. while (files.hasMoreElements())
  1664. {
  1665. var f = files.getNext().QueryInterface(Ci.nsIFile);
  1666. var name = f.leafName;
  1667. if (!f.isHidden() &&
  1668. (name.charAt(name.length - 1) != HIDDEN_CHAR ||
  1669. name.charAt(name.length - 2) == HIDDEN_CHAR))
  1670. fileList.push(f);
  1671. }
  1672. fileList.sort(fileSort);
  1673. for (var i = 0; i < fileList.length; i++)
  1674. {
  1675. var file = fileList[i];
  1676. try
  1677. {
  1678. var name = file.leafName;
  1679. if (name.charAt(name.length - 1) == HIDDEN_CHAR)
  1680. name = name.substring(0, name.length - 1);
  1681. var sep = file.isDirectory() ? "/" : "";
  1682. // Note: using " to delimit the attribute here because encodeURIComponent
  1683. // passes through '.
  1684. var item = '<li><a href="' + encodeURIComponent(name) + sep + '">' +
  1685. htmlEscape(name) + sep +
  1686. '</a></li>';
  1687. body += item;
  1688. }
  1689. catch (e) { /* some file system error, ignore the file */ }
  1690. }
  1691. body += ' </ol>\
  1692. </body>\
  1693. </html>';
  1694. response.bodyOutputStream.write(body, body.length);
  1695. }
  1696. /**
  1697. * Sorts a and b (nsIFile objects) into an aesthetically pleasing order.
  1698. */
  1699. function fileSort(a, b)
  1700. {
  1701. var dira = a.isDirectory(), dirb = b.isDirectory();
  1702. if (dira && !dirb)
  1703. return -1;
  1704. if (dirb && !dira)
  1705. return 1;
  1706. var namea = a.leafName.toLowerCase(), nameb = b.leafName.toLowerCase();
  1707. return nameb > namea ? -1 : 1;
  1708. }
  1709. /**
  1710. * Converts an externally-provided path into an internal path for use in
  1711. * determining file mappings.
  1712. *
  1713. * @param path
  1714. * the path to convert
  1715. * @param encoded
  1716. * true if the given path should be passed through decodeURI prior to
  1717. * conversion
  1718. * @throws URIError
  1719. * if path is incorrectly encoded
  1720. */
  1721. function toInternalPath(path, encoded)
  1722. {
  1723. if (encoded)
  1724. path = decodeURI(path);
  1725. var comps = path.split("/");
  1726. for (var i = 0, sz = comps.length; i < sz; i++)
  1727. {
  1728. var comp = comps[i];
  1729. if (comp.charAt(comp.length - 1) == HIDDEN_CHAR)
  1730. comps[i] = comp + HIDDEN_CHAR;
  1731. }
  1732. return comps.join("/");
  1733. }
  1734. /**
  1735. * Adds custom-specified headers for the given file to the given response, if
  1736. * any such headers are specified.
  1737. *
  1738. * @param file
  1739. * the file on the disk which is to be written
  1740. * @param metadata
  1741. * metadata about the incoming request
  1742. * @param response
  1743. * the Response to which any specified headers/data should be written
  1744. * @throws HTTP_500
  1745. * if an error occurred while processing custom-specified headers
  1746. */
  1747. function maybeAddHeaders(file, metadata, response)
  1748. {
  1749. var name = file.leafName;
  1750. if (name.charAt(name.length - 1) == HIDDEN_CHAR)
  1751. name = name.substring(0, name.length - 1);
  1752. var headerFile = file.parent;
  1753. headerFile.append(name + HEADERS_SUFFIX);
  1754. if (!headerFile.exists())
  1755. return;
  1756. const PR_RDONLY = 0x01;
  1757. var fis = new FileInputStream(headerFile, PR_RDONLY, parseInt("444", 8),
  1758. Ci.nsIFileInputStream.CLOSE_ON_EOF);
  1759. try
  1760. {
  1761. var lis = new ConverterInputStream(fis, "UTF-8", 1024, 0x0);
  1762. lis.QueryInterface(Ci.nsIUnicharLineInputStream);
  1763. var line = {value: ""};
  1764. var more = lis.readLine(line);
  1765. if (!more && line.value == "")
  1766. return;
  1767. // request line
  1768. var status = line.value;
  1769. if (status.indexOf("HTTP ") == 0)
  1770. {
  1771. status = status.substring(5);
  1772. var space = status.indexOf(" ");
  1773. var code, description;
  1774. if (space < 0)
  1775. {
  1776. code = status;
  1777. description = "";
  1778. }
  1779. else
  1780. {
  1781. code = status.substring(0, space);
  1782. description = status.substring(space + 1, status.length);
  1783. }
  1784. response.setStatusLine(metadata.httpVersion, parseInt(code, 10), description);
  1785. line.value = "";
  1786. more = lis.readLine(line);
  1787. }
  1788. // headers
  1789. while (more || line.value != "")
  1790. {
  1791. var header = line.value;
  1792. var colon = header.indexOf(":");
  1793. response.setHeader(header.substring(0, colon),
  1794. header.substring(colon + 1, header.length),
  1795. false); // allow overriding server-set headers
  1796. line.value = "";
  1797. more = lis.readLine(line);
  1798. }
  1799. }
  1800. catch (e)
  1801. {
  1802. dumpn("WARNING: error in headers for " + metadata.path + ": " + e);
  1803. throw HTTP_500;
  1804. }
  1805. finally
  1806. {
  1807. fis.close();
  1808. }
  1809. }
  1810. /**
  1811. * An object which handles requests for a server, executing default and
  1812. * overridden behaviors as instructed by the code which uses and manipulates it.
  1813. * Default behavior includes the paths / and /trace (diagnostics), with some
  1814. * support for HTTP error pages for various codes and fallback to HTTP 500 if
  1815. * those codes fail for any reason.
  1816. *
  1817. * @param server : nsHttpServer
  1818. * the server in which this handler is being used
  1819. */
  1820. function ServerHandler(server)
  1821. {
  1822. // FIELDS
  1823. /**
  1824. * The nsHttpServer instance associated with this handler.
  1825. */
  1826. this._server = server;
  1827. /**
  1828. * A FileMap object containing the set of path->nsILocalFile mappings for
  1829. * all directory mappings set in the server (e.g., "/" for /var/www/html/,
  1830. * "/foo/bar/" for /local/path/, and "/foo/bar/baz/" for /local/path2).
  1831. *
  1832. * Note carefully: the leading and trailing "/" in each path (not file) are
  1833. * removed before insertion to simplify the code which uses this. You have
  1834. * been warned!
  1835. */
  1836. this._pathDirectoryMap = new FileMap();
  1837. /**
  1838. * Custom request handlers for the server in which this resides. Path-handler
  1839. * pairs are stored as property-value pairs in this property.
  1840. *
  1841. * @see ServerHandler.prototype._defaultPaths
  1842. */
  1843. this._overridePaths = {};
  1844. /**
  1845. * Custom request handlers for the server in which this resides. Prefix-handler
  1846. * pairs are stored as property-value pairs in this property.
  1847. */
  1848. this._overridePrefixes = {};
  1849. /**
  1850. * Custom request handlers for the error handlers in the server in which this
  1851. * resides. Path-handler pairs are stored as property-value pairs in this
  1852. * property.
  1853. *
  1854. * @see ServerHandler.prototype._defaultErrors
  1855. */
  1856. this._overrideErrors = {};
  1857. /**
  1858. * Maps file extensions to their MIME types in the server, overriding any
  1859. * mapping that might or might not exist in the MIME service.
  1860. */
  1861. this._mimeMappings = {};
  1862. /**
  1863. * The default handler for requests for directories, used to serve directories
  1864. * when no index file is present.
  1865. */
  1866. this._indexHandler = defaultIndexHandler;
  1867. /** Per-path state storage for the server. */
  1868. this._state = {};
  1869. /** Entire-server state storage. */
  1870. this._sharedState = {};
  1871. /** Entire-server state storage for nsISupports values. */
  1872. this._objectState = {};
  1873. }
  1874. ServerHandler.prototype =
  1875. {
  1876. // PUBLIC API
  1877. /**
  1878. * Handles a request to this server, responding to the request appropriately
  1879. * and initiating server shutdown if necessary.
  1880. *
  1881. * This method never throws an exception.
  1882. *
  1883. * @param connection : Connection
  1884. * the connection for this request
  1885. */
  1886. handleResponse: function(connection)
  1887. {
  1888. var request = connection.request;
  1889. var response = new Response(connection);
  1890. var path = request.path;
  1891. dumpn("*** path == " + path);
  1892. try
  1893. {
  1894. try
  1895. {
  1896. if (path in this._overridePaths)
  1897. {
  1898. // explicit paths first, then files based on existing directory mappings,
  1899. // then (if the file doesn't exist) built-in server default paths
  1900. dumpn("calling override for " + path);
  1901. this._overridePaths[path](request, response);
  1902. }
  1903. else
  1904. {
  1905. let longestPrefix = "";
  1906. for (let prefix in this._overridePrefixes)
  1907. {
  1908. if (prefix.length > longestPrefix.length && path.startsWith(prefix))
  1909. {
  1910. longestPrefix = prefix;
  1911. }
  1912. }
  1913. if (longestPrefix.length > 0)
  1914. {
  1915. dumpn("calling prefix override for " + longestPrefix);
  1916. this._overridePrefixes[longestPrefix](request, response);
  1917. }
  1918. else
  1919. {
  1920. this._handleDefault(request, response);
  1921. }
  1922. }
  1923. }
  1924. catch (e)
  1925. {
  1926. if (response.partiallySent())
  1927. {
  1928. response.abort(e);
  1929. return;
  1930. }
  1931. if (!(e instanceof HttpError))
  1932. {
  1933. dumpn("*** unexpected error: e == " + e);
  1934. throw HTTP_500;
  1935. }
  1936. if (e.code !== 404)
  1937. throw e;
  1938. dumpn("*** default: " + (path in this._defaultPaths));
  1939. response = new Response(connection);
  1940. if (path in this._defaultPaths)
  1941. this._defaultPaths[path](request, response);
  1942. else
  1943. throw HTTP_404;
  1944. }
  1945. }
  1946. catch (e)
  1947. {
  1948. if (response.partiallySent())
  1949. {
  1950. response.abort(e);
  1951. return;
  1952. }
  1953. var errorCode = "internal";
  1954. try
  1955. {
  1956. if (!(e instanceof HttpError))
  1957. throw e;
  1958. errorCode = e.code;
  1959. dumpn("*** errorCode == " + errorCode);
  1960. response = new Response(connection);
  1961. if (e.customErrorHandling)
  1962. e.customErrorHandling(response);
  1963. this._handleError(errorCode, request, response);
  1964. return;
  1965. }
  1966. catch (e2)
  1967. {
  1968. dumpn("*** error handling " + errorCode + " error: " +
  1969. "e2 == " + e2 + ", shutting down server");
  1970. connection.server._requestQuit();
  1971. response.abort(e2);
  1972. return;
  1973. }
  1974. }
  1975. response.complete();
  1976. },
  1977. //
  1978. // see nsIHttpServer.registerFile
  1979. //
  1980. registerFile: function(path, file)
  1981. {
  1982. if (!file)
  1983. {
  1984. dumpn("*** unregistering '" + path + "' mapping");
  1985. delete this._overridePaths[path];
  1986. return;
  1987. }
  1988. dumpn("*** registering '" + path + "' as mapping to " + file.path);
  1989. file = file.clone();
  1990. var self = this;
  1991. this._overridePaths[path] =
  1992. function(request, response)
  1993. {
  1994. if (!file.exists())
  1995. throw HTTP_404;
  1996. response.setStatusLine(request.httpVersion, 200, "OK");
  1997. self._writeFileResponse(request, file, response, 0, file.fileSize);
  1998. };
  1999. },
  2000. //
  2001. // see nsIHttpServer.registerPathHandler
  2002. //
  2003. registerPathHandler: function(path, handler)
  2004. {
  2005. // XXX true path validation!
  2006. if (path.charAt(0) != "/")
  2007. throw Cr.NS_ERROR_INVALID_ARG;
  2008. this._handlerToField(handler, this._overridePaths, path);
  2009. },
  2010. //
  2011. // see nsIHttpServer.registerPrefixHandler
  2012. //
  2013. registerPrefixHandler: function(prefix, handler)
  2014. {
  2015. // XXX true prefix validation!
  2016. if (!(prefix.startsWith("/") && prefix.endsWith("/")))
  2017. throw Cr.NS_ERROR_INVALID_ARG;
  2018. this._handlerToField(handler, this._overridePrefixes, prefix);
  2019. },
  2020. //
  2021. // see nsIHttpServer.registerDirectory
  2022. //
  2023. registerDirectory: function(path, directory)
  2024. {
  2025. // strip off leading and trailing '/' so that we can use lastIndexOf when
  2026. // determining exactly how a path maps onto a mapped directory --
  2027. // conditional is required here to deal with "/".substring(1, 0) being
  2028. // converted to "/".substring(0, 1) per the JS specification
  2029. var key = path.length == 1 ? "" : path.substring(1, path.length - 1);
  2030. // the path-to-directory mapping code requires that the first character not
  2031. // be "/", or it will go into an infinite loop
  2032. if (key.charAt(0) == "/")
  2033. throw Cr.NS_ERROR_INVALID_ARG;
  2034. key = toInternalPath(key, false);
  2035. if (directory)
  2036. {
  2037. dumpn("*** mapping '" + path + "' to the location " + directory.path);
  2038. this._pathDirectoryMap.put(key, directory);
  2039. }
  2040. else
  2041. {
  2042. dumpn("*** removing mapping for '" + path + "'");
  2043. this._pathDirectoryMap.put(key, null);
  2044. }
  2045. },
  2046. //
  2047. // see nsIHttpServer.registerErrorHandler
  2048. //
  2049. registerErrorHandler: function(err, handler)
  2050. {
  2051. if (!(err in HTTP_ERROR_CODES))
  2052. dumpn("*** WARNING: registering non-HTTP/1.1 error code " +
  2053. "(" + err + ") handler -- was this intentional?");
  2054. this._handlerToField(handler, this._overrideErrors, err);
  2055. },
  2056. //
  2057. // see nsIHttpServer.setIndexHandler
  2058. //
  2059. setIndexHandler: function(handler)
  2060. {
  2061. if (!handler)
  2062. handler = defaultIndexHandler;
  2063. else if (typeof(handler) != "function")
  2064. handler = createHandlerFunc(handler);
  2065. this._indexHandler = handler;
  2066. },
  2067. //
  2068. // see nsIHttpServer.registerContentType
  2069. //
  2070. registerContentType: function(ext, type)
  2071. {
  2072. if (!type)
  2073. delete this._mimeMappings[ext];
  2074. else
  2075. this._mimeMappings[ext] = headerUtils.normalizeFieldValue(type);
  2076. },
  2077. // PRIVATE API
  2078. /**
  2079. * Sets or remove (if handler is null) a handler in an object with a key.
  2080. *
  2081. * @param handler
  2082. * a handler, either function or an nsIHttpRequestHandler
  2083. * @param dict
  2084. * The object to attach the handler to.
  2085. * @param key
  2086. * The field name of the handler.
  2087. */
  2088. _handlerToField: function(handler, dict, key)
  2089. {
  2090. // for convenience, handler can be a function if this is run from xpcshell
  2091. if (typeof(handler) == "function")
  2092. dict[key] = handler;
  2093. else if (handler)
  2094. dict[key] = createHandlerFunc(handler);
  2095. else
  2096. delete dict[key];
  2097. },
  2098. /**
  2099. * Handles a request which maps to a file in the local filesystem (if a base
  2100. * path has already been set; otherwise the 404 error is thrown).
  2101. *
  2102. * @param metadata : Request
  2103. * metadata for the incoming request
  2104. * @param response : Response
  2105. * an uninitialized Response to the given request, to be initialized by a
  2106. * request handler
  2107. * @throws HTTP_###
  2108. * if an HTTP error occurred (usually HTTP_404); note that in this case the
  2109. * calling code must handle post-processing of the response
  2110. */
  2111. _handleDefault: function(metadata, response)
  2112. {
  2113. dumpn("*** _handleDefault()");
  2114. response.setStatusLine(metadata.httpVersion, 200, "OK");
  2115. var path = metadata.path;
  2116. NS_ASSERT(path.charAt(0) == "/", "invalid path: <" + path + ">");
  2117. // determine the actual on-disk file; this requires finding the deepest
  2118. // path-to-directory mapping in the requested URL
  2119. var file = this._getFileForPath(path);
  2120. // the "file" might be a directory, in which case we either serve the
  2121. // contained index.html or make the index handler write the response
  2122. if (file.exists() && file.isDirectory())
  2123. {
  2124. file.append("index.html"); // make configurable?
  2125. if (!file.exists() || file.isDirectory())
  2126. {
  2127. metadata._ensurePropertyBag();
  2128. metadata._bag.setPropertyAsInterface("directory", file.parent);
  2129. this._indexHandler(metadata, response);
  2130. return;
  2131. }
  2132. }
  2133. // alternately, the file might not exist
  2134. if (!file.exists())
  2135. throw HTTP_404;
  2136. var start, end;
  2137. if (metadata._httpVersion.atLeast(nsHttpVersion.HTTP_1_1) &&
  2138. metadata.hasHeader("Range") &&
  2139. this._getTypeFromFile(file) !== SJS_TYPE)
  2140. {
  2141. var rangeMatch = metadata.getHeader("Range").match(/^bytes=(\d+)?-(\d+)?$/);
  2142. if (!rangeMatch)
  2143. throw HTTP_400;
  2144. if (rangeMatch[1] !== undefined)
  2145. start = parseInt(rangeMatch[1], 10);
  2146. if (rangeMatch[2] !== undefined)
  2147. end = parseInt(rangeMatch[2], 10);
  2148. if (start === undefined && end === undefined)
  2149. throw HTTP_400;
  2150. // No start given, so the end is really the count of bytes from the
  2151. // end of the file.
  2152. if (start === undefined)
  2153. {
  2154. start = Math.max(0, file.fileSize - end);
  2155. end = file.fileSize - 1;
  2156. }
  2157. // start and end are inclusive
  2158. if (end === undefined || end >= file.fileSize)
  2159. end = file.fileSize - 1;
  2160. if (start !== undefined && start >= file.fileSize) {
  2161. var HTTP_416 = new HttpError(416, "Requested Range Not Satisfiable");
  2162. HTTP_416.customErrorHandling = function(errorResponse)
  2163. {
  2164. maybeAddHeaders(file, metadata, errorResponse);
  2165. };
  2166. throw HTTP_416;
  2167. }
  2168. if (end < start)
  2169. {
  2170. response.setStatusLine(metadata.httpVersion, 200, "OK");
  2171. start = 0;
  2172. end = file.fileSize - 1;
  2173. }
  2174. else
  2175. {
  2176. response.setStatusLine(metadata.httpVersion, 206, "Partial Content");
  2177. var contentRange = "bytes " + start + "-" + end + "/" + file.fileSize;
  2178. response.setHeader("Content-Range", contentRange);
  2179. }
  2180. }
  2181. else
  2182. {
  2183. start = 0;
  2184. end = file.fileSize - 1;
  2185. }
  2186. // finally...
  2187. dumpn("*** handling '" + path + "' as mapping to " + file.path + " from " +
  2188. start + " to " + end + " inclusive");
  2189. this._writeFileResponse(metadata, file, response, start, end - start + 1);
  2190. },
  2191. /**
  2192. * Writes an HTTP response for the given file, including setting headers for
  2193. * file metadata.
  2194. *
  2195. * @param metadata : Request
  2196. * the Request for which a response is being generated
  2197. * @param file : nsILocalFile
  2198. * the file which is to be sent in the response
  2199. * @param response : Response
  2200. * the response to which the file should be written
  2201. * @param offset: uint
  2202. * the byte offset to skip to when writing
  2203. * @param count: uint
  2204. * the number of bytes to write
  2205. */
  2206. _writeFileResponse: function(metadata, file, response, offset, count)
  2207. {
  2208. const PR_RDONLY = 0x01;
  2209. var type = this._getTypeFromFile(file);
  2210. if (type === SJS_TYPE)
  2211. {
  2212. var fis = new FileInputStream(file, PR_RDONLY, parseInt("444", 8),
  2213. Ci.nsIFileInputStream.CLOSE_ON_EOF);
  2214. try
  2215. {
  2216. var sis = new ScriptableInputStream(fis);
  2217. var s = Cu.Sandbox(gGlobalObject);
  2218. s.importFunction(dump, "dump");
  2219. // Define a basic key-value state-preservation API across requests, with
  2220. // keys initially corresponding to the empty string.
  2221. var self = this;
  2222. var path = metadata.path;
  2223. s.importFunction(function getState(k)
  2224. {
  2225. return self._getState(path, k);
  2226. });
  2227. s.importFunction(function setState(k, v)
  2228. {
  2229. self._setState(path, k, v);
  2230. });
  2231. s.importFunction(function getSharedState(k)
  2232. {
  2233. return self._getSharedState(k);
  2234. });
  2235. s.importFunction(function setSharedState(k, v)
  2236. {
  2237. self._setSharedState(k, v);
  2238. });
  2239. s.importFunction(function getObjectState(k, callback)
  2240. {
  2241. callback(self._getObjectState(k));
  2242. });
  2243. s.importFunction(function setObjectState(k, v)
  2244. {
  2245. self._setObjectState(k, v);
  2246. });
  2247. s.importFunction(function registerPathHandler(p, h)
  2248. {
  2249. self.registerPathHandler(p, h);
  2250. });
  2251. // Make it possible for sjs files to access their location
  2252. this._setState(path, "__LOCATION__", file.path);
  2253. try
  2254. {
  2255. // Alas, the line number in errors dumped to console when calling the
  2256. // request handler is simply an offset from where we load the SJS file.
  2257. // Work around this in a reasonably non-fragile way by dynamically
  2258. // getting the line number where we evaluate the SJS file. Don't
  2259. // separate these two lines!
  2260. var line = new Error().lineNumber;
  2261. Cu.evalInSandbox(sis.read(file.fileSize), s);
  2262. }
  2263. catch (e)
  2264. {
  2265. dumpn("*** syntax error in SJS at " + file.path + ": " + e);
  2266. throw HTTP_500;
  2267. }
  2268. try
  2269. {
  2270. s.handleRequest(metadata, response);
  2271. }
  2272. catch (e)
  2273. {
  2274. dump("*** error running SJS at " + file.path + ": " +
  2275. e + " on line " +
  2276. (e instanceof Error
  2277. ? e.lineNumber + " in httpd.js"
  2278. : (e.lineNumber - line)) + "\n");
  2279. throw HTTP_500;
  2280. }
  2281. }
  2282. finally
  2283. {
  2284. fis.close();
  2285. }
  2286. }
  2287. else
  2288. {
  2289. try
  2290. {
  2291. response.setHeader("Last-Modified",
  2292. toDateString(file.lastModifiedTime),
  2293. false);
  2294. }
  2295. catch (e) { /* lastModifiedTime threw, ignore */ }
  2296. response.setHeader("Content-Type", type, false);
  2297. maybeAddHeaders(file, metadata, response);
  2298. response.setHeader("Content-Length", "" + count, false);
  2299. var fis = new FileInputStream(file, PR_RDONLY, parseInt("444", 8),
  2300. Ci.nsIFileInputStream.CLOSE_ON_EOF);
  2301. offset = offset || 0;
  2302. count = count || file.fileSize;
  2303. NS_ASSERT(offset === 0 || offset < file.fileSize, "bad offset");
  2304. NS_ASSERT(count >= 0, "bad count");
  2305. NS_ASSERT(offset + count <= file.fileSize, "bad total data size");
  2306. try
  2307. {
  2308. if (offset !== 0)
  2309. {
  2310. // Seek (or read, if seeking isn't supported) to the correct offset so
  2311. // the data sent to the client matches the requested range.
  2312. if (fis instanceof Ci.nsISeekableStream)
  2313. fis.seek(Ci.nsISeekableStream.NS_SEEK_SET, offset);
  2314. else
  2315. new ScriptableInputStream(fis).read(offset);
  2316. }
  2317. }
  2318. catch (e)
  2319. {
  2320. fis.close();
  2321. throw e;
  2322. }
  2323. let writeMore = function writeMore()
  2324. {
  2325. gThreadManager.currentThread
  2326. .dispatch(writeData, Ci.nsIThread.DISPATCH_NORMAL);
  2327. }
  2328. var input = new BinaryInputStream(fis);
  2329. var output = new BinaryOutputStream(response.bodyOutputStream);
  2330. var writeData =
  2331. {
  2332. run: function()
  2333. {
  2334. var chunkSize = Math.min(65536, count);
  2335. count -= chunkSize;
  2336. NS_ASSERT(count >= 0, "underflow");
  2337. try
  2338. {
  2339. var data = input.readByteArray(chunkSize);
  2340. NS_ASSERT(data.length === chunkSize,
  2341. "incorrect data returned? got " + data.length +
  2342. ", expected " + chunkSize);
  2343. output.writeByteArray(data, data.length);
  2344. if (count === 0)
  2345. {
  2346. fis.close();
  2347. response.finish();
  2348. }
  2349. else
  2350. {
  2351. writeMore();
  2352. }
  2353. }
  2354. catch (e)
  2355. {
  2356. try
  2357. {
  2358. fis.close();
  2359. }
  2360. finally
  2361. {
  2362. response.finish();
  2363. }
  2364. throw e;
  2365. }
  2366. }
  2367. };
  2368. writeMore();
  2369. // Now that we know copying will start, flag the response as async.
  2370. response.processAsync();
  2371. }
  2372. },
  2373. /**
  2374. * Get the value corresponding to a given key for the given path for SJS state
  2375. * preservation across requests.
  2376. *
  2377. * @param path : string
  2378. * the path from which the given state is to be retrieved
  2379. * @param k : string
  2380. * the key whose corresponding value is to be returned
  2381. * @returns string
  2382. * the corresponding value, which is initially the empty string
  2383. */
  2384. _getState: function(path, k)
  2385. {
  2386. var state = this._state;
  2387. if (path in state && k in state[path])
  2388. return state[path][k];
  2389. return "";
  2390. },
  2391. /**
  2392. * Set the value corresponding to a given key for the given path for SJS state
  2393. * preservation across requests.
  2394. *
  2395. * @param path : string
  2396. * the path from which the given state is to be retrieved
  2397. * @param k : string
  2398. * the key whose corresponding value is to be set
  2399. * @param v : string
  2400. * the value to be set
  2401. */
  2402. _setState: function(path, k, v)
  2403. {
  2404. if (typeof v !== "string")
  2405. throw new Error("non-string value passed");
  2406. var state = this._state;
  2407. if (!(path in state))
  2408. state[path] = {};
  2409. state[path][k] = v;
  2410. },
  2411. /**
  2412. * Get the value corresponding to a given key for SJS state preservation
  2413. * across requests.
  2414. *
  2415. * @param k : string
  2416. * the key whose corresponding value is to be returned
  2417. * @returns string
  2418. * the corresponding value, which is initially the empty string
  2419. */
  2420. _getSharedState: function(k)
  2421. {
  2422. var state = this._sharedState;
  2423. if (k in state)
  2424. return state[k];
  2425. return "";
  2426. },
  2427. /**
  2428. * Set the value corresponding to a given key for SJS state preservation
  2429. * across requests.
  2430. *
  2431. * @param k : string
  2432. * the key whose corresponding value is to be set
  2433. * @param v : string
  2434. * the value to be set
  2435. */
  2436. _setSharedState: function(k, v)
  2437. {
  2438. if (typeof v !== "string")
  2439. throw new Error("non-string value passed");
  2440. this._sharedState[k] = v;
  2441. },
  2442. /**
  2443. * Returns the object associated with the given key in the server for SJS
  2444. * state preservation across requests.
  2445. *
  2446. * @param k : string
  2447. * the key whose corresponding object is to be returned
  2448. * @returns nsISupports
  2449. * the corresponding object, or null if none was present
  2450. */
  2451. _getObjectState: function(k)
  2452. {
  2453. if (typeof k !== "string")
  2454. throw new Error("non-string key passed");
  2455. return this._objectState[k] || null;
  2456. },
  2457. /**
  2458. * Sets the object associated with the given key in the server for SJS
  2459. * state preservation across requests.
  2460. *
  2461. * @param k : string
  2462. * the key whose corresponding object is to be set
  2463. * @param v : nsISupports
  2464. * the object to be associated with the given key; may be null
  2465. */
  2466. _setObjectState: function(k, v)
  2467. {
  2468. if (typeof k !== "string")
  2469. throw new Error("non-string key passed");
  2470. if (typeof v !== "object")
  2471. throw new Error("non-object value passed");
  2472. if (v && !("QueryInterface" in v))
  2473. {
  2474. throw new Error("must pass an nsISupports; use wrappedJSObject to ease " +
  2475. "pain when using the server from JS");
  2476. }
  2477. this._objectState[k] = v;
  2478. },
  2479. /**
  2480. * Gets a content-type for the given file, first by checking for any custom
  2481. * MIME-types registered with this handler for the file's extension, second by
  2482. * asking the global MIME service for a content-type, and finally by failing
  2483. * over to application/octet-stream.
  2484. *
  2485. * @param file : nsIFile
  2486. * the nsIFile for which to get a file type
  2487. * @returns string
  2488. * the best content-type which can be determined for the file
  2489. */
  2490. _getTypeFromFile: function(file)
  2491. {
  2492. try
  2493. {
  2494. var name = file.leafName;
  2495. var dot = name.lastIndexOf(".");
  2496. if (dot > 0)
  2497. {
  2498. var ext = name.slice(dot + 1);
  2499. if (ext in this._mimeMappings)
  2500. return this._mimeMappings[ext];
  2501. }
  2502. return Cc["@mozilla.org/uriloader/external-helper-app-service;1"]
  2503. .getService(Ci.nsIMIMEService)
  2504. .getTypeFromFile(file);
  2505. }
  2506. catch (e)
  2507. {
  2508. return "application/octet-stream";
  2509. }
  2510. },
  2511. /**
  2512. * Returns the nsILocalFile which corresponds to the path, as determined using
  2513. * all registered path->directory mappings and any paths which are explicitly
  2514. * overridden.
  2515. *
  2516. * @param path : string
  2517. * the server path for which a file should be retrieved, e.g. "/foo/bar"
  2518. * @throws HttpError
  2519. * when the correct action is the corresponding HTTP error (i.e., because no
  2520. * mapping was found for a directory in path, the referenced file doesn't
  2521. * exist, etc.)
  2522. * @returns nsILocalFile
  2523. * the file to be sent as the response to a request for the path
  2524. */
  2525. _getFileForPath: function(path)
  2526. {
  2527. // decode and add underscores as necessary
  2528. try
  2529. {
  2530. path = toInternalPath(path, true);
  2531. }
  2532. catch (e)
  2533. {
  2534. throw HTTP_400; // malformed path
  2535. }
  2536. // next, get the directory which contains this path
  2537. var pathMap = this._pathDirectoryMap;
  2538. // An example progression of tmp for a path "/foo/bar/baz/" might be:
  2539. // "foo/bar/baz/", "foo/bar/baz", "foo/bar", "foo", ""
  2540. var tmp = path.substring(1);
  2541. while (true)
  2542. {
  2543. // do we have a match for current head of the path?
  2544. var file = pathMap.get(tmp);
  2545. if (file)
  2546. {
  2547. // XXX hack; basically disable showing mapping for /foo/bar/ when the
  2548. // requested path was /foo/bar, because relative links on the page
  2549. // will all be incorrect -- we really need the ability to easily
  2550. // redirect here instead
  2551. if (tmp == path.substring(1) &&
  2552. tmp.length != 0 &&
  2553. tmp.charAt(tmp.length - 1) != "/")
  2554. file = null;
  2555. else
  2556. break;
  2557. }
  2558. // if we've finished trying all prefixes, exit
  2559. if (tmp == "")
  2560. break;
  2561. tmp = tmp.substring(0, tmp.lastIndexOf("/"));
  2562. }
  2563. // no mapping applies, so 404
  2564. if (!file)
  2565. throw HTTP_404;
  2566. // last, get the file for the path within the determined directory
  2567. var parentFolder = file.parent;
  2568. var dirIsRoot = (parentFolder == null);
  2569. // Strategy here is to append components individually, making sure we
  2570. // never move above the given directory; this allows paths such as
  2571. // "<file>/foo/../bar" but prevents paths such as "<file>/../base-sibling";
  2572. // this component-wise approach also means the code works even on platforms
  2573. // which don't use "/" as the directory separator, such as Windows
  2574. var leafPath = path.substring(tmp.length + 1);
  2575. var comps = leafPath.split("/");
  2576. for (var i = 0, sz = comps.length; i < sz; i++)
  2577. {
  2578. var comp = comps[i];
  2579. if (comp == "..")
  2580. file = file.parent;
  2581. else if (comp == "." || comp == "")
  2582. continue;
  2583. else
  2584. file.append(comp);
  2585. if (!dirIsRoot && file.equals(parentFolder))
  2586. throw HTTP_403;
  2587. }
  2588. return file;
  2589. },
  2590. /**
  2591. * Writes the error page for the given HTTP error code over the given
  2592. * connection.
  2593. *
  2594. * @param errorCode : uint
  2595. * the HTTP error code to be used
  2596. * @param connection : Connection
  2597. * the connection on which the error occurred
  2598. */
  2599. handleError: function(errorCode, connection)
  2600. {
  2601. var response = new Response(connection);
  2602. dumpn("*** error in request: " + errorCode);
  2603. this._handleError(errorCode, new Request(connection.port), response);
  2604. },
  2605. /**
  2606. * Handles a request which generates the given error code, using the
  2607. * user-defined error handler if one has been set, gracefully falling back to
  2608. * the x00 status code if the code has no handler, and failing to status code
  2609. * 500 if all else fails.
  2610. *
  2611. * @param errorCode : uint
  2612. * the HTTP error which is to be returned
  2613. * @param metadata : Request
  2614. * metadata for the request, which will often be incomplete since this is an
  2615. * error
  2616. * @param response : Response
  2617. * an uninitialized Response should be initialized when this method
  2618. * completes with information which represents the desired error code in the
  2619. * ideal case or a fallback code in abnormal circumstances (i.e., 500 is a
  2620. * fallback for 505, per HTTP specs)
  2621. */
  2622. _handleError: function(errorCode, metadata, response)
  2623. {
  2624. if (!metadata)
  2625. throw Cr.NS_ERROR_NULL_POINTER;
  2626. var errorX00 = errorCode - (errorCode % 100);
  2627. try
  2628. {
  2629. if (!(errorCode in HTTP_ERROR_CODES))
  2630. dumpn("*** WARNING: requested invalid error: " + errorCode);
  2631. // RFC 2616 says that we should try to handle an error by its class if we
  2632. // can't otherwise handle it -- if that fails, we revert to handling it as
  2633. // a 500 internal server error, and if that fails we throw and shut down
  2634. // the server
  2635. // actually handle the error
  2636. try
  2637. {
  2638. if (errorCode in this._overrideErrors)
  2639. this._overrideErrors[errorCode](metadata, response);
  2640. else
  2641. this._defaultErrors[errorCode](metadata, response);
  2642. }
  2643. catch (e)
  2644. {
  2645. if (response.partiallySent())
  2646. {
  2647. response.abort(e);
  2648. return;
  2649. }
  2650. // don't retry the handler that threw
  2651. if (errorX00 == errorCode)
  2652. throw HTTP_500;
  2653. dumpn("*** error in handling for error code " + errorCode + ", " +
  2654. "falling back to " + errorX00 + "...");
  2655. response = new Response(response._connection);
  2656. if (errorX00 in this._overrideErrors)
  2657. this._overrideErrors[errorX00](metadata, response);
  2658. else if (errorX00 in this._defaultErrors)
  2659. this._defaultErrors[errorX00](metadata, response);
  2660. else
  2661. throw HTTP_500;
  2662. }
  2663. }
  2664. catch (e)
  2665. {
  2666. if (response.partiallySent())
  2667. {
  2668. response.abort();
  2669. return;
  2670. }
  2671. // we've tried everything possible for a meaningful error -- now try 500
  2672. dumpn("*** error in handling for error code " + errorX00 + ", falling " +
  2673. "back to 500...");
  2674. try
  2675. {
  2676. response = new Response(response._connection);
  2677. if (500 in this._overrideErrors)
  2678. this._overrideErrors[500](metadata, response);
  2679. else
  2680. this._defaultErrors[500](metadata, response);
  2681. }
  2682. catch (e2)
  2683. {
  2684. dumpn("*** multiple errors in default error handlers!");
  2685. dumpn("*** e == " + e + ", e2 == " + e2);
  2686. response.abort(e2);
  2687. return;
  2688. }
  2689. }
  2690. response.complete();
  2691. },
  2692. // FIELDS
  2693. /**
  2694. * This object contains the default handlers for the various HTTP error codes.
  2695. */
  2696. _defaultErrors:
  2697. {
  2698. 400: function(metadata, response)
  2699. {
  2700. // none of the data in metadata is reliable, so hard-code everything here
  2701. response.setStatusLine("1.1", 400, "Bad Request");
  2702. response.setHeader("Content-Type", "text/plain", false);
  2703. var body = "Bad request\n";
  2704. response.bodyOutputStream.write(body, body.length);
  2705. },
  2706. 403: function(metadata, response)
  2707. {
  2708. response.setStatusLine(metadata.httpVersion, 403, "Forbidden");
  2709. response.setHeader("Content-Type", "text/html", false);
  2710. var body = "<html>\
  2711. <head><title>403 Forbidden</title></head>\
  2712. <body>\
  2713. <h1>403 Forbidden</h1>\
  2714. </body>\
  2715. </html>";
  2716. response.bodyOutputStream.write(body, body.length);
  2717. },
  2718. 404: function(metadata, response)
  2719. {
  2720. response.setStatusLine(metadata.httpVersion, 404, "Not Found");
  2721. response.setHeader("Content-Type", "text/html", false);
  2722. var body = "<html>\
  2723. <head><title>404 Not Found</title></head>\
  2724. <body>\
  2725. <h1>404 Not Found</h1>\
  2726. <p>\
  2727. <span style='font-family: monospace;'>" +
  2728. htmlEscape(metadata.path) +
  2729. "</span> was not found.\
  2730. </p>\
  2731. </body>\
  2732. </html>";
  2733. response.bodyOutputStream.write(body, body.length);
  2734. },
  2735. 416: function(metadata, response)
  2736. {
  2737. response.setStatusLine(metadata.httpVersion,
  2738. 416,
  2739. "Requested Range Not Satisfiable");
  2740. response.setHeader("Content-Type", "text/html", false);
  2741. var body = "<html>\
  2742. <head>\
  2743. <title>416 Requested Range Not Satisfiable</title></head>\
  2744. <body>\
  2745. <h1>416 Requested Range Not Satisfiable</h1>\
  2746. <p>The byte range was not valid for the\
  2747. requested resource.\
  2748. </p>\
  2749. </body>\
  2750. </html>";
  2751. response.bodyOutputStream.write(body, body.length);
  2752. },
  2753. 500: function(metadata, response)
  2754. {
  2755. response.setStatusLine(metadata.httpVersion,
  2756. 500,
  2757. "Internal Server Error");
  2758. response.setHeader("Content-Type", "text/html", false);
  2759. var body = "<html>\
  2760. <head><title>500 Internal Server Error</title></head>\
  2761. <body>\
  2762. <h1>500 Internal Server Error</h1>\
  2763. <p>Something's broken in this server and\
  2764. needs to be fixed.</p>\
  2765. </body>\
  2766. </html>";
  2767. response.bodyOutputStream.write(body, body.length);
  2768. },
  2769. 501: function(metadata, response)
  2770. {
  2771. response.setStatusLine(metadata.httpVersion, 501, "Not Implemented");
  2772. response.setHeader("Content-Type", "text/html", false);
  2773. var body = "<html>\
  2774. <head><title>501 Not Implemented</title></head>\
  2775. <body>\
  2776. <h1>501 Not Implemented</h1>\
  2777. <p>This server is not (yet) Apache.</p>\
  2778. </body>\
  2779. </html>";
  2780. response.bodyOutputStream.write(body, body.length);
  2781. },
  2782. 505: function(metadata, response)
  2783. {
  2784. response.setStatusLine("1.1", 505, "HTTP Version Not Supported");
  2785. response.setHeader("Content-Type", "text/html", false);
  2786. var body = "<html>\
  2787. <head><title>505 HTTP Version Not Supported</title></head>\
  2788. <body>\
  2789. <h1>505 HTTP Version Not Supported</h1>\
  2790. <p>This server only supports HTTP/1.0 and HTTP/1.1\
  2791. connections.</p>\
  2792. </body>\
  2793. </html>";
  2794. response.bodyOutputStream.write(body, body.length);
  2795. }
  2796. },
  2797. /**
  2798. * Contains handlers for the default set of URIs contained in this server.
  2799. */
  2800. _defaultPaths:
  2801. {
  2802. "/": function(metadata, response)
  2803. {
  2804. response.setStatusLine(metadata.httpVersion, 200, "OK");
  2805. response.setHeader("Content-Type", "text/html", false);
  2806. var body = "<html>\
  2807. <head><title>httpd.js</title></head>\
  2808. <body>\
  2809. <h1>httpd.js</h1>\
  2810. <p>If you're seeing this page, httpd.js is up and\
  2811. serving requests! Now set a base path and serve some\
  2812. files!</p>\
  2813. </body>\
  2814. </html>";
  2815. response.bodyOutputStream.write(body, body.length);
  2816. },
  2817. "/trace": function(metadata, response)
  2818. {
  2819. response.setStatusLine(metadata.httpVersion, 200, "OK");
  2820. response.setHeader("Content-Type", "text/plain", false);
  2821. var body = "Request-URI: " +
  2822. metadata.scheme + "://" + metadata.host + ":" + metadata.port +
  2823. metadata.path + "\n\n";
  2824. body += "Request (semantically equivalent, slightly reformatted):\n\n";
  2825. body += metadata.method + " " + metadata.path;
  2826. if (metadata.queryString)
  2827. body += "?" + metadata.queryString;
  2828. body += " HTTP/" + metadata.httpVersion + "\r\n";
  2829. var headEnum = metadata.headers;
  2830. while (headEnum.hasMoreElements())
  2831. {
  2832. var fieldName = headEnum.getNext()
  2833. .QueryInterface(Ci.nsISupportsString)
  2834. .data;
  2835. body += fieldName + ": " + metadata.getHeader(fieldName) + "\r\n";
  2836. }
  2837. response.bodyOutputStream.write(body, body.length);
  2838. }
  2839. }
  2840. };
  2841. /**
  2842. * Maps absolute paths to files on the local file system (as nsILocalFiles).
  2843. */
  2844. function FileMap()
  2845. {
  2846. /** Hash which will map paths to nsILocalFiles. */
  2847. this._map = {};
  2848. }
  2849. FileMap.prototype =
  2850. {
  2851. // PUBLIC API
  2852. /**
  2853. * Maps key to a clone of the nsILocalFile value if value is non-null;
  2854. * otherwise, removes any extant mapping for key.
  2855. *
  2856. * @param key : string
  2857. * string to which a clone of value is mapped
  2858. * @param value : nsILocalFile
  2859. * the file to map to key, or null to remove a mapping
  2860. */
  2861. put: function(key, value)
  2862. {
  2863. if (value)
  2864. this._map[key] = value.clone();
  2865. else
  2866. delete this._map[key];
  2867. },
  2868. /**
  2869. * Returns a clone of the nsILocalFile mapped to key, or null if no such
  2870. * mapping exists.
  2871. *
  2872. * @param key : string
  2873. * key to which the returned file maps
  2874. * @returns nsILocalFile
  2875. * a clone of the mapped file, or null if no mapping exists
  2876. */
  2877. get: function(key)
  2878. {
  2879. var val = this._map[key];
  2880. return val ? val.clone() : null;
  2881. }
  2882. };
  2883. // Response CONSTANTS
  2884. // token = *<any CHAR except CTLs or separators>
  2885. // CHAR = <any US-ASCII character (0-127)>
  2886. // CTL = <any US-ASCII control character (0-31) and DEL (127)>
  2887. // separators = "(" | ")" | "<" | ">" | "@"
  2888. // | "," | ";" | ":" | "\" | <">
  2889. // | "/" | "[" | "]" | "?" | "="
  2890. // | "{" | "}" | SP | HT
  2891. const IS_TOKEN_ARRAY =
  2892. [0, 0, 0, 0, 0, 0, 0, 0, // 0
  2893. 0, 0, 0, 0, 0, 0, 0, 0, // 8
  2894. 0, 0, 0, 0, 0, 0, 0, 0, // 16
  2895. 0, 0, 0, 0, 0, 0, 0, 0, // 24
  2896. 0, 1, 0, 1, 1, 1, 1, 1, // 32
  2897. 0, 0, 1, 1, 0, 1, 1, 0, // 40
  2898. 1, 1, 1, 1, 1, 1, 1, 1, // 48
  2899. 1, 1, 0, 0, 0, 0, 0, 0, // 56
  2900. 0, 1, 1, 1, 1, 1, 1, 1, // 64
  2901. 1, 1, 1, 1, 1, 1, 1, 1, // 72
  2902. 1, 1, 1, 1, 1, 1, 1, 1, // 80
  2903. 1, 1, 1, 0, 0, 0, 1, 1, // 88
  2904. 1, 1, 1, 1, 1, 1, 1, 1, // 96
  2905. 1, 1, 1, 1, 1, 1, 1, 1, // 104
  2906. 1, 1, 1, 1, 1, 1, 1, 1, // 112
  2907. 1, 1, 1, 0, 1, 0, 1]; // 120
  2908. /**
  2909. * Determines whether the given character code is a CTL.
  2910. *
  2911. * @param code : uint
  2912. * the character code
  2913. * @returns boolean
  2914. * true if code is a CTL, false otherwise
  2915. */
  2916. function isCTL(code)
  2917. {
  2918. return (code >= 0 && code <= 31) || (code == 127);
  2919. }
  2920. /**
  2921. * Represents a response to an HTTP request, encapsulating all details of that
  2922. * response. This includes all headers, the HTTP version, status code and
  2923. * explanation, and the entity itself.
  2924. *
  2925. * @param connection : Connection
  2926. * the connection over which this response is to be written
  2927. */
  2928. function Response(connection)
  2929. {
  2930. /** The connection over which this response will be written. */
  2931. this._connection = connection;
  2932. /**
  2933. * The HTTP version of this response; defaults to 1.1 if not set by the
  2934. * handler.
  2935. */
  2936. this._httpVersion = nsHttpVersion.HTTP_1_1;
  2937. /**
  2938. * The HTTP code of this response; defaults to 200.
  2939. */
  2940. this._httpCode = 200;
  2941. /**
  2942. * The description of the HTTP code in this response; defaults to "OK".
  2943. */
  2944. this._httpDescription = "OK";
  2945. /**
  2946. * An nsIHttpHeaders object in which the headers in this response should be
  2947. * stored. This property is null after the status line and headers have been
  2948. * written to the network, and it may be modified up until it is cleared,
  2949. * except if this._finished is set first (in which case headers are written
  2950. * asynchronously in response to a finish() call not preceded by
  2951. * flushHeaders()).
  2952. */
  2953. this._headers = new nsHttpHeaders();
  2954. /**
  2955. * Set to true when this response is ended (completely constructed if possible
  2956. * and the connection closed); further actions on this will then fail.
  2957. */
  2958. this._ended = false;
  2959. /**
  2960. * A stream used to hold data written to the body of this response.
  2961. */
  2962. this._bodyOutputStream = null;
  2963. /**
  2964. * A stream containing all data that has been written to the body of this
  2965. * response so far. (Async handlers make the data contained in this
  2966. * unreliable as a way of determining content length in general, but auxiliary
  2967. * saved information can sometimes be used to guarantee reliability.)
  2968. */
  2969. this._bodyInputStream = null;
  2970. /**
  2971. * A stream copier which copies data to the network. It is initially null
  2972. * until replaced with a copier for response headers; when headers have been
  2973. * fully sent it is replaced with a copier for the response body, remaining
  2974. * so for the duration of response processing.
  2975. */
  2976. this._asyncCopier = null;
  2977. /**
  2978. * True if this response has been designated as being processed
  2979. * asynchronously rather than for the duration of a single call to
  2980. * nsIHttpRequestHandler.handle.
  2981. */
  2982. this._processAsync = false;
  2983. /**
  2984. * True iff finish() has been called on this, signaling that no more changes
  2985. * to this may be made.
  2986. */
  2987. this._finished = false;
  2988. /**
  2989. * True iff powerSeized() has been called on this, signaling that this
  2990. * response is to be handled manually by the response handler (which may then
  2991. * send arbitrary data in response, even non-HTTP responses).
  2992. */
  2993. this._powerSeized = false;
  2994. }
  2995. Response.prototype =
  2996. {
  2997. // PUBLIC CONSTRUCTION API
  2998. //
  2999. // see nsIHttpResponse.bodyOutputStream
  3000. //
  3001. get bodyOutputStream()
  3002. {
  3003. if (this._finished)
  3004. throw Cr.NS_ERROR_NOT_AVAILABLE;
  3005. if (!this._bodyOutputStream)
  3006. {
  3007. var pipe = new Pipe(true, false, Response.SEGMENT_SIZE, PR_UINT32_MAX,
  3008. null);
  3009. this._bodyOutputStream = pipe.outputStream;
  3010. this._bodyInputStream = pipe.inputStream;
  3011. if (this._processAsync || this._powerSeized)
  3012. this._startAsyncProcessor();
  3013. }
  3014. return this._bodyOutputStream;
  3015. },
  3016. //
  3017. // see nsIHttpResponse.write
  3018. //
  3019. write: function(data)
  3020. {
  3021. if (this._finished)
  3022. throw Cr.NS_ERROR_NOT_AVAILABLE;
  3023. var dataAsString = String(data);
  3024. this.bodyOutputStream.write(dataAsString, dataAsString.length);
  3025. },
  3026. //
  3027. // see nsIHttpResponse.setStatusLine
  3028. //
  3029. setStatusLine: function(httpVersion, code, description)
  3030. {
  3031. if (!this._headers || this._finished || this._powerSeized)
  3032. throw Cr.NS_ERROR_NOT_AVAILABLE;
  3033. this._ensureAlive();
  3034. if (!(code >= 0 && code < 1000))
  3035. throw Cr.NS_ERROR_INVALID_ARG;
  3036. try
  3037. {
  3038. var httpVer;
  3039. // avoid version construction for the most common cases
  3040. if (!httpVersion || httpVersion == "1.1")
  3041. httpVer = nsHttpVersion.HTTP_1_1;
  3042. else if (httpVersion == "1.0")
  3043. httpVer = nsHttpVersion.HTTP_1_0;
  3044. else
  3045. httpVer = new nsHttpVersion(httpVersion);
  3046. }
  3047. catch (e)
  3048. {
  3049. throw Cr.NS_ERROR_INVALID_ARG;
  3050. }
  3051. // Reason-Phrase = *<TEXT, excluding CR, LF>
  3052. // TEXT = <any OCTET except CTLs, but including LWS>
  3053. //
  3054. // XXX this ends up disallowing octets which aren't Unicode, I think -- not
  3055. // much to do if description is IDL'd as string
  3056. if (!description)
  3057. description = "";
  3058. for (var i = 0; i < description.length; i++)
  3059. if (isCTL(description.charCodeAt(i)) && description.charAt(i) != "\t")
  3060. throw Cr.NS_ERROR_INVALID_ARG;
  3061. // set the values only after validation to preserve atomicity
  3062. this._httpDescription = description;
  3063. this._httpCode = code;
  3064. this._httpVersion = httpVer;
  3065. },
  3066. //
  3067. // see nsIHttpResponse.setHeader
  3068. //
  3069. setHeader: function(name, value, merge)
  3070. {
  3071. if (!this._headers || this._finished || this._powerSeized)
  3072. throw Cr.NS_ERROR_NOT_AVAILABLE;
  3073. this._ensureAlive();
  3074. this._headers.setHeader(name, value, merge);
  3075. },
  3076. //
  3077. // see nsIHttpResponse.processAsync
  3078. //
  3079. processAsync: function()
  3080. {
  3081. if (this._finished)
  3082. throw Cr.NS_ERROR_UNEXPECTED;
  3083. if (this._powerSeized)
  3084. throw Cr.NS_ERROR_NOT_AVAILABLE;
  3085. if (this._processAsync)
  3086. return;
  3087. this._ensureAlive();
  3088. dumpn("*** processing connection " + this._connection.number + " async");
  3089. this._processAsync = true;
  3090. /*
  3091. * Either the bodyOutputStream getter or this method is responsible for
  3092. * starting the asynchronous processor and catching writes of data to the
  3093. * response body of async responses as they happen, for the purpose of
  3094. * forwarding those writes to the actual connection's output stream.
  3095. * If bodyOutputStream is accessed first, calling this method will create
  3096. * the processor (when it first is clear that body data is to be written
  3097. * immediately, not buffered). If this method is called first, accessing
  3098. * bodyOutputStream will create the processor. If only this method is
  3099. * called, we'll write nothing, neither headers nor the nonexistent body,
  3100. * until finish() is called. Since that delay is easily avoided by simply
  3101. * getting bodyOutputStream or calling write(""), we don't worry about it.
  3102. */
  3103. if (this._bodyOutputStream && !this._asyncCopier)
  3104. this._startAsyncProcessor();
  3105. },
  3106. //
  3107. // see nsIHttpResponse.seizePower
  3108. //
  3109. seizePower: function()
  3110. {
  3111. if (this._processAsync)
  3112. throw Cr.NS_ERROR_NOT_AVAILABLE;
  3113. if (this._finished)
  3114. throw Cr.NS_ERROR_UNEXPECTED;
  3115. if (this._powerSeized)
  3116. return;
  3117. this._ensureAlive();
  3118. dumpn("*** forcefully seizing power over connection " +
  3119. this._connection.number + "...");
  3120. // Purge any already-written data without sending it. We could as easily
  3121. // swap out the streams entirely, but that makes it possible to acquire and
  3122. // unknowingly use a stale reference, so we require there only be one of
  3123. // each stream ever for any response to avoid this complication.
  3124. if (this._asyncCopier)
  3125. this._asyncCopier.cancel(Cr.NS_BINDING_ABORTED);
  3126. this._asyncCopier = null;
  3127. if (this._bodyOutputStream)
  3128. {
  3129. var input = new BinaryInputStream(this._bodyInputStream);
  3130. var avail;
  3131. while ((avail = input.available()) > 0)
  3132. input.readByteArray(avail);
  3133. }
  3134. this._powerSeized = true;
  3135. if (this._bodyOutputStream)
  3136. this._startAsyncProcessor();
  3137. },
  3138. //
  3139. // see nsIHttpResponse.finish
  3140. //
  3141. finish: function()
  3142. {
  3143. if (!this._processAsync && !this._powerSeized)
  3144. throw Cr.NS_ERROR_UNEXPECTED;
  3145. if (this._finished)
  3146. return;
  3147. dumpn("*** finishing connection " + this._connection.number);
  3148. this._startAsyncProcessor(); // in case bodyOutputStream was never accessed
  3149. if (this._bodyOutputStream)
  3150. this._bodyOutputStream.close();
  3151. this._finished = true;
  3152. },
  3153. // NSISUPPORTS
  3154. //
  3155. // see nsISupports.QueryInterface
  3156. //
  3157. QueryInterface: function(iid)
  3158. {
  3159. if (iid.equals(Ci.nsIHttpResponse) || iid.equals(Ci.nsISupports))
  3160. return this;
  3161. throw Cr.NS_ERROR_NO_INTERFACE;
  3162. },
  3163. // POST-CONSTRUCTION API (not exposed externally)
  3164. /**
  3165. * The HTTP version number of this, as a string (e.g. "1.1").
  3166. */
  3167. get httpVersion()
  3168. {
  3169. this._ensureAlive();
  3170. return this._httpVersion.toString();
  3171. },
  3172. /**
  3173. * The HTTP status code of this response, as a string of three characters per
  3174. * RFC 2616.
  3175. */
  3176. get httpCode()
  3177. {
  3178. this._ensureAlive();
  3179. var codeString = (this._httpCode < 10 ? "0" : "") +
  3180. (this._httpCode < 100 ? "0" : "") +
  3181. this._httpCode;
  3182. return codeString;
  3183. },
  3184. /**
  3185. * The description of the HTTP status code of this response, or "" if none is
  3186. * set.
  3187. */
  3188. get httpDescription()
  3189. {
  3190. this._ensureAlive();
  3191. return this._httpDescription;
  3192. },
  3193. /**
  3194. * The headers in this response, as an nsHttpHeaders object.
  3195. */
  3196. get headers()
  3197. {
  3198. this._ensureAlive();
  3199. return this._headers;
  3200. },
  3201. //
  3202. // see nsHttpHeaders.getHeader
  3203. //
  3204. getHeader: function(name)
  3205. {
  3206. this._ensureAlive();
  3207. return this._headers.getHeader(name);
  3208. },
  3209. /**
  3210. * Determines whether this response may be abandoned in favor of a newly
  3211. * constructed response. A response may be abandoned only if it is not being
  3212. * sent asynchronously and if raw control over it has not been taken from the
  3213. * server.
  3214. *
  3215. * @returns boolean
  3216. * true iff no data has been written to the network
  3217. */
  3218. partiallySent: function()
  3219. {
  3220. dumpn("*** partiallySent()");
  3221. return this._processAsync || this._powerSeized;
  3222. },
  3223. /**
  3224. * If necessary, kicks off the remaining request processing needed to be done
  3225. * after a request handler performs its initial work upon this response.
  3226. */
  3227. complete: function()
  3228. {
  3229. dumpn("*** complete()");
  3230. if (this._processAsync || this._powerSeized)
  3231. {
  3232. NS_ASSERT(this._processAsync ^ this._powerSeized,
  3233. "can't both send async and relinquish power");
  3234. return;
  3235. }
  3236. NS_ASSERT(!this.partiallySent(), "completing a partially-sent response?");
  3237. this._startAsyncProcessor();
  3238. // Now make sure we finish processing this request!
  3239. if (this._bodyOutputStream)
  3240. this._bodyOutputStream.close();
  3241. },
  3242. /**
  3243. * Abruptly ends processing of this response, usually due to an error in an
  3244. * incoming request but potentially due to a bad error handler. Since we
  3245. * cannot handle the error in the usual way (giving an HTTP error page in
  3246. * response) because data may already have been sent (or because the response
  3247. * might be expected to have been generated asynchronously or completely from
  3248. * scratch by the handler), we stop processing this response and abruptly
  3249. * close the connection.
  3250. *
  3251. * @param e : Error
  3252. * the exception which precipitated this abort, or null if no such exception
  3253. * was generated
  3254. */
  3255. abort: function(e)
  3256. {
  3257. dumpn("*** abort(<" + e + ">)");
  3258. // This response will be ended by the processor if one was created.
  3259. var copier = this._asyncCopier;
  3260. if (copier)
  3261. {
  3262. // We dispatch asynchronously here so that any pending writes of data to
  3263. // the connection will be deterministically written. This makes it easier
  3264. // to specify exact behavior, and it makes observable behavior more
  3265. // predictable for clients. Note that the correctness of this depends on
  3266. // callbacks in response to _waitToReadData in WriteThroughCopier
  3267. // happening asynchronously with respect to the actual writing of data to
  3268. // bodyOutputStream, as they currently do; if they happened synchronously,
  3269. // an event which ran before this one could write more data to the
  3270. // response body before we get around to canceling the copier. We have
  3271. // tests for this in test_seizepower.js, however, and I can't think of a
  3272. // way to handle both cases without removing bodyOutputStream access and
  3273. // moving its effective write(data, length) method onto Response, which
  3274. // would be slower and require more code than this anyway.
  3275. gThreadManager.currentThread.dispatch({
  3276. run: function()
  3277. {
  3278. dumpn("*** canceling copy asynchronously...");
  3279. copier.cancel(Cr.NS_ERROR_UNEXPECTED);
  3280. }
  3281. }, Ci.nsIThread.DISPATCH_NORMAL);
  3282. }
  3283. else
  3284. {
  3285. this.end();
  3286. }
  3287. },
  3288. /**
  3289. * Closes this response's network connection, marks the response as finished,
  3290. * and notifies the server handler that the request is done being processed.
  3291. */
  3292. end: function()
  3293. {
  3294. NS_ASSERT(!this._ended, "ending this response twice?!?!");
  3295. this._connection.close();
  3296. if (this._bodyOutputStream)
  3297. this._bodyOutputStream.close();
  3298. this._finished = true;
  3299. this._ended = true;
  3300. },
  3301. // PRIVATE IMPLEMENTATION
  3302. /**
  3303. * Sends the status line and headers of this response if they haven't been
  3304. * sent and initiates the process of copying data written to this response's
  3305. * body to the network.
  3306. */
  3307. _startAsyncProcessor: function()
  3308. {
  3309. dumpn("*** _startAsyncProcessor()");
  3310. // Handle cases where we're being called a second time. The former case
  3311. // happens when this is triggered both by complete() and by processAsync(),
  3312. // while the latter happens when processAsync() in conjunction with sent
  3313. // data causes abort() to be called.
  3314. if (this._asyncCopier || this._ended)
  3315. {
  3316. dumpn("*** ignoring second call to _startAsyncProcessor");
  3317. return;
  3318. }
  3319. // Send headers if they haven't been sent already and should be sent, then
  3320. // asynchronously continue to send the body.
  3321. if (this._headers && !this._powerSeized)
  3322. {
  3323. this._sendHeaders();
  3324. return;
  3325. }
  3326. this._headers = null;
  3327. this._sendBody();
  3328. },
  3329. /**
  3330. * Signals that all modifications to the response status line and headers are
  3331. * complete and then sends that data over the network to the client. Once
  3332. * this method completes, a different response to the request that resulted
  3333. * in this response cannot be sent -- the only possible action in case of
  3334. * error is to abort the response and close the connection.
  3335. */
  3336. _sendHeaders: function()
  3337. {
  3338. dumpn("*** _sendHeaders()");
  3339. NS_ASSERT(this._headers);
  3340. NS_ASSERT(!this._powerSeized);
  3341. // request-line
  3342. var statusLine = "HTTP/" + this.httpVersion + " " +
  3343. this.httpCode + " " +
  3344. this.httpDescription + "\r\n";
  3345. // header post-processing
  3346. var headers = this._headers;
  3347. headers.setHeader("Connection", "close", false);
  3348. headers.setHeader("Server", "httpd.js", false);
  3349. if (!headers.hasHeader("Date"))
  3350. headers.setHeader("Date", toDateString(Date.now()), false);
  3351. // Any response not being processed asynchronously must have an associated
  3352. // Content-Length header for reasons of backwards compatibility with the
  3353. // initial server, which fully buffered every response before sending it.
  3354. // Beyond that, however, it's good to do this anyway because otherwise it's
  3355. // impossible to test behaviors that depend on the presence or absence of a
  3356. // Content-Length header.
  3357. if (!this._processAsync)
  3358. {
  3359. dumpn("*** non-async response, set Content-Length");
  3360. var bodyStream = this._bodyInputStream;
  3361. var avail = bodyStream ? bodyStream.available() : 0;
  3362. // XXX assumes stream will always report the full amount of data available
  3363. headers.setHeader("Content-Length", "" + avail, false);
  3364. }
  3365. // construct and send response
  3366. dumpn("*** header post-processing completed, sending response head...");
  3367. // request-line
  3368. var preambleData = [statusLine];
  3369. // headers
  3370. var headEnum = headers.enumerator;
  3371. while (headEnum.hasMoreElements())
  3372. {
  3373. var fieldName = headEnum.getNext()
  3374. .QueryInterface(Ci.nsISupportsString)
  3375. .data;
  3376. var values = headers.getHeaderValues(fieldName);
  3377. for (var i = 0, sz = values.length; i < sz; i++)
  3378. preambleData.push(fieldName + ": " + values[i] + "\r\n");
  3379. }
  3380. // end request-line/headers
  3381. preambleData.push("\r\n");
  3382. var preamble = preambleData.join("");
  3383. var responseHeadPipe = new Pipe(true, false, 0, PR_UINT32_MAX, null);
  3384. responseHeadPipe.outputStream.write(preamble, preamble.length);
  3385. var response = this;
  3386. var copyObserver =
  3387. {
  3388. onStartRequest: function(request, cx)
  3389. {
  3390. dumpn("*** preamble copying started");
  3391. },
  3392. onStopRequest: function(request, cx, statusCode)
  3393. {
  3394. dumpn("*** preamble copying complete " +
  3395. "[status=0x" + statusCode.toString(16) + "]");
  3396. if (!components.isSuccessCode(statusCode))
  3397. {
  3398. dumpn("!!! header copying problems: non-success statusCode, " +
  3399. "ending response");
  3400. response.end();
  3401. }
  3402. else
  3403. {
  3404. response._sendBody();
  3405. }
  3406. },
  3407. QueryInterface: function(aIID)
  3408. {
  3409. if (aIID.equals(Ci.nsIRequestObserver) || aIID.equals(Ci.nsISupports))
  3410. return this;
  3411. throw Cr.NS_ERROR_NO_INTERFACE;
  3412. }
  3413. };
  3414. var headerCopier = this._asyncCopier =
  3415. new WriteThroughCopier(responseHeadPipe.inputStream,
  3416. this._connection.output,
  3417. copyObserver, null);
  3418. responseHeadPipe.outputStream.close();
  3419. // Forbid setting any more headers or modifying the request line.
  3420. this._headers = null;
  3421. },
  3422. /**
  3423. * Asynchronously writes the body of the response (or the entire response, if
  3424. * seizePower() has been called) to the network.
  3425. */
  3426. _sendBody: function()
  3427. {
  3428. dumpn("*** _sendBody");
  3429. NS_ASSERT(!this._headers, "still have headers around but sending body?");
  3430. // If no body data was written, we're done
  3431. if (!this._bodyInputStream)
  3432. {
  3433. dumpn("*** empty body, response finished");
  3434. this.end();
  3435. return;
  3436. }
  3437. var response = this;
  3438. var copyObserver =
  3439. {
  3440. onStartRequest: function(request, context)
  3441. {
  3442. dumpn("*** onStartRequest");
  3443. },
  3444. onStopRequest: function(request, cx, statusCode)
  3445. {
  3446. dumpn("*** onStopRequest [status=0x" + statusCode.toString(16) + "]");
  3447. if (statusCode === Cr.NS_BINDING_ABORTED)
  3448. {
  3449. dumpn("*** terminating copy observer without ending the response");
  3450. }
  3451. else
  3452. {
  3453. if (!components.isSuccessCode(statusCode))
  3454. dumpn("*** WARNING: non-success statusCode in onStopRequest");
  3455. response.end();
  3456. }
  3457. },
  3458. QueryInterface: function(aIID)
  3459. {
  3460. if (aIID.equals(Ci.nsIRequestObserver) || aIID.equals(Ci.nsISupports))
  3461. return this;
  3462. throw Cr.NS_ERROR_NO_INTERFACE;
  3463. }
  3464. };
  3465. dumpn("*** starting async copier of body data...");
  3466. this._asyncCopier =
  3467. new WriteThroughCopier(this._bodyInputStream, this._connection.output,
  3468. copyObserver, null);
  3469. },
  3470. /** Ensures that this hasn't been ended. */
  3471. _ensureAlive: function()
  3472. {
  3473. NS_ASSERT(!this._ended, "not handling response lifetime correctly");
  3474. }
  3475. };
  3476. /**
  3477. * Size of the segments in the buffer used in storing response data and writing
  3478. * it to the socket.
  3479. */
  3480. Response.SEGMENT_SIZE = 8192;
  3481. /** Serves double duty in WriteThroughCopier implementation. */
  3482. function notImplemented()
  3483. {
  3484. throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  3485. }
  3486. /** Returns true iff the given exception represents stream closure. */
  3487. function streamClosed(e)
  3488. {
  3489. return e === Cr.NS_BASE_STREAM_CLOSED ||
  3490. (typeof e === "object" && e.result === Cr.NS_BASE_STREAM_CLOSED);
  3491. }
  3492. /** Returns true iff the given exception represents a blocked stream. */
  3493. function wouldBlock(e)
  3494. {
  3495. return e === Cr.NS_BASE_STREAM_WOULD_BLOCK ||
  3496. (typeof e === "object" && e.result === Cr.NS_BASE_STREAM_WOULD_BLOCK);
  3497. }
  3498. /**
  3499. * Copies data from source to sink as it becomes available, when that data can
  3500. * be written to sink without blocking.
  3501. *
  3502. * @param source : nsIAsyncInputStream
  3503. * the stream from which data is to be read
  3504. * @param sink : nsIAsyncOutputStream
  3505. * the stream to which data is to be copied
  3506. * @param observer : nsIRequestObserver
  3507. * an observer which will be notified when the copy starts and finishes
  3508. * @param context : nsISupports
  3509. * context passed to observer when notified of start/stop
  3510. * @throws NS_ERROR_NULL_POINTER
  3511. * if source, sink, or observer are null
  3512. */
  3513. function WriteThroughCopier(source, sink, observer, context)
  3514. {
  3515. if (!source || !sink || !observer)
  3516. throw Cr.NS_ERROR_NULL_POINTER;
  3517. /** Stream from which data is being read. */
  3518. this._source = source;
  3519. /** Stream to which data is being written. */
  3520. this._sink = sink;
  3521. /** Observer watching this copy. */
  3522. this._observer = observer;
  3523. /** Context for the observer watching this. */
  3524. this._context = context;
  3525. /**
  3526. * True iff this is currently being canceled (cancel has been called, the
  3527. * callback may not yet have been made).
  3528. */
  3529. this._canceled = false;
  3530. /**
  3531. * False until all data has been read from input and written to output, at
  3532. * which point this copy is completed and cancel() is asynchronously called.
  3533. */
  3534. this._completed = false;
  3535. /** Required by nsIRequest, meaningless. */
  3536. this.loadFlags = 0;
  3537. /** Required by nsIRequest, meaningless. */
  3538. this.loadGroup = null;
  3539. /** Required by nsIRequest, meaningless. */
  3540. this.name = "response-body-copy";
  3541. /** Status of this request. */
  3542. this.status = Cr.NS_OK;
  3543. /** Arrays of byte strings waiting to be written to output. */
  3544. this._pendingData = [];
  3545. // start copying
  3546. try
  3547. {
  3548. observer.onStartRequest(this, context);
  3549. this._waitToReadData();
  3550. this._waitForSinkClosure();
  3551. }
  3552. catch (e)
  3553. {
  3554. dumpn("!!! error starting copy: " + e +
  3555. ("lineNumber" in e ? ", line " + e.lineNumber : ""));
  3556. dumpn(e.stack);
  3557. this.cancel(Cr.NS_ERROR_UNEXPECTED);
  3558. }
  3559. }
  3560. WriteThroughCopier.prototype =
  3561. {
  3562. /* nsISupports implementation */
  3563. QueryInterface: function(iid)
  3564. {
  3565. if (iid.equals(Ci.nsIInputStreamCallback) ||
  3566. iid.equals(Ci.nsIOutputStreamCallback) ||
  3567. iid.equals(Ci.nsIRequest) ||
  3568. iid.equals(Ci.nsISupports))
  3569. {
  3570. return this;
  3571. }
  3572. throw Cr.NS_ERROR_NO_INTERFACE;
  3573. },
  3574. // NSIINPUTSTREAMCALLBACK
  3575. /**
  3576. * Receives a more-data-in-input notification and writes the corresponding
  3577. * data to the output.
  3578. *
  3579. * @param input : nsIAsyncInputStream
  3580. * the input stream on whose data we have been waiting
  3581. */
  3582. onInputStreamReady: function(input)
  3583. {
  3584. if (this._source === null)
  3585. return;
  3586. dumpn("*** onInputStreamReady");
  3587. //
  3588. // Ordinarily we'll read a non-zero amount of data from input, queue it up
  3589. // to be written and then wait for further callbacks. The complications in
  3590. // this method are the cases where we deviate from that behavior when errors
  3591. // occur or when copying is drawing to a finish.
  3592. //
  3593. // The edge cases when reading data are:
  3594. //
  3595. // Zero data is read
  3596. // If zero data was read, we're at the end of available data, so we can
  3597. // should stop reading and move on to writing out what we have (or, if
  3598. // we've already done that, onto notifying of completion).
  3599. // A stream-closed exception is thrown
  3600. // This is effectively a less kind version of zero data being read; the
  3601. // only difference is that we notify of completion with that result
  3602. // rather than with NS_OK.
  3603. // Some other exception is thrown
  3604. // This is the least kind result. We don't know what happened, so we
  3605. // act as though the stream closed except that we notify of completion
  3606. // with the result NS_ERROR_UNEXPECTED.
  3607. //
  3608. var bytesWanted = 0, bytesConsumed = -1;
  3609. try
  3610. {
  3611. input = new BinaryInputStream(input);
  3612. bytesWanted = Math.min(input.available(), Response.SEGMENT_SIZE);
  3613. dumpn("*** input wanted: " + bytesWanted);
  3614. if (bytesWanted > 0)
  3615. {
  3616. var data = input.readByteArray(bytesWanted);
  3617. bytesConsumed = data.length;
  3618. this._pendingData.push(String.fromCharCode.apply(String, data));
  3619. }
  3620. dumpn("*** " + bytesConsumed + " bytes read");
  3621. // Handle the zero-data edge case in the same place as all other edge
  3622. // cases are handled.
  3623. if (bytesWanted === 0)
  3624. throw Cr.NS_BASE_STREAM_CLOSED;
  3625. }
  3626. catch (e)
  3627. {
  3628. if (streamClosed(e))
  3629. {
  3630. dumpn("*** input stream closed");
  3631. e = bytesWanted === 0 ? Cr.NS_OK : Cr.NS_ERROR_UNEXPECTED;
  3632. }
  3633. else
  3634. {
  3635. dumpn("!!! unexpected error reading from input, canceling: " + e);
  3636. e = Cr.NS_ERROR_UNEXPECTED;
  3637. }
  3638. this._doneReadingSource(e);
  3639. return;
  3640. }
  3641. var pendingData = this._pendingData;
  3642. NS_ASSERT(bytesConsumed > 0);
  3643. NS_ASSERT(pendingData.length > 0, "no pending data somehow?");
  3644. NS_ASSERT(pendingData[pendingData.length - 1].length > 0,
  3645. "buffered zero bytes of data?");
  3646. NS_ASSERT(this._source !== null);
  3647. // Reading has gone great, and we've gotten data to write now. What if we
  3648. // don't have a place to write that data, because output went away just
  3649. // before this read? Drop everything on the floor, including new data, and
  3650. // cancel at this point.
  3651. if (this._sink === null)
  3652. {
  3653. pendingData.length = 0;
  3654. this._doneReadingSource(Cr.NS_ERROR_UNEXPECTED);
  3655. return;
  3656. }
  3657. // Okay, we've read the data, and we know we have a place to write it. We
  3658. // need to queue up the data to be written, but *only* if none is queued
  3659. // already -- if data's already queued, the code that actually writes the
  3660. // data will make sure to wait on unconsumed pending data.
  3661. try
  3662. {
  3663. if (pendingData.length === 1)
  3664. this._waitToWriteData();
  3665. }
  3666. catch (e)
  3667. {
  3668. dumpn("!!! error waiting to write data just read, swallowing and " +
  3669. "writing only what we already have: " + e);
  3670. this._doneWritingToSink(Cr.NS_ERROR_UNEXPECTED);
  3671. return;
  3672. }
  3673. // Whee! We successfully read some data, and it's successfully queued up to
  3674. // be written. All that remains now is to wait for more data to read.
  3675. try
  3676. {
  3677. this._waitToReadData();
  3678. }
  3679. catch (e)
  3680. {
  3681. dumpn("!!! error waiting to read more data: " + e);
  3682. this._doneReadingSource(Cr.NS_ERROR_UNEXPECTED);
  3683. }
  3684. },
  3685. // NSIOUTPUTSTREAMCALLBACK
  3686. /**
  3687. * Callback when data may be written to the output stream without blocking, or
  3688. * when the output stream has been closed.
  3689. *
  3690. * @param output : nsIAsyncOutputStream
  3691. * the output stream on whose writability we've been waiting, also known as
  3692. * this._sink
  3693. */
  3694. onOutputStreamReady: function(output)
  3695. {
  3696. if (this._sink === null)
  3697. return;
  3698. dumpn("*** onOutputStreamReady");
  3699. var pendingData = this._pendingData;
  3700. if (pendingData.length === 0)
  3701. {
  3702. // There's no pending data to write. The only way this can happen is if
  3703. // we're waiting on the output stream's closure, so we can respond to a
  3704. // copying failure as quickly as possible (rather than waiting for data to
  3705. // be available to read and then fail to be copied). Therefore, we must
  3706. // be done now -- don't bother to attempt to write anything and wrap
  3707. // things up.
  3708. dumpn("!!! output stream closed prematurely, ending copy");
  3709. this._doneWritingToSink(Cr.NS_ERROR_UNEXPECTED);
  3710. return;
  3711. }
  3712. NS_ASSERT(pendingData[0].length > 0, "queued up an empty quantum?");
  3713. //
  3714. // Write out the first pending quantum of data. The possible errors here
  3715. // are:
  3716. //
  3717. // The write might fail because we can't write that much data
  3718. // Okay, we've written what we can now, so re-queue what's left and
  3719. // finish writing it out later.
  3720. // The write failed because the stream was closed
  3721. // Discard pending data that we can no longer write, stop reading, and
  3722. // signal that copying finished.
  3723. // Some other error occurred.
  3724. // Same as if the stream were closed, but notify with the status
  3725. // NS_ERROR_UNEXPECTED so the observer knows something was wonky.
  3726. //
  3727. try
  3728. {
  3729. var quantum = pendingData[0];
  3730. // XXX |quantum| isn't guaranteed to be ASCII, so we're relying on
  3731. // undefined behavior! We're only using this because writeByteArray
  3732. // is unusably broken for asynchronous output streams; see bug 532834
  3733. // for details.
  3734. var bytesWritten = output.write(quantum, quantum.length);
  3735. if (bytesWritten === quantum.length)
  3736. pendingData.shift();
  3737. else
  3738. pendingData[0] = quantum.substring(bytesWritten);
  3739. dumpn("*** wrote " + bytesWritten + " bytes of data");
  3740. }
  3741. catch (e)
  3742. {
  3743. if (wouldBlock(e))
  3744. {
  3745. NS_ASSERT(pendingData.length > 0,
  3746. "stream-blocking exception with no data to write?");
  3747. NS_ASSERT(pendingData[0].length > 0,
  3748. "stream-blocking exception with empty quantum?");
  3749. this._waitToWriteData();
  3750. return;
  3751. }
  3752. if (streamClosed(e))
  3753. dumpn("!!! output stream prematurely closed, signaling error...");
  3754. else
  3755. dumpn("!!! unknown error: " + e + ", quantum=" + quantum);
  3756. this._doneWritingToSink(Cr.NS_ERROR_UNEXPECTED);
  3757. return;
  3758. }
  3759. // The day is ours! Quantum written, now let's see if we have more data
  3760. // still to write.
  3761. try
  3762. {
  3763. if (pendingData.length > 0)
  3764. {
  3765. this._waitToWriteData();
  3766. return;
  3767. }
  3768. }
  3769. catch (e)
  3770. {
  3771. dumpn("!!! unexpected error waiting to write pending data: " + e);
  3772. this._doneWritingToSink(Cr.NS_ERROR_UNEXPECTED);
  3773. return;
  3774. }
  3775. // Okay, we have no more pending data to write -- but might we get more in
  3776. // the future?
  3777. if (this._source !== null)
  3778. {
  3779. /*
  3780. * If we might, then wait for the output stream to be closed. (We wait
  3781. * only for closure because we have no data to write -- and if we waited
  3782. * for a specific amount of data, we would get repeatedly notified for no
  3783. * reason if over time the output stream permitted more and more data to
  3784. * be written to it without blocking.)
  3785. */
  3786. this._waitForSinkClosure();
  3787. }
  3788. else
  3789. {
  3790. /*
  3791. * On the other hand, if we can't have more data because the input
  3792. * stream's gone away, then it's time to notify of copy completion.
  3793. * Victory!
  3794. */
  3795. this._sink = null;
  3796. this._cancelOrDispatchCancelCallback(Cr.NS_OK);
  3797. }
  3798. },
  3799. // NSIREQUEST
  3800. /** Returns true if the cancel observer hasn't been notified yet. */
  3801. isPending: function()
  3802. {
  3803. return !this._completed;
  3804. },
  3805. /** Not implemented, don't use! */
  3806. suspend: notImplemented,
  3807. /** Not implemented, don't use! */
  3808. resume: notImplemented,
  3809. /**
  3810. * Cancels data reading from input, asynchronously writes out any pending
  3811. * data, and causes the observer to be notified with the given error code when
  3812. * all writing has finished.
  3813. *
  3814. * @param status : nsresult
  3815. * the status to pass to the observer when data copying has been canceled
  3816. */
  3817. cancel: function(status)
  3818. {
  3819. dumpn("*** cancel(" + status.toString(16) + ")");
  3820. if (this._canceled)
  3821. {
  3822. dumpn("*** suppressing a late cancel");
  3823. return;
  3824. }
  3825. this._canceled = true;
  3826. this.status = status;
  3827. // We could be in the middle of absolutely anything at this point. Both
  3828. // input and output might still be around, we might have pending data to
  3829. // write, and in general we know nothing about the state of the world. We
  3830. // therefore must assume everything's in progress and take everything to its
  3831. // final steady state (or so far as it can go before we need to finish
  3832. // writing out remaining data).
  3833. this._doneReadingSource(status);
  3834. },
  3835. // PRIVATE IMPLEMENTATION
  3836. /**
  3837. * Stop reading input if we haven't already done so, passing e as the status
  3838. * when closing the stream, and kick off a copy-completion notice if no more
  3839. * data remains to be written.
  3840. *
  3841. * @param e : nsresult
  3842. * the status to be used when closing the input stream
  3843. */
  3844. _doneReadingSource: function(e)
  3845. {
  3846. dumpn("*** _doneReadingSource(0x" + e.toString(16) + ")");
  3847. this._finishSource(e);
  3848. if (this._pendingData.length === 0)
  3849. this._sink = null;
  3850. else
  3851. NS_ASSERT(this._sink !== null, "null output?");
  3852. // If we've written out all data read up to this point, then it's time to
  3853. // signal completion.
  3854. if (this._sink === null)
  3855. {
  3856. NS_ASSERT(this._pendingData.length === 0, "pending data still?");
  3857. this._cancelOrDispatchCancelCallback(e);
  3858. }
  3859. },
  3860. /**
  3861. * Stop writing output if we haven't already done so, discard any data that
  3862. * remained to be sent, close off input if it wasn't already closed, and kick
  3863. * off a copy-completion notice.
  3864. *
  3865. * @param e : nsresult
  3866. * the status to be used when closing input if it wasn't already closed
  3867. */
  3868. _doneWritingToSink: function(e)
  3869. {
  3870. dumpn("*** _doneWritingToSink(0x" + e.toString(16) + ")");
  3871. this._pendingData.length = 0;
  3872. this._sink = null;
  3873. this._doneReadingSource(e);
  3874. },
  3875. /**
  3876. * Completes processing of this copy: either by canceling the copy if it
  3877. * hasn't already been canceled using the provided status, or by dispatching
  3878. * the cancel callback event (with the originally provided status, of course)
  3879. * if it already has been canceled.
  3880. *
  3881. * @param status : nsresult
  3882. * the status code to use to cancel this, if this hasn't already been
  3883. * canceled
  3884. */
  3885. _cancelOrDispatchCancelCallback: function(status)
  3886. {
  3887. dumpn("*** _cancelOrDispatchCancelCallback(" + status + ")");
  3888. NS_ASSERT(this._source === null, "should have finished input");
  3889. NS_ASSERT(this._sink === null, "should have finished output");
  3890. NS_ASSERT(this._pendingData.length === 0, "should have no pending data");
  3891. if (!this._canceled)
  3892. {
  3893. this.cancel(status);
  3894. return;
  3895. }
  3896. var self = this;
  3897. var event =
  3898. {
  3899. run: function()
  3900. {
  3901. dumpn("*** onStopRequest async callback");
  3902. self._completed = true;
  3903. try
  3904. {
  3905. self._observer.onStopRequest(self, self._context, self.status);
  3906. }
  3907. catch (e)
  3908. {
  3909. NS_ASSERT(false,
  3910. "how are we throwing an exception here? we control " +
  3911. "all the callers! " + e);
  3912. }
  3913. }
  3914. };
  3915. gThreadManager.currentThread.dispatch(event, Ci.nsIThread.DISPATCH_NORMAL);
  3916. },
  3917. /**
  3918. * Kicks off another wait for more data to be available from the input stream.
  3919. */
  3920. _waitToReadData: function()
  3921. {
  3922. dumpn("*** _waitToReadData");
  3923. this._source.asyncWait(this, 0, Response.SEGMENT_SIZE,
  3924. gThreadManager.mainThread);
  3925. },
  3926. /**
  3927. * Kicks off another wait until data can be written to the output stream.
  3928. */
  3929. _waitToWriteData: function()
  3930. {
  3931. dumpn("*** _waitToWriteData");
  3932. var pendingData = this._pendingData;
  3933. NS_ASSERT(pendingData.length > 0, "no pending data to write?");
  3934. NS_ASSERT(pendingData[0].length > 0, "buffered an empty write?");
  3935. this._sink.asyncWait(this, 0, pendingData[0].length,
  3936. gThreadManager.mainThread);
  3937. },
  3938. /**
  3939. * Kicks off a wait for the sink to which data is being copied to be closed.
  3940. * We wait for stream closure when we don't have any data to be copied, rather
  3941. * than waiting to write a specific amount of data. We can't wait to write
  3942. * data because the sink might be infinitely writable, and if no data appears
  3943. * in the source for a long time we might have to spin quite a bit waiting to
  3944. * write, waiting to write again, &c. Waiting on stream closure instead means
  3945. * we'll get just one notification if the sink dies. Note that when data
  3946. * starts arriving from the sink we'll resume waiting for data to be written,
  3947. * dropping this closure-only callback entirely.
  3948. */
  3949. _waitForSinkClosure: function()
  3950. {
  3951. dumpn("*** _waitForSinkClosure");
  3952. this._sink.asyncWait(this, Ci.nsIAsyncOutputStream.WAIT_CLOSURE_ONLY, 0,
  3953. gThreadManager.mainThread);
  3954. },
  3955. /**
  3956. * Closes input with the given status, if it hasn't already been closed;
  3957. * otherwise a no-op.
  3958. *
  3959. * @param status : nsresult
  3960. * status code use to close the source stream if necessary
  3961. */
  3962. _finishSource: function(status)
  3963. {
  3964. dumpn("*** _finishSource(" + status.toString(16) + ")");
  3965. if (this._source !== null)
  3966. {
  3967. this._source.closeWithStatus(status);
  3968. this._source = null;
  3969. }
  3970. }
  3971. };
  3972. /**
  3973. * A container for utility functions used with HTTP headers.
  3974. */
  3975. const headerUtils =
  3976. {
  3977. /**
  3978. * Normalizes fieldName (by converting it to lowercase) and ensures it is a
  3979. * valid header field name (although not necessarily one specified in RFC
  3980. * 2616).
  3981. *
  3982. * @throws NS_ERROR_INVALID_ARG
  3983. * if fieldName does not match the field-name production in RFC 2616
  3984. * @returns string
  3985. * fieldName converted to lowercase if it is a valid header, for characters
  3986. * where case conversion is possible
  3987. */
  3988. normalizeFieldName: function(fieldName)
  3989. {
  3990. if (fieldName == "")
  3991. throw Cr.NS_ERROR_INVALID_ARG;
  3992. for (var i = 0, sz = fieldName.length; i < sz; i++)
  3993. {
  3994. if (!IS_TOKEN_ARRAY[fieldName.charCodeAt(i)])
  3995. {
  3996. dumpn(fieldName + " is not a valid header field name!");
  3997. throw Cr.NS_ERROR_INVALID_ARG;
  3998. }
  3999. }
  4000. return fieldName.toLowerCase();
  4001. },
  4002. /**
  4003. * Ensures that fieldValue is a valid header field value (although not
  4004. * necessarily as specified in RFC 2616 if the corresponding field name is
  4005. * part of the HTTP protocol), normalizes the value if it is, and
  4006. * returns the normalized value.
  4007. *
  4008. * @param fieldValue : string
  4009. * a value to be normalized as an HTTP header field value
  4010. * @throws NS_ERROR_INVALID_ARG
  4011. * if fieldValue does not match the field-value production in RFC 2616
  4012. * @returns string
  4013. * fieldValue as a normalized HTTP header field value
  4014. */
  4015. normalizeFieldValue: function(fieldValue)
  4016. {
  4017. // field-value = *( field-content | LWS )
  4018. // field-content = <the OCTETs making up the field-value
  4019. // and consisting of either *TEXT or combinations
  4020. // of token, separators, and quoted-string>
  4021. // TEXT = <any OCTET except CTLs,
  4022. // but including LWS>
  4023. // LWS = [CRLF] 1*( SP | HT )
  4024. //
  4025. // quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
  4026. // qdtext = <any TEXT except <">>
  4027. // quoted-pair = "\" CHAR
  4028. // CHAR = <any US-ASCII character (octets 0 - 127)>
  4029. // Any LWS that occurs between field-content MAY be replaced with a single
  4030. // SP before interpreting the field value or forwarding the message
  4031. // downstream (section 4.2); we replace 1*LWS with a single SP
  4032. var val = fieldValue.replace(/(?:(?:\r\n)?[ \t]+)+/g, " ");
  4033. // remove leading/trailing LWS (which has been converted to SP)
  4034. val = val.replace(/^ +/, "").replace(/ +$/, "");
  4035. // that should have taken care of all CTLs, so val should contain no CTLs
  4036. for (var i = 0, len = val.length; i < len; i++)
  4037. if (isCTL(val.charCodeAt(i)))
  4038. throw Cr.NS_ERROR_INVALID_ARG;
  4039. // XXX disallows quoted-pair where CHAR is a CTL -- will not invalidly
  4040. // normalize, however, so this can be construed as a tightening of the
  4041. // spec and not entirely as a bug
  4042. return val;
  4043. }
  4044. };
  4045. /**
  4046. * Converts the given string into a string which is safe for use in an HTML
  4047. * context.
  4048. *
  4049. * @param str : string
  4050. * the string to make HTML-safe
  4051. * @returns string
  4052. * an HTML-safe version of str
  4053. */
  4054. function htmlEscape(str)
  4055. {
  4056. // this is naive, but it'll work
  4057. var s = "";
  4058. for (var i = 0; i < str.length; i++)
  4059. s += "&#" + str.charCodeAt(i) + ";";
  4060. return s;
  4061. }
  4062. /**
  4063. * Constructs an object representing an HTTP version (see section 3.1).
  4064. *
  4065. * @param versionString
  4066. * a string of the form "#.#", where # is an non-negative decimal integer with
  4067. * or without leading zeros
  4068. * @throws
  4069. * if versionString does not specify a valid HTTP version number
  4070. */
  4071. function nsHttpVersion(versionString)
  4072. {
  4073. var matches = /^(\d+)\.(\d+)$/.exec(versionString);
  4074. if (!matches)
  4075. throw "Not a valid HTTP version!";
  4076. /** The major version number of this, as a number. */
  4077. this.major = parseInt(matches[1], 10);
  4078. /** The minor version number of this, as a number. */
  4079. this.minor = parseInt(matches[2], 10);
  4080. if (isNaN(this.major) || isNaN(this.minor) ||
  4081. this.major < 0 || this.minor < 0)
  4082. throw "Not a valid HTTP version!";
  4083. }
  4084. nsHttpVersion.prototype =
  4085. {
  4086. /**
  4087. * Returns the standard string representation of the HTTP version represented
  4088. * by this (e.g., "1.1").
  4089. */
  4090. toString: function ()
  4091. {
  4092. return this.major + "." + this.minor;
  4093. },
  4094. /**
  4095. * Returns true if this represents the same HTTP version as otherVersion,
  4096. * false otherwise.
  4097. *
  4098. * @param otherVersion : nsHttpVersion
  4099. * the version to compare against this
  4100. */
  4101. equals: function (otherVersion)
  4102. {
  4103. return this.major == otherVersion.major &&
  4104. this.minor == otherVersion.minor;
  4105. },
  4106. /** True if this >= otherVersion, false otherwise. */
  4107. atLeast: function(otherVersion)
  4108. {
  4109. return this.major > otherVersion.major ||
  4110. (this.major == otherVersion.major &&
  4111. this.minor >= otherVersion.minor);
  4112. }
  4113. };
  4114. nsHttpVersion.HTTP_1_0 = new nsHttpVersion("1.0");
  4115. nsHttpVersion.HTTP_1_1 = new nsHttpVersion("1.1");
  4116. /**
  4117. * An object which stores HTTP headers for a request or response.
  4118. *
  4119. * Note that since headers are case-insensitive, this object converts headers to
  4120. * lowercase before storing them. This allows the getHeader and hasHeader
  4121. * methods to work correctly for any case of a header, but it means that the
  4122. * values returned by .enumerator may not be equal case-sensitively to the
  4123. * values passed to setHeader when adding headers to this.
  4124. */
  4125. function nsHttpHeaders()
  4126. {
  4127. /**
  4128. * A hash of headers, with header field names as the keys and header field
  4129. * values as the values. Header field names are case-insensitive, but upon
  4130. * insertion here they are converted to lowercase. Header field values are
  4131. * normalized upon insertion to contain no leading or trailing whitespace.
  4132. *
  4133. * Note also that per RFC 2616, section 4.2, two headers with the same name in
  4134. * a message may be treated as one header with the same field name and a field
  4135. * value consisting of the separate field values joined together with a "," in
  4136. * their original order. This hash stores multiple headers with the same name
  4137. * in this manner.
  4138. */
  4139. this._headers = {};
  4140. }
  4141. nsHttpHeaders.prototype =
  4142. {
  4143. /**
  4144. * Sets the header represented by name and value in this.
  4145. *
  4146. * @param name : string
  4147. * the header name
  4148. * @param value : string
  4149. * the header value
  4150. * @throws NS_ERROR_INVALID_ARG
  4151. * if name or value is not a valid header component
  4152. */
  4153. setHeader: function(fieldName, fieldValue, merge)
  4154. {
  4155. var name = headerUtils.normalizeFieldName(fieldName);
  4156. var value = headerUtils.normalizeFieldValue(fieldValue);
  4157. // The following three headers are stored as arrays because their real-world
  4158. // syntax prevents joining individual headers into a single header using
  4159. // ",". See also <http://hg.mozilla.org/mozilla-central/diff/9b2a99adc05e/netwerk/protocol/http/src/nsHttpHeaderArray.cpp#l77>
  4160. if (merge && name in this._headers)
  4161. {
  4162. if (name === "www-authenticate" ||
  4163. name === "proxy-authenticate" ||
  4164. name === "set-cookie")
  4165. {
  4166. this._headers[name].push(value);
  4167. }
  4168. else
  4169. {
  4170. this._headers[name][0] += "," + value;
  4171. NS_ASSERT(this._headers[name].length === 1,
  4172. "how'd a non-special header have multiple values?")
  4173. }
  4174. }
  4175. else
  4176. {
  4177. this._headers[name] = [value];
  4178. }
  4179. },
  4180. /**
  4181. * Returns the value for the header specified by this.
  4182. *
  4183. * @throws NS_ERROR_INVALID_ARG
  4184. * if fieldName does not constitute a valid header field name
  4185. * @throws NS_ERROR_NOT_AVAILABLE
  4186. * if the given header does not exist in this
  4187. * @returns string
  4188. * the field value for the given header, possibly with non-semantic changes
  4189. * (i.e., leading/trailing whitespace stripped, whitespace runs replaced
  4190. * with spaces, etc.) at the option of the implementation; multiple
  4191. * instances of the header will be combined with a comma, except for
  4192. * the three headers noted in the description of getHeaderValues
  4193. */
  4194. getHeader: function(fieldName)
  4195. {
  4196. return this.getHeaderValues(fieldName).join("\n");
  4197. },
  4198. /**
  4199. * Returns the value for the header specified by fieldName as an array.
  4200. *
  4201. * @throws NS_ERROR_INVALID_ARG
  4202. * if fieldName does not constitute a valid header field name
  4203. * @throws NS_ERROR_NOT_AVAILABLE
  4204. * if the given header does not exist in this
  4205. * @returns [string]
  4206. * an array of all the header values in this for the given
  4207. * header name. Header values will generally be collapsed
  4208. * into a single header by joining all header values together
  4209. * with commas, but certain headers (Proxy-Authenticate,
  4210. * WWW-Authenticate, and Set-Cookie) violate the HTTP spec
  4211. * and cannot be collapsed in this manner. For these headers
  4212. * only, the returned array may contain multiple elements if
  4213. * that header has been added more than once.
  4214. */
  4215. getHeaderValues: function(fieldName)
  4216. {
  4217. var name = headerUtils.normalizeFieldName(fieldName);
  4218. if (name in this._headers)
  4219. return this._headers[name];
  4220. else
  4221. throw Cr.NS_ERROR_NOT_AVAILABLE;
  4222. },
  4223. /**
  4224. * Returns true if a header with the given field name exists in this, false
  4225. * otherwise.
  4226. *
  4227. * @param fieldName : string
  4228. * the field name whose existence is to be determined in this
  4229. * @throws NS_ERROR_INVALID_ARG
  4230. * if fieldName does not constitute a valid header field name
  4231. * @returns boolean
  4232. * true if the header's present, false otherwise
  4233. */
  4234. hasHeader: function(fieldName)
  4235. {
  4236. var name = headerUtils.normalizeFieldName(fieldName);
  4237. return (name in this._headers);
  4238. },
  4239. /**
  4240. * Returns a new enumerator over the field names of the headers in this, as
  4241. * nsISupportsStrings. The names returned will be in lowercase, regardless of
  4242. * how they were input using setHeader (header names are case-insensitive per
  4243. * RFC 2616).
  4244. */
  4245. get enumerator()
  4246. {
  4247. var headers = [];
  4248. for (var i in this._headers)
  4249. {
  4250. var supports = new SupportsString();
  4251. supports.data = i;
  4252. headers.push(supports);
  4253. }
  4254. return new nsSimpleEnumerator(headers);
  4255. }
  4256. };
  4257. /**
  4258. * Constructs an nsISimpleEnumerator for the given array of items.
  4259. *
  4260. * @param items : Array
  4261. * the items, which must all implement nsISupports
  4262. */
  4263. function nsSimpleEnumerator(items)
  4264. {
  4265. this._items = items;
  4266. this._nextIndex = 0;
  4267. }
  4268. nsSimpleEnumerator.prototype =
  4269. {
  4270. hasMoreElements: function()
  4271. {
  4272. return this._nextIndex < this._items.length;
  4273. },
  4274. getNext: function()
  4275. {
  4276. if (!this.hasMoreElements())
  4277. throw Cr.NS_ERROR_NOT_AVAILABLE;
  4278. return this._items[this._nextIndex++];
  4279. },
  4280. QueryInterface: function(aIID)
  4281. {
  4282. if (Ci.nsISimpleEnumerator.equals(aIID) ||
  4283. Ci.nsISupports.equals(aIID))
  4284. return this;
  4285. throw Cr.NS_ERROR_NO_INTERFACE;
  4286. }
  4287. };
  4288. /**
  4289. * A representation of the data in an HTTP request.
  4290. *
  4291. * @param port : uint
  4292. * the port on which the server receiving this request runs
  4293. */
  4294. function Request(port)
  4295. {
  4296. /** Method of this request, e.g. GET or POST. */
  4297. this._method = "";
  4298. /** Path of the requested resource; empty paths are converted to '/'. */
  4299. this._path = "";
  4300. /** Query string, if any, associated with this request (not including '?'). */
  4301. this._queryString = "";
  4302. /** Scheme of requested resource, usually http, always lowercase. */
  4303. this._scheme = "http";
  4304. /** Hostname on which the requested resource resides. */
  4305. this._host = undefined;
  4306. /** Port number over which the request was received. */
  4307. this._port = port;
  4308. var bodyPipe = new Pipe(false, false, 0, PR_UINT32_MAX, null);
  4309. /** Stream from which data in this request's body may be read. */
  4310. this._bodyInputStream = bodyPipe.inputStream;
  4311. /** Stream to which data in this request's body is written. */
  4312. this._bodyOutputStream = bodyPipe.outputStream;
  4313. /**
  4314. * The headers in this request.
  4315. */
  4316. this._headers = new nsHttpHeaders();
  4317. /**
  4318. * For the addition of ad-hoc properties and new functionality without having
  4319. * to change nsIHttpRequest every time; currently lazily created, as its only
  4320. * use is in directory listings.
  4321. */
  4322. this._bag = null;
  4323. }
  4324. Request.prototype =
  4325. {
  4326. // SERVER METADATA
  4327. //
  4328. // see nsIHttpRequest.scheme
  4329. //
  4330. get scheme()
  4331. {
  4332. return this._scheme;
  4333. },
  4334. //
  4335. // see nsIHttpRequest.host
  4336. //
  4337. get host()
  4338. {
  4339. return this._host;
  4340. },
  4341. //
  4342. // see nsIHttpRequest.port
  4343. //
  4344. get port()
  4345. {
  4346. return this._port;
  4347. },
  4348. // REQUEST LINE
  4349. //
  4350. // see nsIHttpRequest.method
  4351. //
  4352. get method()
  4353. {
  4354. return this._method;
  4355. },
  4356. //
  4357. // see nsIHttpRequest.httpVersion
  4358. //
  4359. get httpVersion()
  4360. {
  4361. return this._httpVersion.toString();
  4362. },
  4363. //
  4364. // see nsIHttpRequest.path
  4365. //
  4366. get path()
  4367. {
  4368. return this._path;
  4369. },
  4370. //
  4371. // see nsIHttpRequest.queryString
  4372. //
  4373. get queryString()
  4374. {
  4375. return this._queryString;
  4376. },
  4377. // HEADERS
  4378. //
  4379. // see nsIHttpRequest.getHeader
  4380. //
  4381. getHeader: function(name)
  4382. {
  4383. return this._headers.getHeader(name);
  4384. },
  4385. //
  4386. // see nsIHttpRequest.hasHeader
  4387. //
  4388. hasHeader: function(name)
  4389. {
  4390. return this._headers.hasHeader(name);
  4391. },
  4392. //
  4393. // see nsIHttpRequest.headers
  4394. //
  4395. get headers()
  4396. {
  4397. return this._headers.enumerator;
  4398. },
  4399. //
  4400. // see nsIPropertyBag.enumerator
  4401. //
  4402. get enumerator()
  4403. {
  4404. this._ensurePropertyBag();
  4405. return this._bag.enumerator;
  4406. },
  4407. //
  4408. // see nsIHttpRequest.headers
  4409. //
  4410. get bodyInputStream()
  4411. {
  4412. return this._bodyInputStream;
  4413. },
  4414. //
  4415. // see nsIPropertyBag.getProperty
  4416. //
  4417. getProperty: function(name)
  4418. {
  4419. this._ensurePropertyBag();
  4420. return this._bag.getProperty(name);
  4421. },
  4422. // NSISUPPORTS
  4423. //
  4424. // see nsISupports.QueryInterface
  4425. //
  4426. QueryInterface: function(iid)
  4427. {
  4428. if (iid.equals(Ci.nsIHttpRequest) || iid.equals(Ci.nsISupports))
  4429. return this;
  4430. throw Cr.NS_ERROR_NO_INTERFACE;
  4431. },
  4432. // PRIVATE IMPLEMENTATION
  4433. /** Ensures a property bag has been created for ad-hoc behaviors. */
  4434. _ensurePropertyBag: function()
  4435. {
  4436. if (!this._bag)
  4437. this._bag = new WritablePropertyBag();
  4438. }
  4439. };
  4440. // XPCOM trappings
  4441. if ("XPCOMUtils" in this && // Firefox 3.6 doesn't load XPCOMUtils in this scope for some reason...
  4442. "generateNSGetFactory" in XPCOMUtils) {
  4443. var NSGetFactory = XPCOMUtils.generateNSGetFactory([nsHttpServer]);
  4444. }
  4445. /**
  4446. * Creates a new HTTP server listening for loopback traffic on the given port,
  4447. * starts it, and runs the server until the server processes a shutdown request,
  4448. * spinning an event loop so that events posted by the server's socket are
  4449. * processed.
  4450. *
  4451. * This method is primarily intended for use in running this script from within
  4452. * xpcshell and running a functional HTTP server without having to deal with
  4453. * non-essential details.
  4454. *
  4455. * Note that running multiple servers using variants of this method probably
  4456. * doesn't work, simply due to how the internal event loop is spun and stopped.
  4457. *
  4458. * @note
  4459. * This method only works with Mozilla 1.9 (i.e., Firefox 3 or trunk code);
  4460. * you should use this server as a component in Mozilla 1.8.
  4461. * @param port
  4462. * the port on which the server will run, or -1 if there exists no preference
  4463. * for a specific port; note that attempting to use some values for this
  4464. * parameter (particularly those below 1024) may cause this method to throw or
  4465. * may result in the server being prematurely shut down
  4466. * @param basePath
  4467. * a local directory from which requests will be served (i.e., if this is
  4468. * "/home/jwalden/" then a request to /index.html will load
  4469. * /home/jwalden/index.html); if this is omitted, only the default URLs in
  4470. * this server implementation will be functional
  4471. */
  4472. function server(port, basePath)
  4473. {
  4474. if (basePath)
  4475. {
  4476. var lp = Cc["@mozilla.org/file/local;1"]
  4477. .createInstance(Ci.nsILocalFile);
  4478. lp.initWithPath(basePath);
  4479. }
  4480. // if you're running this, you probably want to see debugging info
  4481. DEBUG = true;
  4482. var srv = new nsHttpServer();
  4483. if (lp)
  4484. srv.registerDirectory("/", lp);
  4485. srv.registerContentType("sjs", SJS_TYPE);
  4486. srv.start(port);
  4487. var thread = gThreadManager.currentThread;
  4488. while (!srv.isStopped())
  4489. thread.processNextEvent(true);
  4490. // get rid of any pending requests
  4491. while (thread.hasPendingEvents())
  4492. thread.processNextEvent(true);
  4493. DEBUG = false;
  4494. }
  4495. function startServerAsync(port, basePath)
  4496. {
  4497. if (basePath)
  4498. {
  4499. var lp = Cc["@mozilla.org/file/local;1"]
  4500. .createInstance(Ci.nsILocalFile);
  4501. lp.initWithPath(basePath);
  4502. }
  4503. var srv = new nsHttpServer();
  4504. if (lp)
  4505. srv.registerDirectory("/", lp);
  4506. srv.registerContentType("sjs", "sjs");
  4507. srv.start(port);
  4508. return srv;
  4509. }
  4510. exports.nsHttpServer = nsHttpServer;
  4511. exports.ScriptableInputStream = ScriptableInputStream;
  4512. exports.server = server;
  4513. exports.startServerAsync = startServerAsync;