nsDirectoryIndexStream.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
  2. /* vim:set sw=4 sts=4 et cin: */
  3. /* This Source Code Form is subject to the terms of the Mozilla Public
  4. * License, v. 2.0. If a copy of the MPL was not distributed with this
  5. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  6. /*
  7. The converts a filesystem directory into an "HTTP index" stream per
  8. Lou Montulli's original spec:
  9. http://www.mozilla.org/projects/netlib/dirindexformat.html
  10. */
  11. #include "nsEscape.h"
  12. #include "nsDirectoryIndexStream.h"
  13. #include "mozilla/Logging.h"
  14. #include "prtime.h"
  15. #include "nsISimpleEnumerator.h"
  16. #ifdef THREADSAFE_I18N
  17. #include "nsCollationCID.h"
  18. #include "nsICollation.h"
  19. #include "nsILocale.h"
  20. #include "nsILocaleService.h"
  21. #endif
  22. #include "nsIFile.h"
  23. #include "nsURLHelper.h"
  24. #include "nsNativeCharsetUtils.h"
  25. // NOTE: This runs on the _file transport_ thread.
  26. // The problem is that now that we're actually doing something with the data,
  27. // we want to do stuff like i18n sorting. However, none of the collation stuff
  28. // is threadsafe.
  29. // So THIS CODE IS ASCII ONLY!!!!!!!! This is no worse than the current
  30. // behaviour, though. See bug 99382.
  31. // When this is fixed, #define THREADSAFE_I18N to get this code working
  32. //#define THREADSAFE_I18N
  33. using namespace mozilla;
  34. static LazyLogModule gLog("nsDirectoryIndexStream");
  35. nsDirectoryIndexStream::nsDirectoryIndexStream()
  36. : mOffset(0), mStatus(NS_OK), mPos(0)
  37. {
  38. MOZ_LOG(gLog, LogLevel::Debug,
  39. ("nsDirectoryIndexStream[%p]: created", this));
  40. }
  41. static int compare(nsIFile* aElement1, nsIFile* aElement2, void* aData)
  42. {
  43. if (!NS_IsNativeUTF8()) {
  44. // don't check for errors, because we can't report them anyway
  45. nsAutoString name1, name2;
  46. aElement1->GetLeafName(name1);
  47. aElement2->GetLeafName(name2);
  48. // Note - we should do the collation to do sorting. Why don't we?
  49. // Because that is _slow_. Using TestProtocols to list file:///dev/
  50. // goes from 3 seconds to 22. (This may be why nsXULSortService is
  51. // so slow as well).
  52. // Does this have bad effects? Probably, but since nsXULTree appears
  53. // to use the raw RDF literal value as the sort key (which ammounts to an
  54. // strcmp), it won't be any worse, I think.
  55. // This could be made faster, by creating the keys once,
  56. // but CompareString could still be smarter - see bug 99383 - bbaetz
  57. // NB - 99393 has been WONTFIXed. So if the I18N code is ever made
  58. // threadsafe so that this matters, we'd have to pass through a
  59. // struct { nsIFile*, uint8_t* } with the pre-calculated key.
  60. return Compare(name1, name2);
  61. }
  62. nsAutoCString name1, name2;
  63. aElement1->GetNativeLeafName(name1);
  64. aElement2->GetNativeLeafName(name2);
  65. return Compare(name1, name2);
  66. }
  67. nsresult
  68. nsDirectoryIndexStream::Init(nsIFile* aDir)
  69. {
  70. nsresult rv;
  71. bool isDir;
  72. rv = aDir->IsDirectory(&isDir);
  73. if (NS_FAILED(rv)) return rv;
  74. NS_PRECONDITION(isDir, "not a directory");
  75. if (!isDir)
  76. return NS_ERROR_ILLEGAL_VALUE;
  77. if (MOZ_LOG_TEST(gLog, LogLevel::Debug)) {
  78. nsAutoCString path;
  79. aDir->GetNativePath(path);
  80. MOZ_LOG(gLog, LogLevel::Debug,
  81. ("nsDirectoryIndexStream[%p]: initialized on %s",
  82. this, path.get()));
  83. }
  84. // Sigh. We have to allocate on the heap because there are no
  85. // assignment operators defined.
  86. nsCOMPtr<nsISimpleEnumerator> iter;
  87. rv = aDir->GetDirectoryEntries(getter_AddRefs(iter));
  88. if (NS_FAILED(rv)) return rv;
  89. // Now lets sort, because clients expect it that way
  90. // XXX - should we do so here, or when the first item is requested?
  91. // XXX - use insertion sort instead?
  92. bool more;
  93. nsCOMPtr<nsISupports> elem;
  94. while (NS_SUCCEEDED(iter->HasMoreElements(&more)) && more) {
  95. rv = iter->GetNext(getter_AddRefs(elem));
  96. if (NS_SUCCEEDED(rv)) {
  97. nsCOMPtr<nsIFile> file = do_QueryInterface(elem);
  98. if (file)
  99. mArray.AppendObject(file); // addrefs
  100. }
  101. }
  102. #ifdef THREADSAFE_I18N
  103. nsCOMPtr<nsILocaleService> ls = do_GetService(NS_LOCALESERVICE_CONTRACTID,
  104. &rv);
  105. if (NS_FAILED(rv)) return rv;
  106. nsCOMPtr<nsILocale> locale;
  107. rv = ls->GetApplicationLocale(getter_AddRefs(locale));
  108. if (NS_FAILED(rv)) return rv;
  109. nsCOMPtr<nsICollationFactory> cf = do_CreateInstance(NS_COLLATIONFACTORY_CONTRACTID,
  110. &rv);
  111. if (NS_FAILED(rv)) return rv;
  112. nsCOMPtr<nsICollation> coll;
  113. rv = cf->CreateCollation(locale, getter_AddRefs(coll));
  114. if (NS_FAILED(rv)) return rv;
  115. mArray.Sort(compare, coll);
  116. #else
  117. mArray.Sort(compare, nullptr);
  118. #endif
  119. mBuf.AppendLiteral("300: ");
  120. nsAutoCString url;
  121. rv = net_GetURLSpecFromFile(aDir, url);
  122. if (NS_FAILED(rv)) return rv;
  123. mBuf.Append(url);
  124. mBuf.Append('\n');
  125. mBuf.AppendLiteral("200: filename content-length last-modified file-type\n");
  126. return NS_OK;
  127. }
  128. nsDirectoryIndexStream::~nsDirectoryIndexStream()
  129. {
  130. MOZ_LOG(gLog, LogLevel::Debug,
  131. ("nsDirectoryIndexStream[%p]: destroyed", this));
  132. }
  133. nsresult
  134. nsDirectoryIndexStream::Create(nsIFile* aDir, nsIInputStream** aResult)
  135. {
  136. RefPtr<nsDirectoryIndexStream> result = new nsDirectoryIndexStream();
  137. if (! result)
  138. return NS_ERROR_OUT_OF_MEMORY;
  139. nsresult rv = result->Init(aDir);
  140. if (NS_FAILED(rv)) {
  141. return rv;
  142. }
  143. result.forget(aResult);
  144. return NS_OK;
  145. }
  146. NS_IMPL_ISUPPORTS(nsDirectoryIndexStream, nsIInputStream)
  147. // The below routines are proxied to the UI thread!
  148. NS_IMETHODIMP
  149. nsDirectoryIndexStream::Close()
  150. {
  151. mStatus = NS_BASE_STREAM_CLOSED;
  152. return NS_OK;
  153. }
  154. NS_IMETHODIMP
  155. nsDirectoryIndexStream::Available(uint64_t* aLength)
  156. {
  157. if (NS_FAILED(mStatus))
  158. return mStatus;
  159. // If there's data in our buffer, use that
  160. if (mOffset < (int32_t)mBuf.Length()) {
  161. *aLength = mBuf.Length() - mOffset;
  162. return NS_OK;
  163. }
  164. // Returning one byte is not ideal, but good enough
  165. *aLength = (mPos < mArray.Count()) ? 1 : 0;
  166. return NS_OK;
  167. }
  168. NS_IMETHODIMP
  169. nsDirectoryIndexStream::Read(char* aBuf, uint32_t aCount, uint32_t* aReadCount)
  170. {
  171. if (mStatus == NS_BASE_STREAM_CLOSED) {
  172. *aReadCount = 0;
  173. return NS_OK;
  174. }
  175. if (NS_FAILED(mStatus))
  176. return mStatus;
  177. uint32_t nread = 0;
  178. // If anything is enqueued (or left-over) in mBuf, then feed it to
  179. // the reader first.
  180. while (mOffset < (int32_t)mBuf.Length() && aCount != 0) {
  181. *(aBuf++) = char(mBuf.CharAt(mOffset++));
  182. --aCount;
  183. ++nread;
  184. }
  185. // Room left?
  186. if (aCount > 0) {
  187. mOffset = 0;
  188. mBuf.Truncate();
  189. // Okay, now we'll suck stuff off of our iterator into the mBuf...
  190. while (uint32_t(mBuf.Length()) < aCount) {
  191. bool more = mPos < mArray.Count();
  192. if (!more) break;
  193. // don't addref, for speed - an addref happened when it
  194. // was placed in the array, so it's not going to go stale
  195. nsIFile* current = mArray.ObjectAt(mPos);
  196. ++mPos;
  197. if (MOZ_LOG_TEST(gLog, LogLevel::Debug)) {
  198. nsAutoCString path;
  199. current->GetNativePath(path);
  200. MOZ_LOG(gLog, LogLevel::Debug,
  201. ("nsDirectoryIndexStream[%p]: iterated %s",
  202. this, path.get()));
  203. }
  204. // rjc: don't return hidden files/directories!
  205. // bbaetz: why not?
  206. nsresult rv;
  207. #ifndef XP_UNIX
  208. bool hidden = false;
  209. current->IsHidden(&hidden);
  210. if (hidden) {
  211. MOZ_LOG(gLog, LogLevel::Debug,
  212. ("nsDirectoryIndexStream[%p]: skipping hidden file/directory",
  213. this));
  214. continue;
  215. }
  216. #endif
  217. int64_t fileSize = 0;
  218. current->GetFileSize( &fileSize );
  219. PRTime fileInfoModifyTime = 0;
  220. current->GetLastModifiedTime( &fileInfoModifyTime );
  221. fileInfoModifyTime *= PR_USEC_PER_MSEC;
  222. mBuf.AppendLiteral("201: ");
  223. // The "filename" field
  224. if (!NS_IsNativeUTF8()) {
  225. nsAutoString leafname;
  226. rv = current->GetLeafName(leafname);
  227. if (NS_FAILED(rv)) return rv;
  228. nsAutoCString escaped;
  229. if (!leafname.IsEmpty() &&
  230. NS_Escape(NS_ConvertUTF16toUTF8(leafname), escaped, url_Path)) {
  231. mBuf.Append(escaped);
  232. mBuf.Append(' ');
  233. }
  234. } else {
  235. nsAutoCString leafname;
  236. rv = current->GetNativeLeafName(leafname);
  237. if (NS_FAILED(rv)) return rv;
  238. nsAutoCString escaped;
  239. if (!leafname.IsEmpty() &&
  240. NS_Escape(leafname, escaped, url_Path)) {
  241. mBuf.Append(escaped);
  242. mBuf.Append(' ');
  243. }
  244. }
  245. // The "content-length" field
  246. mBuf.AppendInt(fileSize, 10);
  247. mBuf.Append(' ');
  248. // The "last-modified" field
  249. PRExplodedTime tm;
  250. PR_ExplodeTime(fileInfoModifyTime, PR_GMTParameters, &tm);
  251. {
  252. char buf[64];
  253. PR_FormatTimeUSEnglish(buf, sizeof(buf), "%a,%%20%d%%20%b%%20%Y%%20%H:%M:%S%%20GMT ", &tm);
  254. mBuf.Append(buf);
  255. }
  256. // The "file-type" field
  257. bool isFile = true;
  258. current->IsFile(&isFile);
  259. if (isFile) {
  260. mBuf.AppendLiteral("FILE ");
  261. }
  262. else {
  263. bool isDir;
  264. rv = current->IsDirectory(&isDir);
  265. if (NS_FAILED(rv)) return rv;
  266. if (isDir) {
  267. mBuf.AppendLiteral("DIRECTORY ");
  268. }
  269. else {
  270. bool isLink;
  271. rv = current->IsSymlink(&isLink);
  272. if (NS_FAILED(rv)) return rv;
  273. if (isLink) {
  274. mBuf.AppendLiteral("SYMBOLIC-LINK ");
  275. }
  276. }
  277. }
  278. mBuf.Append('\n');
  279. }
  280. // ...and once we've either run out of directory entries, or
  281. // filled up the buffer, then we'll push it to the reader.
  282. while (mOffset < (int32_t)mBuf.Length() && aCount != 0) {
  283. *(aBuf++) = char(mBuf.CharAt(mOffset++));
  284. --aCount;
  285. ++nread;
  286. }
  287. }
  288. *aReadCount = nread;
  289. return NS_OK;
  290. }
  291. NS_IMETHODIMP
  292. nsDirectoryIndexStream::ReadSegments(nsWriteSegmentFun writer, void * closure, uint32_t count, uint32_t *_retval)
  293. {
  294. return NS_ERROR_NOT_IMPLEMENTED;
  295. }
  296. NS_IMETHODIMP
  297. nsDirectoryIndexStream::IsNonBlocking(bool *aNonBlocking)
  298. {
  299. *aNonBlocking = false;
  300. return NS_OK;
  301. }