nsFeedSniffer.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #include "nsFeedSniffer.h"
  6. #include "nsNetCID.h"
  7. #include "nsXPCOM.h"
  8. #include "nsCOMPtr.h"
  9. #include "nsStringStream.h"
  10. #include "nsBrowserCompsCID.h"
  11. #include "nsICategoryManager.h"
  12. #include "nsIServiceManager.h"
  13. #include "nsComponentManagerUtils.h"
  14. #include "nsServiceManagerUtils.h"
  15. #include "nsIStreamConverterService.h"
  16. #include "nsIStreamConverter.h"
  17. #include "nsIStreamListener.h"
  18. #include "nsIHttpChannel.h"
  19. #include "nsIMIMEHeaderParam.h"
  20. #include "nsMimeTypes.h"
  21. #include "nsIURI.h"
  22. #include <algorithm>
  23. #define TYPE_ATOM "application/atom+xml"
  24. #define TYPE_RSS "application/rss+xml"
  25. #define TYPE_MAYBE_FEED "application/vnd.mozilla.maybe.feed"
  26. #define NS_RDF "http://www.w3.org/1999/02/22-rdf-syntax-ns#"
  27. #define NS_RSS "http://purl.org/rss/1.0/"
  28. #define MAX_BYTES 512u
  29. NS_IMPL_ISUPPORTS(nsFeedSniffer,
  30. nsIContentSniffer,
  31. nsIStreamListener,
  32. nsIRequestObserver)
  33. nsresult
  34. nsFeedSniffer::ConvertEncodedData(nsIRequest* request,
  35. const uint8_t* data,
  36. uint32_t length)
  37. {
  38. nsresult rv = NS_OK;
  39. mDecodedData = "";
  40. nsCOMPtr<nsIHttpChannel> httpChannel(do_QueryInterface(request));
  41. if (!httpChannel)
  42. return NS_ERROR_NO_INTERFACE;
  43. nsAutoCString contentEncoding;
  44. httpChannel->GetResponseHeader(NS_LITERAL_CSTRING("Content-Encoding"),
  45. contentEncoding);
  46. if (!contentEncoding.IsEmpty()) {
  47. nsCOMPtr<nsIStreamConverterService> converterService(do_GetService(NS_STREAMCONVERTERSERVICE_CONTRACTID));
  48. if (converterService) {
  49. ToLowerCase(contentEncoding);
  50. nsCOMPtr<nsIStreamListener> converter;
  51. rv = converterService->AsyncConvertData(contentEncoding.get(),
  52. "uncompressed", this, nullptr,
  53. getter_AddRefs(converter));
  54. NS_ENSURE_SUCCESS(rv, rv);
  55. converter->OnStartRequest(request, nullptr);
  56. nsCOMPtr<nsIStringInputStream> rawStream =
  57. do_CreateInstance(NS_STRINGINPUTSTREAM_CONTRACTID);
  58. if (!rawStream)
  59. return NS_ERROR_FAILURE;
  60. rv = rawStream->SetData((const char*)data, length);
  61. NS_ENSURE_SUCCESS(rv, rv);
  62. rv = converter->OnDataAvailable(request, nullptr, rawStream, 0, length);
  63. NS_ENSURE_SUCCESS(rv, rv);
  64. converter->OnStopRequest(request, nullptr, NS_OK);
  65. }
  66. }
  67. return rv;
  68. }
  69. template<int N>
  70. static bool
  71. StringBeginsWithLowercaseLiteral(nsAString& aString,
  72. const char (&aSubstring)[N])
  73. {
  74. return StringHead(aString, N).LowerCaseEqualsLiteral(aSubstring);
  75. }
  76. bool
  77. HasAttachmentDisposition(nsIHttpChannel* httpChannel)
  78. {
  79. if (!httpChannel)
  80. return false;
  81. uint32_t disp;
  82. nsresult rv = httpChannel->GetContentDisposition(&disp);
  83. if (NS_SUCCEEDED(rv) && disp == nsIChannel::DISPOSITION_ATTACHMENT)
  84. return true;
  85. return false;
  86. }
  87. /**
  88. * @return the first occurrence of a character within a string buffer,
  89. * or nullptr if not found
  90. */
  91. static const char*
  92. FindChar(char c, const char *begin, const char *end)
  93. {
  94. for (; begin < end; ++begin) {
  95. if (*begin == c)
  96. return begin;
  97. }
  98. return nullptr;
  99. }
  100. /**
  101. *
  102. * Determine if a substring is the "documentElement" in the document.
  103. *
  104. * All of our sniffed substrings: <rss, <feed, <rdf:RDF must be the "document"
  105. * element within the XML DOM, i.e. the root container element. Otherwise,
  106. * it's possible that someone embedded one of these tags inside a document of
  107. * another type, e.g. a HTML document, and we don't want to show the preview
  108. * page if the document isn't actually a feed.
  109. *
  110. * @param start
  111. * The beginning of the data being sniffed
  112. * @param end
  113. * The end of the data being sniffed, right before the substring that
  114. * was found.
  115. * @returns true if the found substring is the documentElement, false
  116. * otherwise.
  117. */
  118. static bool
  119. IsDocumentElement(const char *start, const char* end)
  120. {
  121. // For every tag in the buffer, check to see if it's a PI, Doctype or
  122. // comment, our desired substring or something invalid.
  123. while ( (start = FindChar('<', start, end)) ) {
  124. ++start;
  125. if (start >= end)
  126. return false;
  127. // Check to see if the character following the '<' is either '?' or '!'
  128. // (processing instruction or doctype or comment)... these are valid nodes
  129. // to have in the prologue.
  130. if (*start != '?' && *start != '!')
  131. return false;
  132. // Now advance the iterator until the '>' (We do this because we don't want
  133. // to sniff indicator substrings that are embedded within other nodes, e.g.
  134. // comments: <!-- <rdf:RDF .. > -->
  135. start = FindChar('>', start, end);
  136. if (!start)
  137. return false;
  138. ++start;
  139. }
  140. return true;
  141. }
  142. /**
  143. * Determines whether or not a string exists as the root element in an XML data
  144. * string buffer.
  145. * @param dataString
  146. * The data being sniffed
  147. * @param substring
  148. * The substring being tested for existence and root-ness.
  149. * @returns true if the substring exists and is the documentElement, false
  150. * otherwise.
  151. */
  152. static bool
  153. ContainsTopLevelSubstring(nsACString& dataString, const char *substring)
  154. {
  155. int32_t offset = dataString.Find(substring);
  156. if (offset == -1)
  157. return false;
  158. const char *begin = dataString.BeginReading();
  159. // Only do the validation when we find the substring.
  160. return IsDocumentElement(begin, begin + offset);
  161. }
  162. NS_IMETHODIMP
  163. nsFeedSniffer::GetMIMETypeFromContent(nsIRequest* request,
  164. const uint8_t* data,
  165. uint32_t length,
  166. nsACString& sniffedType)
  167. {
  168. nsCOMPtr<nsIHttpChannel> channel(do_QueryInterface(request));
  169. if (!channel)
  170. return NS_ERROR_NO_INTERFACE;
  171. // Check that this is a GET request, since you can't subscribe to a POST...
  172. nsAutoCString method;
  173. channel->GetRequestMethod(method);
  174. if (!method.EqualsLiteral("GET")) {
  175. sniffedType.Truncate();
  176. return NS_OK;
  177. }
  178. // We need to find out if this is a load of a view-source document. In this
  179. // case we do not want to override the content type, since the source display
  180. // does not need to be converted from feed format to XUL. More importantly,
  181. // we don't want to change the content type from something
  182. // nsContentDLF::CreateInstance knows about (e.g. application/xml, text/html
  183. // etc) to something that only the application fe knows about (maybe.feed)
  184. // thus deactivating syntax highlighting.
  185. nsCOMPtr<nsIURI> originalURI;
  186. channel->GetOriginalURI(getter_AddRefs(originalURI));
  187. nsAutoCString scheme;
  188. originalURI->GetScheme(scheme);
  189. if (scheme.EqualsLiteral("view-source")) {
  190. sniffedType.Truncate();
  191. return NS_OK;
  192. }
  193. // Check the Content-Type to see if it is set correctly. If it is set to
  194. // something specific that we think is a reliable indication of a feed, don't
  195. // bother sniffing since we assume the site maintainer knows what they're
  196. // doing.
  197. nsAutoCString contentType;
  198. channel->GetContentType(contentType);
  199. bool noSniff = contentType.EqualsLiteral(TYPE_RSS) ||
  200. contentType.EqualsLiteral(TYPE_ATOM);
  201. // Check to see if this was a feed request from the location bar or from
  202. // the feed: protocol. This is also a reliable indication.
  203. // The value of the header doesn't matter.
  204. if (!noSniff) {
  205. nsAutoCString sniffHeader;
  206. nsresult foundHeader =
  207. channel->GetRequestHeader(NS_LITERAL_CSTRING("X-Moz-Is-Feed"),
  208. sniffHeader);
  209. noSniff = NS_SUCCEEDED(foundHeader);
  210. }
  211. if (noSniff) {
  212. // check for an attachment after we have a likely feed.
  213. if(HasAttachmentDisposition(channel)) {
  214. sniffedType.Truncate();
  215. return NS_OK;
  216. }
  217. // set the feed header as a response header, since we have good metadata
  218. // telling us that the feed is supposed to be RSS or Atom
  219. channel->SetResponseHeader(NS_LITERAL_CSTRING("X-Moz-Is-Feed"),
  220. NS_LITERAL_CSTRING("1"), false);
  221. sniffedType.AssignLiteral(TYPE_MAYBE_FEED);
  222. return NS_OK;
  223. }
  224. // Don't sniff arbitrary types. Limit sniffing to situations that
  225. // we think can reasonably arise.
  226. if (!contentType.EqualsLiteral(TEXT_HTML) &&
  227. !contentType.EqualsLiteral(APPLICATION_OCTET_STREAM) &&
  228. // Same criterion as XMLHttpRequest. Should we be checking for "+xml"
  229. // and check for text/xml and application/xml by hand instead?
  230. contentType.Find("xml") == -1) {
  231. sniffedType.Truncate();
  232. return NS_OK;
  233. }
  234. // Now we need to potentially decompress data served with
  235. // Content-Encoding: gzip
  236. nsresult rv = ConvertEncodedData(request, data, length);
  237. if (NS_FAILED(rv))
  238. return rv;
  239. // We cap the number of bytes to scan at MAX_BYTES to prevent picking up
  240. // false positives by accidentally reading document content, e.g. a "how to
  241. // make a feed" page.
  242. const char* testData;
  243. if (mDecodedData.IsEmpty()) {
  244. testData = (const char*)data;
  245. length = std::min(length, MAX_BYTES);
  246. } else {
  247. testData = mDecodedData.get();
  248. length = std::min(mDecodedData.Length(), MAX_BYTES);
  249. }
  250. // The strategy here is based on that described in:
  251. // http://blogs.msdn.com/rssteam/articles/PublishersGuide.aspx
  252. // for interoperarbility purposes.
  253. // Thus begins the actual sniffing.
  254. nsDependentCSubstring dataString((const char*)testData, length);
  255. bool isFeed = false;
  256. // RSS 0.91/0.92/2.0
  257. isFeed = ContainsTopLevelSubstring(dataString, "<rss");
  258. // Atom 1.0
  259. if (!isFeed)
  260. isFeed = ContainsTopLevelSubstring(dataString, "<feed");
  261. // RSS 1.0
  262. if (!isFeed) {
  263. isFeed = ContainsTopLevelSubstring(dataString, "<rdf:RDF") &&
  264. dataString.Find(NS_RDF) != -1 &&
  265. dataString.Find(NS_RSS) != -1;
  266. }
  267. // If we sniffed a feed, coerce our internal type
  268. if (isFeed && !HasAttachmentDisposition(channel))
  269. sniffedType.AssignLiteral(TYPE_MAYBE_FEED);
  270. else
  271. sniffedType.Truncate();
  272. return NS_OK;
  273. }
  274. NS_IMETHODIMP
  275. nsFeedSniffer::OnStartRequest(nsIRequest* request, nsISupports* context)
  276. {
  277. return NS_OK;
  278. }
  279. nsresult
  280. nsFeedSniffer::AppendSegmentToString(nsIInputStream* inputStream,
  281. void* closure,
  282. const char* rawSegment,
  283. uint32_t toOffset,
  284. uint32_t count,
  285. uint32_t* writeCount)
  286. {
  287. nsCString* decodedData = static_cast<nsCString*>(closure);
  288. decodedData->Append(rawSegment, count);
  289. *writeCount = count;
  290. return NS_OK;
  291. }
  292. NS_IMETHODIMP
  293. nsFeedSniffer::OnDataAvailable(nsIRequest* request, nsISupports* context,
  294. nsIInputStream* stream, uint64_t offset,
  295. uint32_t count)
  296. {
  297. uint32_t read;
  298. return stream->ReadSegments(AppendSegmentToString, &mDecodedData, count,
  299. &read);
  300. }
  301. NS_IMETHODIMP
  302. nsFeedSniffer::OnStopRequest(nsIRequest* request, nsISupports* context,
  303. nsresult status)
  304. {
  305. return NS_OK;
  306. }