TestOpen.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /* -*- Mode: C++; tab-width: 2; 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 "TestCommon.h"
  6. #include "nsCOMPtr.h"
  7. #include "nsStringAPI.h"
  8. #include "nsIURI.h"
  9. #include "nsIChannel.h"
  10. #include "nsIHttpChannel.h"
  11. #include "nsIInputStream.h"
  12. #include "nsNetUtil.h"
  13. #include "nsServiceManagerUtils.h"
  14. #include "mozilla/Unused.h"
  15. #include "nsIScriptSecurityManager.h"
  16. #include <stdio.h>
  17. using namespace mozilla;
  18. /*
  19. * Test synchronous Open.
  20. */
  21. #define RETURN_IF_FAILED(rv, what) \
  22. PR_BEGIN_MACRO \
  23. if (NS_FAILED(rv)) { \
  24. printf(what ": failed - %08x\n", static_cast<uint32_t>(rv)); \
  25. return -1; \
  26. } \
  27. PR_END_MACRO
  28. int
  29. main(int argc, char **argv)
  30. {
  31. if (test_common_init(&argc, &argv) != 0)
  32. return -1;
  33. nsresult rv = NS_InitXPCOM2(nullptr, nullptr, nullptr);
  34. if (NS_FAILED(rv)) return -1;
  35. char buf[256];
  36. if (argc != 3) {
  37. printf("Usage: TestOpen url filename\nLoads a URL using ::Open, writing it to a file\n");
  38. return -1;
  39. }
  40. nsCOMPtr<nsIURI> uri;
  41. nsCOMPtr<nsIInputStream> stream;
  42. rv = NS_NewURI(getter_AddRefs(uri), argv[1]);
  43. RETURN_IF_FAILED(rv, "NS_NewURI");
  44. nsCOMPtr<nsIScriptSecurityManager> secman =
  45. do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv);
  46. RETURN_IF_FAILED(rv, "Couldn't get script security manager!");
  47. nsCOMPtr<nsIPrincipal> systemPrincipal;
  48. rv = secman->GetSystemPrincipal(getter_AddRefs(systemPrincipal));
  49. RETURN_IF_FAILED(rv, "Couldn't get system principal!");
  50. nsCOMPtr<nsIChannel> channel;
  51. rv = NS_NewChannel(getter_AddRefs(channel),
  52. uri,
  53. systemPrincipal,
  54. nsILoadInfo::SEC_ALLOW_CROSS_ORIGIN_DATA_IS_NULL,
  55. nsIContentPolicy::TYPE_OTHER);
  56. RETURN_IF_FAILED(rv, "NS_NewChannel");
  57. rv = channel->Open2(getter_AddRefs(stream));
  58. RETURN_IF_FAILED(rv, "channel->Open2()");
  59. FILE* outfile = fopen(argv[2], "wb");
  60. if (!outfile) {
  61. printf("error opening %s\n", argv[2]);
  62. return 1;
  63. }
  64. uint32_t read;
  65. while (NS_SUCCEEDED(stream->Read(buf, sizeof(buf), &read)) && read) {
  66. Unused << fwrite(buf, 1, read, outfile);
  67. }
  68. printf("Done\n");
  69. fclose(outfile);
  70. NS_ShutdownXPCOM(nullptr);
  71. return 0;
  72. }