Download.cs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Text;
  5. using System.Xml;
  6. using winsw.Util;
  7. namespace winsw
  8. {
  9. /// <summary>
  10. /// Specify the download activities prior to the launch.
  11. /// This enables self-updating services.
  12. /// </summary>
  13. public class Download
  14. {
  15. public enum AuthType { none = 0, sspi, basic }
  16. public readonly string From;
  17. public readonly string To;
  18. public readonly AuthType Auth = AuthType.none;
  19. public readonly string Username;
  20. public readonly string Password;
  21. public readonly bool UnsecureAuth;
  22. public readonly bool FailOnError;
  23. public string ShortId { get { return String.Format("(download from {0})", From); } }
  24. public Download(string from, string to, bool failOnError = false, AuthType auth = AuthType.none,
  25. string username = null, string password = null, bool unsecureAuth = false)
  26. {
  27. From = from;
  28. To = to;
  29. FailOnError = failOnError;
  30. Auth = auth;
  31. Username = username;
  32. Password = password;
  33. UnsecureAuth = unsecureAuth;
  34. }
  35. /// <summary>
  36. /// Constructs the download setting sfrom the XML entry
  37. /// </summary>
  38. /// <param name="n">XML element</param>
  39. /// <exception cref="InvalidDataException">The required attribute is missing or the configuration is invalid</exception>
  40. internal Download(XmlElement n)
  41. {
  42. From = XmlHelper.SingleAttribute<String>(n, "from");
  43. To = XmlHelper.SingleAttribute<String>(n, "to");
  44. // All arguments below are optional
  45. FailOnError = XmlHelper.SingleAttribute<bool>(n, "failOnError", false);
  46. Auth = XmlHelper.EnumAttribute<AuthType>(n, "auth", AuthType.none);
  47. Username = XmlHelper.SingleAttribute<String>(n, "user", null);
  48. Password = XmlHelper.SingleAttribute<String>(n, "password", null);
  49. UnsecureAuth = XmlHelper.SingleAttribute<bool>(n, "unsecureAuth", false);
  50. if (Auth == AuthType.basic)
  51. {
  52. // Allow it only for HTTPS or for UnsecureAuth
  53. if (!From.StartsWith("https:") && !UnsecureAuth)
  54. {
  55. throw new InvalidDataException("Warning: you're sending your credentials in clear text to the server " + ShortId +
  56. "If you really want this you must enable 'unsecureAuth' in the configuration");
  57. }
  58. // Also fail if there is no user/password
  59. if (Username == null)
  60. {
  61. throw new InvalidDataException("Basic Auth is enabled, but username is not specified " + ShortId);
  62. }
  63. if (Password == null)
  64. {
  65. throw new InvalidDataException("Basic Auth is enabled, but password is not specified " + ShortId);
  66. }
  67. }
  68. }
  69. // Source: http://stackoverflow.com/questions/2764577/forcing-basic-authentication-in-webrequest
  70. private void SetBasicAuthHeader(WebRequest request, String username, String password)
  71. {
  72. string authInfo = username + ":" + password;
  73. authInfo = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(authInfo));
  74. request.Headers["Authorization"] = "Basic " + authInfo;
  75. }
  76. /// <summary>
  77. /// Downloads the requested file and puts it to the specified target.
  78. /// </summary>
  79. /// <exception cref="System.Net.WebException">
  80. /// Download failure. FailOnError flag should be processed outside.
  81. /// </exception>
  82. public void Perform()
  83. {
  84. WebRequest req = WebRequest.Create(From);
  85. switch (Auth)
  86. {
  87. case AuthType.none:
  88. // Do nothing
  89. break;
  90. case AuthType.sspi:
  91. req.UseDefaultCredentials = true;
  92. req.PreAuthenticate = true;
  93. req.Credentials = CredentialCache.DefaultCredentials;
  94. break;
  95. case AuthType.basic:
  96. SetBasicAuthHeader(req, Username, Password);
  97. break;
  98. default:
  99. throw new WebException("Code defect. Unsupported authentication type: " + Auth);
  100. }
  101. WebResponse rsp = req.GetResponse();
  102. FileStream tmpstream = new FileStream(To + ".tmp", FileMode.Create);
  103. CopyStream(rsp.GetResponseStream(), tmpstream);
  104. // only after we successfully downloaded a file, overwrite the existing one
  105. if (File.Exists(To))
  106. File.Delete(To);
  107. File.Move(To + ".tmp", To);
  108. }
  109. private static void CopyStream(Stream i, Stream o)
  110. {
  111. byte[] buf = new byte[8192];
  112. while (true)
  113. {
  114. int len = i.Read(buf, 0, buf.Length);
  115. if (len <= 0) break;
  116. o.Write(buf, 0, len);
  117. }
  118. i.Close();
  119. o.Close();
  120. }
  121. }
  122. }