1
0

ModNet.vb 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076
  1. Imports System.Net.Sockets
  2. Imports System.Runtime.CompilerServices
  3. Imports System.Threading.Tasks
  4. Public Module ModNet
  5. #Region "网络请求"
  6. ''' <summary>
  7. ''' 发送一次网络请求并获取返回内容。
  8. ''' </summary>
  9. Public Function NetRequestByClient(Url As String, Optional Method As HttpMethod = Nothing,
  10. Optional Content As Object = Nothing, Optional ContentType As String = Nothing, Optional Accept As String = "*/*",
  11. Optional Timeout As Integer = 25000, Optional Headers As String(,) = Nothing, Optional RequireJson As Boolean = False,
  12. Optional Encoding As Encoding = Nothing, Optional SimulateBrowserHeaders As Boolean = False, Optional MakeLog As Boolean = True) As String
  13. If Method Is Nothing Then Method = HttpMethod.Get
  14. If MakeLog Then Log("[Net] 发起网络请求(" & Method.Method & "," & Url & "),最大超时 " & Timeout)
  15. Try
  16. Dim HeaderDictionary = If(Headers, {}).ToDictionary
  17. If ContentType IsNot Nothing Then HeaderDictionary("Content-Type") = ContentType
  18. If Accept IsNot Nothing Then HeaderDictionary("Accept") = Accept
  19. Dim Result = If(Encoding, Encoding.UTF8).GetString(SendRequest(Url, Method, Content, HeaderDictionary, Timeout:=Timeout, Encoding:=Encoding, SimulateBrowserHeaders:=SimulateBrowserHeaders))
  20. '检查结果是否为完整 JSON(在 #6683 中可能返回空,在被 GFW 截断时可能不完整)
  21. '在此处检查并报错,可以让 NetRequestByClientRetry 等方法进行重试
  22. If RequireJson Then
  23. Result = Result.Trim((vbCrLf & " ").ToCharArray) 'Authlib-Injector 的结果会在末尾附带一个空行
  24. If Not (Result.StartsWithF("{") AndAlso Result.EndsWithF("}")) AndAlso
  25. Not (Result.StartsWithF("[") AndAlso Result.EndsWithF("]")) Then
  26. Throw New FormatException("返回结果并非 JSON 格式:" &
  27. If(Result.Length > 2000, Result.Substring(0, 1000) & "..." & Result.Substring(Result.Length - 1000), Result))
  28. End If
  29. End If
  30. Return Result
  31. Catch ex As FormatException
  32. Throw
  33. Catch ex As ThreadInterruptedException
  34. Throw
  35. Catch ex As Exception
  36. If MakeLog Then Log(ex, "网络请求失败", NotifyLevel.DevelopOnly)
  37. Throw
  38. End Try
  39. End Function
  40. ''' <summary>
  41. ''' 发送网络请求并获取返回内容。
  42. ''' 会进行至多 45 秒 3 次的尝试,允许最长 30s 的超时。
  43. ''' </summary>
  44. ''' <param name="BackupUrl">如果第一次尝试失败,换用的备用 URL。</param>
  45. Public Function NetRequestByClientRetry(Url As String, Optional Method As HttpMethod = Nothing, Optional BackupUrl As String = Nothing,
  46. Optional Content As Object = Nothing, Optional ContentType As String = Nothing, Optional Accept As String = "*/*",
  47. Optional Headers As String(,) = Nothing, Optional RequireJson As Boolean = False,
  48. Optional Encoding As Encoding = Nothing, Optional SimulateBrowserHeaders As Boolean = False) As String
  49. Dim RetryCount As Integer = 0
  50. Dim RetryException As Exception = Nothing
  51. Dim StartTime As Long = GetTimeMs()
  52. Try
  53. Retry:
  54. Select Case RetryCount
  55. Case 0 '正常尝试
  56. Return NetRequestByClient(Url, Method, Content, ContentType, Accept, 10000, Headers, RequireJson, Encoding, SimulateBrowserHeaders)
  57. Case 1 '慢速重试
  58. Thread.Sleep(500)
  59. Return NetRequestByClient(Url, Method, Content, ContentType, Accept, 30000, Headers, RequireJson, Encoding, SimulateBrowserHeaders)
  60. Case Else '快速重试
  61. If GetTimeMs() - StartTime > 5500 Then
  62. '若前两次加载耗费 5 秒以上,才进行重试
  63. Thread.Sleep(500)
  64. Return NetRequestByClient(Url, Method, Content, ContentType, Accept, 4000, Headers, RequireJson, Encoding, SimulateBrowserHeaders)
  65. Else
  66. Throw RetryException
  67. End If
  68. End Select
  69. Catch ex As ThreadInterruptedException
  70. Throw
  71. Catch ex As Exception
  72. If TypeOf ex Is ResponsedWebException Then
  73. If CType(ex, ResponsedWebException).StatusCode = HttpStatusCode.Forbidden Then Throw
  74. If CType(ex, ResponsedWebException).StatusCode = 429 Then Thread.Sleep(10000) 'Too Many Requests
  75. End If
  76. '重试
  77. Select Case RetryCount
  78. Case 0
  79. RetryException = ex
  80. RetryCount += 1
  81. GoTo Retry
  82. Case 1
  83. RetryCount += 1
  84. GoTo Retry
  85. Case Else
  86. Throw
  87. End Select
  88. End Try
  89. End Function
  90. ''' <summary>
  91. ''' 生成数个线程,同时发送网络请求并获取返回内容。
  92. ''' 每个线程开始之前会略有延迟。
  93. ''' </summary>
  94. Public Function NetRequestByClientMultiple(Url As String, Optional Method As HttpMethod = Nothing, Optional ThreadCount As Integer = 3,
  95. Optional Content As Object = Nothing, Optional ContentType As String = Nothing, Optional Accept As String = "*/*",
  96. Optional Headers As String(,) = Nothing, Optional RequireJson As Boolean = False, Optional Timeout As Integer = 25000,
  97. Optional Encoding As Encoding = Nothing, Optional SimulateBrowserHeaders As Boolean = False) As String
  98. Dim Threads As New List(Of Thread)
  99. Dim RequestResult = Nothing
  100. Dim RequestEx As Exception = Nothing
  101. Dim FailCount As Integer = 0
  102. For i = 1 To ThreadCount
  103. Dim th As New Thread(
  104. Sub()
  105. Try
  106. RequestResult = NetRequestByClient(Url, Method, Content, ContentType, Accept, Timeout, Headers, RequireJson, Encoding, SimulateBrowserHeaders)
  107. Catch ex As Exception
  108. FailCount += 1
  109. RequestEx = ex
  110. End Try
  111. End Sub)
  112. th.Start()
  113. Threads.Add(th)
  114. Thread.Sleep(i * 250)
  115. If RequestResult IsNot Nothing Then GoTo RequestFinished
  116. Next
  117. Do While True
  118. If RequestResult IsNot Nothing Then
  119. RequestFinished:
  120. Try
  121. For Each th In Threads
  122. If th.IsAlive Then th.Interrupt()
  123. Next
  124. Catch
  125. End Try
  126. Return RequestResult
  127. ElseIf FailCount = ThreadCount Then
  128. Try
  129. For Each th In Threads
  130. If th.IsAlive Then th.Interrupt()
  131. Next
  132. Catch
  133. End Try
  134. Throw RequestEx
  135. End If
  136. Thread.Sleep(20)
  137. Loop
  138. Return Nothing
  139. End Function
  140. ''' <summary>
  141. ''' 以多线程下载网页文件的方式获取内容。
  142. ''' 不支持缓存协商;若需缓存协商,需要换用 NetRequestByClient。
  143. ''' </summary>
  144. Public Function NetRequestByLoader(Url As String, Optional Timeout As Integer = 45000, Optional IsJson As Boolean = False, Optional SimulateBrowserHeaders As Boolean = False) As String
  145. Return NetRequestByLoader({Url}, Timeout, IsJson, SimulateBrowserHeaders)
  146. End Function
  147. ''' <summary>
  148. ''' 以多线程下载网页文件的方式获取内容。
  149. ''' 不支持缓存协商;若需缓存协商,需要换用 NetRequestByClient。
  150. ''' </summary>
  151. Public Function NetRequestByLoader(Urls As IEnumerable(Of String), Optional Timeout As Integer = 45000, Optional IsJson As Boolean = False, Optional SimulateBrowserHeaders As Boolean = False) As String
  152. Dim Temp As String = RequestTaskTempFolder() & "download.txt"
  153. Dim NewTask As New LoaderDownload("源码获取 " & GetUuid() & "#", New List(Of NetFile) From {New NetFile(Urls, Temp, New FileChecker With {.IsJson = IsJson}, SimulateBrowserHeaders)})
  154. Try
  155. NewTask.WaitForExitTime(Timeout, TimeoutMessage:="连接服务器超时(第一下载源:" & Urls.First & ")")
  156. NetRequestByLoader = ReadFile(Temp)
  157. File.Delete(Temp)
  158. Finally
  159. NewTask.Interrupt()
  160. End Try
  161. End Function
  162. #End Region
  163. #Region "文件下载"
  164. ''' <summary>
  165. ''' 通过网络请求直接下载小文件,若文件已存在将被覆盖。
  166. ''' 不建议用于下载大文件。
  167. ''' </summary>
  168. Public Sub NetDownloadByClient(Url As String, LocalPath As String, Optional SimulateBrowserHeaders As Boolean = False)
  169. Log($"[Net] 通过网络请求直接下载小文件:{Url} → {LocalPath}")
  170. '初始化文件路径
  171. Try
  172. DirectoryUtils.Create(LocalPath, isFilePath:=True)
  173. File.Delete(LocalPath)
  174. Catch ex As Exception
  175. Throw New Exception($"预处理下载文件路径失败({LocalPath})", ex)
  176. End Try
  177. '下载
  178. Dim RetryCount As Integer = 0
  179. Retry:
  180. Try
  181. File.WriteAllBytes(LocalPath, SendRequest(Url, HttpMethod.Get, SimulateBrowserHeaders:=SimulateBrowserHeaders))
  182. Catch ex As ThreadInterruptedException
  183. File.Delete(LocalPath)
  184. Throw
  185. Catch ex As Exception
  186. File.Delete(LocalPath)
  187. If RetryCount < 2 Then
  188. RetryCount += 1
  189. GoTo Retry
  190. End If
  191. Throw New WebException($"通过网络请求直接下载小文件失败({LocalPath})", ex)
  192. End Try
  193. End Sub
  194. ''' <summary>
  195. ''' 通过多线程下载引擎下载文件。
  196. ''' </summary>
  197. Public Sub NetDownloadByLoader(Url As String, LocalPath As String, Optional LoaderToSyncProgress As LoaderBase = Nothing, Optional Check As FileChecker = Nothing, Optional SimulateBrowserHeaders As Boolean = False)
  198. NetDownloadByLoader({Url}, LocalPath, LoaderToSyncProgress, Check, SimulateBrowserHeaders)
  199. End Sub
  200. ''' <summary>
  201. ''' 通过多线程下载引擎下载文件。
  202. ''' </summary>
  203. ''' <param name="Urls">文件的 Url 列表。</param>
  204. ''' <param name="LocalPath">下载的本地地址。</param>
  205. Public Sub NetDownloadByLoader(Urls As IEnumerable(Of String), LocalPath As String, Optional LoaderToSyncProgress As LoaderBase = Nothing, Optional Check As FileChecker = Nothing, Optional SimulateBrowserHeaders As Boolean = False)
  206. Dim NewTask As New LoaderDownload($"文件下载 {GetUuid()}#", New List(Of NetFile) From {New NetFile(Urls, LocalPath, Check, SimulateBrowserHeaders)})
  207. Try
  208. NewTask.WaitForExit(LoaderToSyncProgress:=LoaderToSyncProgress)
  209. Catch ex As Exception
  210. Throw New WebException($"多线程直接下载文件失败(第一下载源:" & Urls.First() & ")", ex)
  211. Finally
  212. NewTask.Interrupt()
  213. End Try
  214. End Sub
  215. #End Region
  216. #Region "基础请求引擎"
  217. '基础请求函数
  218. Private Function SendRequest(Url As String, Method As HttpMethod,
  219. Optional Content As Object = Nothing, Optional Headers As Dictionary(Of String, String) = Nothing,
  220. Optional SimulateBrowserHeaders As Boolean = False, Optional Timeout As Integer = 25000, Optional Encoding As Encoding = Nothing) As Byte()
  221. If RunInUi() AndAlso Not Url.Contains("//127.") Then Throw New Exception("在 UI 线程执行了网络请求")
  222. Dim Request As HttpRequestMessage = Nothing, CancelToken As CancellationTokenSource = Nothing,
  223. Response As HttpResponseMessage = Nothing, HostIp As String = Nothing
  224. Try
  225. Url = SecretCdnSign(Url)
  226. Request = New HttpRequestMessage(Method, Url)
  227. '写入 Content
  228. If Content IsNot Nothing AndAlso Request.Method <> HttpMethod.Get AndAlso Request.Method <> HttpMethod.Head Then
  229. If TypeOf Content Is HttpContent Then
  230. Request.Content = DirectCast(Content, HttpContent)
  231. ElseIf TypeOf Content Is Byte() Then
  232. Request.Content = New ByteArrayContent(DirectCast(Content, Byte()))
  233. ElseIf Content IsNot Nothing Then
  234. Request.Content = New ByteArrayContent(If(Encoding, Encoding.UTF8).GetBytes(Content.ToString()))
  235. End If
  236. End If
  237. '写入 Headers
  238. For Each Header In If(Headers, New Dictionary(Of String, String))
  239. If Header.Key.Lower = "content-type" Then
  240. Request.Content?.Headers.TryAddWithoutValidation(Header.Key, Header.Value)
  241. Else
  242. Request.Headers.TryAddWithoutValidation(Header.Key, Header.Value)
  243. End If
  244. Next
  245. SecretHeadersSign(Url, Request, SimulateBrowserHeaders)
  246. 'DNS 解析
  247. CancelToken = New CancellationTokenSource(Timeout)
  248. HostIp = DNSLookup(Request, CancelToken.Token)
  249. If HostIp IsNot Nothing Then IPReliability.GetOrAdd(HostIp, -0.01) '预先降低一点,这样快速的重复请求会使用不同的 IP 以提高成功率
  250. '发送请求
  251. SyncLock RequestClientLock
  252. If RequestClient Is Nothing Then '延迟初始化,以避免在程序启动前加载 CacheCow 导致 DLL 加载失败
  253. RequestClient = CacheCow.Client.ClientExtensions.CreateClient(New CacheCow.Client.FileCacheStore.FileStore(PathTemp & "Cache/Http/"), New HttpClientHandler With {
  254. .AutomaticDecompression = DecompressionMethods.Deflate Or DecompressionMethods.GZip,
  255. .UseCookies = False '不设为 False 就不能从 Header 手动传入 Cookies
  256. })
  257. End If
  258. End SyncLock
  259. CancelToken.Dispose() : CancelToken = New CancellationTokenSource(Timeout)
  260. Response = RequestClient.SendAsync(Request, HttpCompletionOption.ResponseHeadersRead, CancelToken.Token).GetResultWithTimeout(CancelToken, Timeout)
  261. Dim ResponseBytes As Byte()
  262. CancelToken.Dispose() : CancelToken = New CancellationTokenSource(Timeout)
  263. Using ResponseStream = Response.Content.ReadAsStreamAsync().GetResultWithTimeout(CancelToken, Timeout)
  264. Using Stream As New MemoryStream
  265. ResponseStream.CopyToAsync(Stream, 81920, CancelToken.Token).GetResultWithTimeout(CancelToken, Timeout)
  266. ResponseBytes = Stream.ToArray()
  267. End Using
  268. End Using
  269. '输出
  270. If Response.IsSuccessStatusCode Then
  271. RecordIPReliability(HostIp, 0.5)
  272. Return ResponseBytes
  273. Else
  274. RecordIPReliability(HostIp, -0.7)
  275. Dim ResponseMessage = If(Encoding, Encoding.UTF8).GetString(ResponseBytes)
  276. Throw New ResponsedWebException(
  277. $"错误码 {Response.StatusCode} ({CInt(Response.StatusCode)}),{Method},{Url},{HostIp}" &
  278. If(String.IsNullOrEmpty(ResponseMessage), "", vbCrLf & ResponseMessage), Response.StatusCode, ResponseMessage)
  279. End If
  280. Catch ex As ThreadInterruptedException
  281. Throw
  282. Catch ex As ResponsedWebException
  283. Throw
  284. Catch ex As FileNotFoundException
  285. '由于 CacheCow 读取缓存失败,然后系统调用不存在的 System.Net.Http.Formatting.resources 抛出(#8150)
  286. Throw New Exception($"网络请求时读取缓存失败", ex)
  287. Catch ex As Exception
  288. RecordIPReliability(HostIp, -1)
  289. If TypeOf ex Is OperationCanceledException OrElse TypeOf ex Is TimeoutException Then 'CancellationToken 超时
  290. Throw New WebException($"连接服务器超时,请稍后再试,或使用 VPN 改善网络环境({Method}, {Url},IP:{HostIp})", WebExceptionStatus.Timeout)
  291. ElseIf ex.IsNetworkRelated Then
  292. Throw New WebException($"网络请求失败,请稍后再试,或使用 VPN 改善网络环境({Method}, {Url},IP:{HostIp})", WebExceptionStatus.Timeout)
  293. Else
  294. Throw New Exception($"网络请求出现意外异常({Method}, {Url},{HostIp})", ex)
  295. End If
  296. Finally
  297. Request?.Dispose()
  298. CancelToken?.Dispose()
  299. Response?.Dispose()
  300. End Try
  301. End Function
  302. Private RequestClient As HttpClient = Nothing
  303. Private RequestClientLock As New Object
  304. ''' <summary>
  305. ''' 进行 DNS 解析。它仅在选择的 IP 与系统默认的不一致时才对 URL 中的 Host 进行替换。
  306. ''' 返回请求时应使用的 IP。若解析失败,则返回 Nothing。
  307. ''' </summary>
  308. Private Function DNSLookup(Request As HttpRequestMessage, CancelToken As CancellationToken) As String
  309. Dim Host = Request.RequestUri.Host
  310. '不对部分有严格 SNI 限制的域名进行 DNS 解析(#8295)
  311. If {"mojang.com", "minecraft.net", "minecraftservices.com"}.Any(Function(h) Host.ContainsIgnoreCase(h)) Then Return Nothing
  312. '若一分钟内已失败过,则不再重复尝试解析,以减少断网时的 Exception 数量
  313. Dim LastFailureTime As Date
  314. If DNSFailureRecord.TryGetValue(Host, LastFailureTime) Then
  315. If Date.Now - LastFailureTime < New TimeSpan(0, 1, 0) Then
  316. Return Nothing
  317. Else
  318. DNSFailureRecord.Remove(Host)
  319. End If
  320. End If
  321. '初步 DNS 解析
  322. Dim Candidates As IPAddress()
  323. Try
  324. Dim AsyncResult = Dns.BeginGetHostAddresses(Host, Nothing, Nothing)
  325. If WaitHandle.WaitAny(New WaitHandle() {AsyncResult.AsyncWaitHandle, CancelToken.WaitHandle}) Then Throw New TimeoutException("DNS 解析超时")
  326. Candidates = Dns.EndGetHostAddresses(AsyncResult).Distinct.ToArray
  327. Catch ex As Exception
  328. Log(ex, $"DNS 解析失败({Host})")
  329. DNSFailureRecord(Host) = Date.Now
  330. Return Nothing
  331. End Try
  332. If Not Candidates.Any Then
  333. Log($"[Net] DNS 解析无结果({Host})")
  334. Return Nothing
  335. End If
  336. '若同时存在 IPv4 和 IPv6 地址,仅选择其中一类(因为 GFW 可能只屏蔽了 IPv4 或 IPv6)
  337. Dim Reliabilities = Candidates.ToDictionary(Function(i) i, Function(i) IPReliability.GetOrDefault(i.ToString, 0))
  338. Dim IPv4Targets = Candidates.Where(Function(i) i.AddressFamily = AddressFamily.InterNetwork).ToArray
  339. Dim IPv6Targets = Candidates.Where(Function(i) i.AddressFamily = AddressFamily.InterNetworkV6).ToArray
  340. If IPv4Targets.Any AndAlso IPv6Targets.Any Then
  341. Dim IPv4Reliability = IPv4Targets.Max(Function(i) Reliabilities(i))
  342. Dim IPv6Reliability = IPv6Targets.Max(Function(i) Reliabilities(i))
  343. If Host = "api.modrinth.com" Then IPv6Reliability -= 0.1 '让 Modrinth 优先使用 IPv4 地址(#6887)
  344. If ModeDebug Then Log($"[Net] DNS IPv4/IPv6 选择({Host}),IPv4 {IPv4Reliability:0.000},IPv6 {IPv6Reliability:0.000}")
  345. Candidates = If(IPv4Reliability >= IPv6Reliability, IPv4Targets, IPv6Targets)
  346. End If
  347. '选择可靠度最高的 IP
  348. Dim Target As IPAddress = Candidates.MaxBy(Function(i) Reliabilities(i))
  349. Request.Headers.Host = Request.RequestUri.Authority
  350. Request.RequestUri = (New UriBuilder(Request.RequestUri) With {.Host = If(Target.AddressFamily = AddressFamily.InterNetworkV6, $"[{Target}]", Target.ToString)}).Uri
  351. Return Target.ToString
  352. End Function
  353. Private DNSFailureRecord As New ConcurrentDictionary(Of String, Date)
  354. ''' <summary>
  355. ''' 记录每个 IP 地址的请求可靠度。
  356. ''' 通常取值 -1 ~ +0.5,越高越好。未尝试过的 IP 应视为 0。
  357. ''' </summary>
  358. Private IPReliability As New ConcurrentDictionary(Of String, Double)
  359. ''' <summary>
  360. ''' 根据请求结果,记录 IP 地址的可靠度。
  361. ''' </summary>
  362. Private Sub RecordIPReliability(IP As String, Result As Double)
  363. If IP Is Nothing Then Return
  364. IPReliability.AddOrUpdate(IP,
  365. Function() Result * 0.5,
  366. Function(k, v) v * 0.5 + Result * 0.5
  367. )
  368. End Sub
  369. ''' <summary>
  370. ''' 当 HTTP 状态码不指示成功时引发的异常。
  371. ''' 附带额外属性,可用于获取远程服务器给予的回复以及 HTTP 状态码。
  372. ''' </summary>
  373. Public Class ResponsedWebException
  374. Inherits WebException
  375. ''' <summary>
  376. ''' HTTP 状态码。
  377. ''' </summary>
  378. Public StatusCode As HttpStatusCode
  379. ''' <summary>
  380. ''' 远程服务器给予的回复。
  381. ''' </summary>
  382. Public Overloads Property Response As String
  383. Public Sub New(Message As String, StatusCode As HttpStatusCode, Response As String)
  384. MyBase.New(Message)
  385. Me.StatusCode = StatusCode
  386. Me.Response = Response
  387. End Sub
  388. End Class
  389. #End Region
  390. #Region "多线程下载引擎"
  391. Private ThreadClient As New HttpClient(New HttpClientHandler With {
  392. .AutomaticDecompression = DecompressionMethods.Deflate Or DecompressionMethods.GZip
  393. })
  394. ''' <summary>
  395. ''' 最大线程数。
  396. ''' </summary>
  397. Public ReadOnly Property NetTaskThreadLimit As Integer
  398. Get
  399. Return Settings.Get("ToolDownloadThread") + 1
  400. End Get
  401. End Property
  402. ''' <summary>
  403. ''' 速度下限。
  404. ''' </summary>
  405. Public NetTaskSpeedLimitLow As Long = 256 * 1024L '256K/s
  406. ''' <summary>
  407. ''' 速度上限。若无限制则为 -1。
  408. ''' </summary>
  409. Public ReadOnly Property NetTaskSpeedLimitHigh As Long
  410. Get
  411. If _NetTaskSpeedLimitHigh Is Nothing Then
  412. Dim Setting As Integer = Settings.Get("ToolDownloadSpeed")
  413. If Setting <= 14 Then
  414. _NetTaskSpeedLimitHigh = (Setting + 1) * 0.1 * 1024 * 1024L
  415. ElseIf Setting <= 31 Then
  416. _NetTaskSpeedLimitHigh = (Setting - 11) * 0.5 * 1024 * 1024L
  417. ElseIf Setting <= 41 Then
  418. _NetTaskSpeedLimitHigh = (Setting - 21) * 1024 * 1024L
  419. Else
  420. _NetTaskSpeedLimitHigh = -1
  421. End If
  422. End If
  423. Return _NetTaskSpeedLimitHigh.Value
  424. End Get
  425. End Property
  426. Private _NetTaskSpeedLimitHigh As Long? = Nothing
  427. Public Sub UpdateNetTaskSpeedLimitHigh(Value As Integer)
  428. _NetTaskSpeedLimitHigh = Nothing
  429. End Sub
  430. ''' <summary>
  431. ''' 基于限速,当前可以下载的剩余量。
  432. ''' </summary>
  433. Public NetTaskSpeedLimitLeft As Long = -1
  434. ''' <summary>
  435. ''' 正在运行中的线程数。
  436. ''' </summary>
  437. Public NetTaskThreadCount As Integer = 0
  438. ''' <summary>
  439. ''' 下载源。
  440. ''' </summary>
  441. Public Class NetSource
  442. Public Id As Integer
  443. Public Url As String
  444. Public FailCount As Integer
  445. Public Ex As Exception
  446. ''' <summary>
  447. ''' 若该下载源正在进行强制单线程下载,标记这个唯一的线程。
  448. ''' </summary>
  449. Public SingleThread As NetThread
  450. Public IsFailed As Boolean
  451. Public Overrides Function ToString() As String
  452. Return Url
  453. End Function
  454. End Class
  455. ''' <summary>
  456. ''' 下载进度标示。
  457. ''' </summary>
  458. Public Enum NetState
  459. ''' <summary>
  460. ''' 尚未进行已存在检查。
  461. ''' </summary>
  462. WaitingToCheck = -1
  463. ''' <summary>
  464. ''' 尚未开始。
  465. ''' </summary>
  466. WaitingToDownload = 0
  467. ''' <summary>
  468. ''' 正在连接,尚未获取文件大小。
  469. ''' </summary>
  470. Connecting = 1
  471. ''' <summary>
  472. ''' 已连接,正在尝试接收首个下载数据包。
  473. ''' </summary>
  474. Reading = 2
  475. ''' <summary>
  476. ''' 正在下载。
  477. ''' </summary>
  478. Downloading = 3
  479. ''' <summary>
  480. ''' 正在合并文件。
  481. ''' </summary>
  482. Merging = 4
  483. ''' <summary>
  484. ''' 已完成。
  485. ''' </summary>
  486. Finished = 5
  487. ''' <summary>
  488. ''' 已失败或中断。
  489. ''' </summary>
  490. Interrupted = 6
  491. End Enum
  492. ''' <summary>
  493. ''' 预下载检查行为。
  494. ''' </summary>
  495. Public Enum NetPreDownloadBehaviour
  496. ''' <summary>
  497. ''' 当文件已存在时,显示提示以提醒用户是否继续下载。
  498. ''' </summary>
  499. HintWhileExists
  500. ''' <summary>
  501. ''' 当文件已存在或正在下载时,直接退出下载函数执行,不对用户进行提示。
  502. ''' </summary>
  503. ExitWhileExistsOrDownloading
  504. ''' <summary>
  505. ''' 不进行已存在检查。
  506. ''' </summary>
  507. IgnoreCheck
  508. End Enum
  509. ''' <summary>
  510. ''' 下载线程。
  511. ''' </summary>
  512. Public Class NetThread
  513. Implements IEnumerable(Of NetThread), IEquatable(Of NetThread)
  514. ''' <summary>
  515. ''' 对应的下载任务。
  516. ''' </summary>
  517. Public Task As NetFile
  518. ''' <summary>
  519. ''' 对应的线程。
  520. ''' </summary>
  521. Public Thread As Thread
  522. ''' <summary>
  523. ''' 链表中的下一个线程。
  524. ''' </summary>
  525. Public NextThread As NetThread
  526. Private ReadOnly Iterator Property [Next]() As IEnumerable(Of NetThread)
  527. Get
  528. Dim CurrentChain As NetThread = Me
  529. While CurrentChain IsNot Nothing
  530. Yield CurrentChain
  531. CurrentChain = CurrentChain.NextThread
  532. End While
  533. End Get
  534. End Property
  535. Public Function GetEnumerator() As IEnumerator(Of NetThread) Implements IEnumerable(Of NetThread).GetEnumerator
  536. Return [Next].GetEnumerator()
  537. End Function
  538. Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
  539. Return [Next].GetEnumerator()
  540. End Function
  541. ''' <summary>
  542. ''' 分配给任务中每个线程(无论其是否失败)的编号。
  543. ''' </summary>
  544. Public Uuid As Integer
  545. ''' <summary>
  546. ''' 是否为第一个线程。
  547. ''' </summary>
  548. Public ReadOnly Property IsFirstThread As Boolean
  549. Get
  550. Return DownloadStart = 0 AndAlso Task.FileSize = -2
  551. End Get
  552. End Property
  553. ''' <summary>
  554. ''' 该线程的缓存文件。
  555. ''' </summary>
  556. Public Temp As String
  557. ''' <summary>
  558. ''' 线程下载起始位置。
  559. ''' </summary>
  560. Public DownloadStart As Long
  561. ''' <summary>
  562. ''' 线程下载结束位置。
  563. ''' </summary>
  564. Public ReadOnly Property DownloadEnd As Long
  565. Get
  566. SyncLock Task.LockChain
  567. If NextThread Is Nothing Then
  568. If Task.IsUnknownSize Then
  569. Return 1000 * 1000 * 1000 * 1000L '约 1T
  570. Else
  571. Return Task.FileSize - 1
  572. End If
  573. Else
  574. Return NextThread.DownloadStart - 1
  575. End If
  576. End SyncLock
  577. End Get
  578. End Property
  579. ''' <summary>
  580. ''' 线程未下载的文件大小。
  581. ''' </summary>
  582. Public ReadOnly Property DownloadUndone As Long
  583. Get
  584. Return DownloadEnd - (DownloadStart + DownloadDone) + 1
  585. End Get
  586. End Property
  587. ''' <summary>
  588. ''' 线程已下载的文件大小。
  589. ''' </summary>
  590. Public DownloadDone As Long = 0
  591. ''' <summary>
  592. ''' 上次记速时的时间。
  593. ''' </summary>
  594. Private SpeedLastTime As Long = GetTimeMs()
  595. ''' <summary>
  596. ''' 上次记速时的已下载大小。
  597. ''' </summary>
  598. Private SpeedLastDone As Long = 0
  599. ''' <summary>
  600. ''' 当前的下载速度,单位为 Byte / 秒。
  601. ''' </summary>
  602. Public ReadOnly Property Speed As Long
  603. Get
  604. If GetTimeMs() - SpeedLastTime > 200 Then
  605. Dim DeltaTime As Long = GetTimeMs() - SpeedLastTime
  606. _Speed = (DownloadDone - SpeedLastDone) / (DeltaTime / 1000)
  607. SpeedLastDone = DownloadDone
  608. SpeedLastTime += DeltaTime
  609. End If
  610. Return _Speed
  611. End Get
  612. End Property
  613. Private _Speed As Long = 0
  614. ''' <summary>
  615. ''' 线程初始化时的时间。
  616. ''' </summary>
  617. Public InitTime As Long = GetTimeMs()
  618. ''' <summary>
  619. ''' 上次接受到有效数据的时间,-1 表示尚未有有效数据。
  620. ''' </summary>
  621. Public LastReceiveTime As Long = -1
  622. ''' <summary>
  623. ''' 当前线程的状态。
  624. ''' </summary>
  625. Public State As NetState = NetState.WaitingToDownload
  626. ''' <summary>
  627. ''' 是否已经结束。
  628. ''' </summary>
  629. Public ReadOnly Property IsEnded As Boolean
  630. Get
  631. Return State = NetState.Finished OrElse State = NetState.Interrupted
  632. End Get
  633. End Property
  634. ''' <summary>
  635. ''' 当前选取的是哪一个 Url。
  636. ''' </summary>
  637. Public Source As NetSource
  638. '允许进行 UUID 比较
  639. Public Overloads Function Equals(other As NetThread) As Boolean Implements IEquatable(Of NetThread).Equals
  640. Return other IsNot Nothing AndAlso Uuid = other.Uuid
  641. End Function
  642. Public Overrides Function Equals(obj As Object) As Boolean
  643. Return Equals(TryCast(obj, NetThread))
  644. End Function
  645. Public Shared Operator =(left As NetThread, right As NetThread) As Boolean
  646. Return EqualityComparer(Of NetThread).Default.Equals(left, right)
  647. End Operator
  648. Public Shared Operator <>(left As NetThread, right As NetThread) As Boolean
  649. Return Not left = right
  650. End Operator
  651. End Class
  652. ''' <summary>
  653. ''' 下载单个文件。
  654. ''' </summary>
  655. Public Class NetFile
  656. #Region "属性"
  657. ''' <summary>
  658. ''' 所属的文件列表任务。
  659. ''' </summary>
  660. Public Tasks As New ConcurrentList(Of LoaderDownload)
  661. ''' <summary>
  662. ''' 所有下载源。
  663. ''' </summary>
  664. Public Sources As ConcurrentList(Of NetSource)
  665. ''' <summary>
  666. ''' 用于在第一个线程出错时切换下载源。
  667. ''' </summary>
  668. Private FirstThreadSource As Integer = 0
  669. ''' <summary>
  670. ''' 所有已经被标记为失败的,但未完整尝试过的,不允许断点续传的下载源。
  671. ''' </summary>
  672. Public SourcesOnce As New ConcurrentList(Of NetSource)
  673. ''' <summary>
  674. ''' 仅当合并失败或首次下载失败时,会将所有下载源重新标记为不允许断点续传的下载源,逐个重新尝试下载。
  675. ''' 这一策略可以兼容多个下载源中的一部分返回错误的文件的情况,以及部分在多线程下载时会抽风的源。
  676. ''' </summary>
  677. Private Retried As Boolean = False
  678. ''' <summary>
  679. ''' 获取从某个源开始,第一个可用的源。
  680. ''' </summary>
  681. Private Function GetSource(Optional Id As Integer = 0) As NetSource
  682. If Id >= Sources.Count OrElse Id < 0 Then Id = 0
  683. SyncLock LockSource
  684. If HasAvailableSource(False) Then
  685. '存在多线程可用源
  686. Dim CurrentSource As NetSource = Sources(Id)
  687. While CurrentSource.IsFailed
  688. Id += 1
  689. If Id >= Sources.Count Then Id = 0
  690. CurrentSource = Sources(Id)
  691. End While
  692. Return CurrentSource
  693. ElseIf SourcesOnce.Any Then
  694. '仅存在单线程可用源
  695. Return SourcesOnce.First
  696. Else
  697. '没有可用源
  698. Return Nothing
  699. End If
  700. End SyncLock
  701. End Function
  702. ''' <summary>
  703. ''' 是否存在可用源。
  704. ''' </summary>
  705. Public Function HasAvailableSource(Optional AllowOnceSource As Boolean = True) As Boolean
  706. SyncLock LockSource
  707. If Sources.Any(Function(s) Not s.IsFailed) Then Return True '存在多线程可用源
  708. If AllowOnceSource AndAlso SourcesOnce.Any Then Return True '存在单线程可用源
  709. End SyncLock
  710. Return False
  711. End Function
  712. ''' <summary>
  713. ''' 存储在本地的带文件名的地址。
  714. ''' </summary>
  715. Public LocalPath As String = Nothing
  716. ''' <summary>
  717. ''' 存储在本地的文件名。
  718. ''' </summary>
  719. Public LocalName As String = Nothing
  720. ''' <summary>
  721. ''' 当前的下载状态。
  722. ''' </summary>
  723. Public State As NetState = NetState.WaitingToCheck
  724. ''' <summary>
  725. ''' 导致下载失败的原因。
  726. ''' </summary>
  727. Public Ex As New List(Of Exception)
  728. ''' <summary>
  729. ''' 作为文件组成部分的线程链表。
  730. ''' 如果没有线程,可以为 Nothing。
  731. ''' </summary>
  732. Public Threads As NetThread
  733. ''' <summary>
  734. ''' 文件的总大小。若为 -2 则为未获取,若为 -1 则为无法获取准确大小。
  735. ''' </summary>
  736. Public FileSize As Long = -2
  737. ''' <summary>
  738. ''' 该文件是否无法获取准确大小。
  739. ''' </summary>
  740. Public IsUnknownSize As Boolean = False
  741. ''' <summary>
  742. ''' 该文件是否不需要分割。
  743. ''' </summary>
  744. Public ReadOnly Property IsNoSplit As Boolean
  745. Get
  746. Return IsUnknownSize OrElse FileSize < 1024 * 1024 '小于 1MB 的文件不分割
  747. End Get
  748. End Property
  749. ''' <summary>
  750. ''' 为不需要分割的小文件在内存中提供临时存储。
  751. ''' </summary>
  752. Private Cache As MemoryStream
  753. ''' <summary>
  754. ''' 文件的已下载大小。
  755. ''' </summary>
  756. Public DownloadDone As Long = 0
  757. ''' <summary>
  758. ''' 文件的校验规则。
  759. ''' </summary>
  760. Public Check As FileChecker
  761. ''' <summary>
  762. ''' 是否模拟浏览器的 UserAgent 和 Referer。
  763. ''' </summary>
  764. Public SimulateBrowserHeaders As Boolean
  765. ''' <summary>
  766. ''' 上次记速时的时间。
  767. ''' </summary>
  768. Private SpeedLastTime As Long = GetTimeMs()
  769. ''' <summary>
  770. ''' 上次记速时的已下载大小。
  771. ''' </summary>
  772. Private SpeedLastDone As Long = 0
  773. ''' <summary>
  774. ''' 当前的下载速度,单位为 Byte / 秒。
  775. ''' </summary>
  776. Public ReadOnly Property Speed As Long
  777. Get
  778. If GetTimeMs() - SpeedLastTime > 200 Then
  779. Dim DeltaTime As Long = GetTimeMs() - SpeedLastTime
  780. _Speed = (DownloadDone - SpeedLastDone) / (DeltaTime / 1000)
  781. SpeedLastDone = DownloadDone
  782. SpeedLastTime += DeltaTime
  783. End If
  784. Return _Speed
  785. End Get
  786. End Property
  787. Private _Speed As Long = 0
  788. ''' <summary>
  789. ''' 该文件是否由本地文件直接拷贝完成。
  790. ''' </summary>
  791. Public IsCopy As Boolean = False
  792. ''' <summary>
  793. ''' 本文件的显示进度。
  794. ''' </summary>
  795. Public ReadOnly Property Progress As Double
  796. Get
  797. Select Case State
  798. Case NetState.WaitingToCheck
  799. Return 0
  800. Case NetState.WaitingToDownload
  801. Return 0.01
  802. Case NetState.Connecting
  803. Return 0.02
  804. Case NetState.Reading
  805. Return 0.04
  806. Case NetState.Downloading
  807. '正在下载中,对应 5% ~ 98%
  808. Dim OriginalProgress As Double = If(IsUnknownSize, 0.5, DownloadDone / Math.Max(FileSize, 1))
  809. OriginalProgress = 1 - (1 - OriginalProgress) ^ 0.9
  810. Return OriginalProgress * 0.93 + 0.05
  811. Case NetState.Merging
  812. Return 0.99
  813. Case NetState.Finished, NetState.Interrupted
  814. Return 1
  815. Case Else
  816. Throw New ArgumentOutOfRangeException("文件状态未知:" & State)
  817. End Select
  818. End Get
  819. End Property
  820. ''' <summary>
  821. ''' 各个线程建立连接成功的总次数。
  822. ''' </summary>
  823. Private ConnectCount As Integer = 0
  824. ''' <summary>
  825. ''' 各个线程建立连接成功的总时间。
  826. ''' </summary>
  827. Private ConnectTime As Long = 0
  828. ''' <summary>
  829. ''' 各个线程建立连接成功的平均时间,单位为毫秒,-1 代表尚未有成功连接。
  830. ''' </summary>
  831. Private ReadOnly Property ConnectAverage As Integer
  832. Get
  833. Dim CurrentConnectCount As Integer = ConnectCount '防止竞态条件
  834. Return If(CurrentConnectCount = 0, -1, ConnectTime / CurrentConnectCount)
  835. End Get
  836. End Property
  837. Private Const FilePieceLimit As Long = 256 * 1024
  838. Public ReadOnly LockState As New Object
  839. Public ReadOnly LockChain As New Object
  840. Public ReadOnly LockSource As New Object
  841. Public ReadOnly Uuid As Integer = GetUuid()
  842. Public Overrides Function Equals(obj As Object) As Boolean
  843. Dim file = TryCast(obj, NetFile)
  844. Return file IsNot Nothing AndAlso Uuid = file.Uuid
  845. End Function
  846. #End Region
  847. ''' <summary>
  848. ''' 新建一个需要下载的文件。
  849. ''' </summary>
  850. ''' <param name="LocalPath">包含文件名的本地地址。</param>
  851. Public Sub New(Urls As IEnumerable(Of String), LocalPath As String, Optional Checker As FileChecker = Nothing, Optional SimulateBrowserHeaders As Boolean = False)
  852. Dim Sources As New List(Of NetSource)
  853. Dim Count As Integer = 0
  854. Urls = Urls.Distinct.ToArray
  855. For Each Source As String In Urls
  856. Sources.Add(New NetSource With {.FailCount = 0, .Url = SecretCdnSign(Source.ReplaceLineEndings("").Trim), .Id = Count, .IsFailed = False, .Ex = Nothing})
  857. Count += 1
  858. Next
  859. Me.Sources = Sources
  860. Me.LocalPath = LocalPath
  861. Me.Check = Checker
  862. Me.SimulateBrowserHeaders = SimulateBrowserHeaders
  863. Me.LocalName = GetFileNameFromPath(LocalPath)
  864. End Sub
  865. ''' <summary>
  866. ''' 尝试开始一个新的下载线程。
  867. ''' 如果失败,返回 Nothing。
  868. ''' </summary>
  869. Public Function TryBeginThread() As NetThread
  870. Try
  871. Dim StartPosition As Long, StartSource As NetSource = Nothing
  872. Dim Th As Thread, ThreadInfo As NetThread
  873. '条件检测
  874. SyncLock LockSource
  875. If NetTaskThreadCount >= NetTaskThreadLimit OrElse Not HasAvailableSource() OrElse
  876. (IsNoSplit AndAlso Threads IsNot Nothing AndAlso Threads.State <> NetState.Interrupted) Then Return Nothing
  877. If State >= NetState.Merging OrElse State = NetState.WaitingToCheck Then Return Nothing
  878. SyncLock LockState
  879. If State < NetState.Connecting Then State = NetState.Connecting
  880. End SyncLock
  881. '初始化参数
  882. '获取线程起点与下载源
  883. '不分割
  884. If IsNoSplit Then GoTo StartSingleThreadDownload
  885. '只剩下单线程可用点
  886. If Not HasAvailableSource(False) Then
  887. If SourcesOnce.First.SingleThread IsNot Nothing AndAlso SourcesOnce.First.SingleThread.State <> NetState.Interrupted Then Return Nothing
  888. StartSingleThreadDownload:
  889. Reset()
  890. State = NetState.Reading
  891. End If
  892. End SyncLock
  893. SyncLock LockChain
  894. '首个开始点
  895. If Threads Is Nothing Then
  896. StartPosition = 0
  897. StartSource = GetSource(FirstThreadSource)
  898. FirstThreadSource = StartSource.Id + 1
  899. GoTo StartThread
  900. End If
  901. '寻找失败点
  902. For Each Thread As NetThread In Threads
  903. If Thread.State = NetState.Interrupted AndAlso Thread.DownloadUndone > 0 Then
  904. StartPosition = Thread.DownloadStart + Thread.DownloadDone
  905. StartSource = GetSource(Thread.Source.Id + 1)
  906. GoTo StartThread
  907. End If
  908. Next
  909. '是否禁用多线程,以及规定碎片大小
  910. Dim Source As NetSource = GetSource()
  911. If Source Is Nothing Then Return Nothing
  912. Dim TargetUrl As String = Source.Url
  913. If TargetUrl.Contains("pcl2-server") OrElse TargetUrl.Contains("meloong.com") OrElse TargetUrl.Contains("bmclapi") OrElse TargetUrl.Contains("github.com") OrElse
  914. TargetUrl.Contains("optifine.net") OrElse TargetUrl.Contains("momot.rs") Then Return Nothing
  915. '寻找最大碎片
  916. 'FUTURE: 下载引擎重做,计算下载源平均链接时间和线程下载速度,按最高时间节省来开启多线程
  917. Dim FilePieceMax As NetThread = Threads
  918. For Each Thread As NetThread In Threads
  919. If Thread.DownloadUndone > FilePieceMax.DownloadUndone Then FilePieceMax = Thread
  920. Next
  921. If FilePieceMax Is Nothing OrElse FilePieceMax.DownloadUndone < FilePieceLimit Then Return Nothing
  922. StartPosition = FilePieceMax.DownloadEnd - FilePieceMax.DownloadUndone * 0.4
  923. StartSource = GetSource()
  924. '开始线程
  925. StartThread:
  926. If (StartPosition > FileSize AndAlso FileSize >= 0 AndAlso Not IsUnknownSize) OrElse StartPosition < 0 OrElse IsNothing(StartSource) Then Return Nothing
  927. '构建线程
  928. Dim ThreadUuid As Integer = GetUuid()
  929. If Not Tasks.Any() Then Return Nothing '由于中断,已没有可用任务
  930. Th = New Thread(AddressOf Thread) With {.Name = $"下载 {Tasks(0).Uuid}/{Uuid}/{ThreadUuid}#", .Priority = ThreadPriority.BelowNormal}
  931. ThreadInfo = New NetThread With {.Uuid = ThreadUuid, .DownloadStart = StartPosition, .Thread = Th, .Source = StartSource, .Task = Me, .State = NetState.WaitingToDownload}
  932. '链表处理
  933. If ThreadInfo.IsFirstThread OrElse Threads Is Nothing Then
  934. Threads = ThreadInfo
  935. Else
  936. Dim CurrentChain As NetThread = Threads
  937. While CurrentChain.DownloadEnd <= StartPosition
  938. CurrentChain = CurrentChain.NextThread
  939. End While
  940. ThreadInfo.NextThread = CurrentChain.NextThread
  941. CurrentChain.NextThread = ThreadInfo
  942. End If
  943. End SyncLock
  944. '开始线程
  945. Interlocked.Increment(NetTaskThreadCount)
  946. SyncLock LockSource
  947. If Not HasAvailableSource(False) Then SourcesOnce.First.SingleThread = ThreadInfo
  948. End SyncLock
  949. Th.Start(ThreadInfo)
  950. Return ThreadInfo
  951. Catch ex As Exception
  952. Fail(New Exception($"尝试开始下载线程失败({LocalName})", ex))
  953. Return Nothing
  954. End Try
  955. End Function
  956. ''' <summary>
  957. ''' 每个下载线程执行的代码。
  958. ''' </summary>
  959. Private Sub Thread(Th As NetThread)
  960. If ModeDebug OrElse Th.DownloadStart = 0 Then Log($"[Download] {LocalName}:开始,起始点 {Th.DownloadStart},{Th.Source.Url}")
  961. Dim ResultStream As Stream = Nothing, HttpRequest As HttpRequestMessage = Nothing,
  962. Response As HttpResponseMessage = Nothing, ResponseStream As Stream = Nothing,
  963. CancelToken As CancellationTokenSource = Nothing, HostIp As String = Nothing
  964. '部分下载源真的特别慢,并且只需要一个请求,例如 Ping 为 20s,如果增长太慢,就会造成类似 2.5s 5s 7.5s 10s 12.5s... 的极大延迟
  965. '延迟过长会导致某些特别慢的链接迟迟不被掐死
  966. Dim Timeout As Integer = Math.Min(Math.Max(ConnectAverage, 15000) * (1 + Th.Source.FailCount), 30000)
  967. Th.State = NetState.Connecting
  968. Try
  969. Dim HttpDataCount As Integer = 0
  970. If SourcesOnce.Contains(Th.Source) AndAlso Th <> Th.Source.SingleThread Then GoTo SourceBreak
  971. HttpRequest = New HttpRequestMessage(HttpMethod.Get, Th.Source.Url)
  972. SecretHeadersSign(Th.Source.Url, HttpRequest, SimulateBrowserHeaders)
  973. CancelToken = New CancellationTokenSource(Timeout)
  974. HostIp = DNSLookup(HttpRequest, CancelToken.Token) 'DNS 预解析
  975. If Not Th.IsFirstThread Then HttpRequest.Headers.Range = New Headers.RangeHeaderValue(Th.DownloadStart, Nothing)
  976. Dim ContentLength As Long = 0
  977. Response = ThreadClient.SendAsync(HttpRequest, HttpCompletionOption.ResponseHeadersRead, CancelToken.Token).GetResultWithTimeout(CancelToken, Timeout)
  978. If Not Response.IsSuccessStatusCode Then Throw New Exception($"错误码 {Response.StatusCode} ({CInt(Response.StatusCode)}),{Th.Source.Url}") '状态码检查
  979. If State = NetState.Interrupted Then GoTo SourceBreak '快速中断
  980. If ModeDebug AndAlso Response.RequestMessage.RequestUri.ToString <> Th.Source.Url Then Log($"[Download] {LocalName}:重定向至 {Response.RequestMessage.RequestUri}")
  981. '文件大小校验
  982. ContentLength = Response.Content.Headers.ContentLength.GetValueOrDefault(-1)
  983. If ContentLength < 0 Then
  984. If FileSize > 1 Then
  985. If Th.DownloadStart = 0 Then
  986. Log($"[Download] {LocalName}:文件大小未知,但已从其他下载源获取,不作处理")
  987. Else
  988. Log($"[Download] {LocalName}:ContentLength 返回了 {ContentLength},无法确定是否支持分段下载,视作不支持")
  989. GoTo NotSupportRange
  990. End If
  991. Else
  992. FileSize = -1 : IsUnknownSize = True
  993. Log($"[Download] {LocalName}:文件大小未知")
  994. End If
  995. ElseIf Th.IsFirstThread Then
  996. If Check IsNot Nothing Then
  997. If ContentLength < Check.MinSize AndAlso Check.MinSize > 0 Then
  998. Throw New Exception($"文件大小不足,获取结果为 {ContentLength},要求至少为 {Check.MinSize}。")
  999. End If
  1000. If ContentLength <> Check.ActualSize AndAlso Check.ActualSize > 0 Then
  1001. Throw New Exception($"文件大小不一致,获取结果为 {ContentLength},要求必须为 {Check.ActualSize}。")
  1002. End If
  1003. End If
  1004. FileSize = ContentLength : IsUnknownSize = False
  1005. Log($"[Download] {LocalName}:文件大小 {ContentLength}({FormatFileSize(ContentLength)})")
  1006. '若文件大小大于 50 M,进行剩余磁盘空间校验
  1007. If ContentLength > 50 * 1024 * 1024 Then
  1008. For Each Drive As DriveInfo In DriveInfo.GetDrives
  1009. Dim DriveName As String = Drive.Name.First.ToString
  1010. Dim RequiredSpace = If(PathTemp.StartsWithF(DriveName), ContentLength * 1.1, 0) +
  1011. If(LocalPath.StartsWithF(DriveName), ContentLength + 5 * 1024 * 1024, 0)
  1012. If RequiredSpace > 0 AndAlso Drive.TotalFreeSpace < RequiredSpace Then
  1013. Throw New Exception(DriveName & " 盘空间不足,无法进行下载。" & vbCrLf & "需要至少 " & FormatFileSize(RequiredSpace) & " 空间,但当前仅剩余 " & FormatFileSize(Drive.TotalFreeSpace) & "。" &
  1014. If(PathTemp.StartsWithF(DriveName), vbCrLf & vbCrLf & "下载时需要与文件同等大小的空间存放缓存,你可以在设置中调整缓存文件夹的位置。", ""))
  1015. End If
  1016. Next
  1017. End If
  1018. ElseIf FileSize < 0 Then
  1019. Throw New Exception("非首线程运行时,尚未获取文件大小")
  1020. ElseIf Th.DownloadStart > 0 AndAlso ContentLength >= FileSize Then
  1021. NotSupportRange:
  1022. SyncLock LockSource
  1023. If SourcesOnce.Contains(Th.Source) Then GoTo SourceBreak
  1024. End SyncLock
  1025. Throw New RangeNotSupportedException($"该下载源不支持分段下载:Range 起始于 {Th.DownloadStart},预期 ContentLength 为 {FileSize - Th.DownloadStart},返回 ContentLength 为 {ContentLength},总文件大小 {FileSize}")
  1026. ElseIf Not FileSize - Th.DownloadStart = ContentLength Then
  1027. Throw New RangeNotSupportedException($"获取到的分段大小不一致:Range 起始于 {Th.DownloadStart},预期 ContentLength 为 {FileSize - Th.DownloadStart},返回 ContentLength 为 {ContentLength},总文件大小 {FileSize}")
  1028. End If
  1029. 'Log($"[Download] {LocalName} {Info.Uuid}#:通过大小检查,文件大小 {FileSize},起始点 {Info.DownloadStart},ContentLength {ContentLength}")
  1030. Th.State = NetState.Reading
  1031. SyncLock LockState
  1032. If State < NetState.Reading Then State = NetState.Reading
  1033. End SyncLock
  1034. '创建缓存文件
  1035. If IsNoSplit Then
  1036. Th.Temp = Nothing
  1037. Cache = New MemoryStream
  1038. ResultStream = Cache
  1039. Else
  1040. Th.Temp = $"{PathTemp}Download\{Uuid}_{Th.Uuid}_{RandomInteger(0, 999999)}.tmp"
  1041. DirectoryUtils.Create(Th.Temp, isFilePath:=True)
  1042. ResultStream = New FileStream(Th.Temp, FileMode.Create, FileAccess.Write, FileShare.Read)
  1043. End If
  1044. '开始下载
  1045. CancelToken.Dispose() : CancelToken = New CancellationTokenSource() '重置超时,不再让 CancellationToken 在固定时间后触发(#8488)
  1046. ResponseStream = Response.Content.ReadAsStreamAsync().GetAwaiter().GetResult()
  1047. If Settings.Get("SystemDebugDelay") Then Threading.Thread.Sleep(RandomInteger(50, 3000))
  1048. Dim ResponseBytes As Byte() = New Byte(16384) {}
  1049. HttpDataCount = ResponseStream.ReadAsync(ResponseBytes, 0, 16384, CancelToken.Token).GetResultWithTimeout(CancelToken, Timeout)
  1050. While (IsUnknownSize OrElse Th.DownloadUndone > 0) AndAlso '判断是否下载完成
  1051. HttpDataCount > 0 AndAlso Not IsProgramEnded AndAlso State < NetState.Merging AndAlso (Not Th.Source.IsFailed OrElse Th.Source.SingleThread = Th)
  1052. '限速
  1053. While NetTaskSpeedLimitHigh > 0 AndAlso NetTaskSpeedLimitLeft <= 0
  1054. Threading.Thread.Sleep(16)
  1055. End While
  1056. Dim RealDataCount As Integer = If(IsUnknownSize, HttpDataCount, Math.Min(HttpDataCount, Th.DownloadUndone))
  1057. If NetTaskSpeedLimitHigh > 0 Then Interlocked.Add(NetTaskSpeedLimitLeft, -RealDataCount)
  1058. Dim DeltaTime = GetTimeMs() - Th.LastReceiveTime
  1059. If DeltaTime > 100000000 Then DeltaTime = 1 '避免时间刻反转导致出现极大值
  1060. If RealDataCount > 0 Then
  1061. '有数据
  1062. If Th.DownloadDone = 0 Then
  1063. '第一次接受到数据
  1064. Th.State = NetState.Downloading
  1065. SyncLock LockState
  1066. If State < NetState.Downloading Then State = NetState.Downloading
  1067. End SyncLock
  1068. Interlocked.Increment(ConnectCount)
  1069. Interlocked.Add(ConnectTime, GetTimeMs() - Th.InitTime)
  1070. End If
  1071. Th.Source.FailCount = 0
  1072. For Each Task In Tasks
  1073. Task.FailCount = 0
  1074. Next
  1075. Interlocked.Add(NetManager.DownloadDone, RealDataCount)
  1076. Interlocked.Add(DownloadDone, RealDataCount)
  1077. Th.DownloadDone += RealDataCount
  1078. ResultStream.Write(ResponseBytes, 0, RealDataCount)
  1079. '已完成
  1080. If Th.DownloadUndone = 0 AndAlso Not IsUnknownSize Then Exit While
  1081. '检查速度是否过慢
  1082. If Th.LastReceiveTime > 0 AndAlso DeltaTime > 5000 AndAlso DeltaTime > RealDataCount AndAlso '数据包间隔大于 5s,且速度小于 1K/s
  1083. Th.Source.SingleThread Is Nothing Then '且并非单线程下载
  1084. Throw New TimeoutException("由于速度过慢断开链接,下载 " & RealDataCount & " B,消耗 " & DeltaTime & " ms。")
  1085. End If
  1086. Th.LastReceiveTime = GetTimeMs()
  1087. ElseIf Th.LastReceiveTime > 0 AndAlso DeltaTime > Timeout Then
  1088. '无数据,且已超时
  1089. Throw New TimeoutException("操作超时,无数据。")
  1090. End If
  1091. HttpDataCount = ResponseStream.ReadAsync(ResponseBytes, 0, 16384, CancelToken.Token).GetResultWithTimeout(CancelToken, Timeout)
  1092. End While
  1093. SourceBreak:
  1094. If State = NetState.Interrupted OrElse (Th.Source.IsFailed AndAlso Th.Source.SingleThread <> Th) OrElse (Th.DownloadUndone > 0 AndAlso Not IsUnknownSize) Then
  1095. '被外部中断
  1096. Th.State = NetState.Interrupted
  1097. Log($"[Download] {LocalName}:中断")
  1098. ElseIf HttpDataCount = 0 AndAlso Th.DownloadUndone > 0 AndAlso Not IsUnknownSize Then
  1099. '服务器无返回数据
  1100. Throw New Exception($"返回的 ContentLength 过多:ContentLength 为 {ContentLength},但获取到的总数据量仅为 {Th.DownloadDone}(全文件总数据量 {DownloadDone})")
  1101. Else
  1102. '本线程完成
  1103. Th.State = NetState.Finished
  1104. If ModeDebug Then Log($"[Download] {LocalName}:完成,已下载 {Th.DownloadDone}({Th.DownloadStart}~{Th.DownloadEnd})")
  1105. RecordIPReliability(HostIp, 0.5)
  1106. End If
  1107. Catch ex As Exception
  1108. Log($"[Download] {LocalName}:出错,{If(TypeOf ex Is OperationCanceledException OrElse TypeOf ex Is TimeoutException,
  1109. $"已超时({Timeout}ms)", ex.GetDetail())},IP:{HostIp}")
  1110. RecordIPReliability(HostIp, -0.7)
  1111. SourceFail(Th, ex, False)
  1112. Finally
  1113. '释放资源
  1114. HttpRequest?.Dispose()
  1115. Response?.Dispose()
  1116. ResponseStream?.Dispose()
  1117. CancelToken?.Dispose()
  1118. If Not IsNoSplit Then ResultStream?.Dispose()
  1119. '改变计数
  1120. Interlocked.Decrement(NetTaskThreadCount)
  1121. '合并
  1122. If ((FileSize >= 0 AndAlso DownloadDone >= FileSize) OrElse (FileSize = -1 AndAlso DownloadDone > 0)) AndAlso
  1123. State < NetState.Merging AndAlso Th.State <> NetState.Interrupted Then Merge(Th)
  1124. End Try
  1125. End Sub
  1126. Private Sub SourceFail(Th As NetThread, ex As Exception, IsMergeFailure As Boolean)
  1127. '状态变更
  1128. Interlocked.Increment(Th.Source.FailCount)
  1129. For Each Task In Tasks
  1130. Interlocked.Increment(Task.FailCount)
  1131. Next
  1132. Th.State = NetState.Interrupted
  1133. Th.Source.Ex = ex
  1134. '根据情况判断,是否在多线程下禁用下载源(连续错误过多,或不支持断点续传)
  1135. Dim IsRangeNotSupported As Boolean = TypeOf ex Is RangeNotSupportedException OrElse ex.Message.Contains("(416)")
  1136. If IsMergeFailure OrElse IsRangeNotSupported OrElse
  1137. ex.Message.Contains("(502)") OrElse ex.Message.Contains("(404)") OrElse
  1138. ex.Message.Contains("未能解析") OrElse ex.Message.Contains("无返回数据") OrElse ex.Message.Contains("空间不足") OrElse
  1139. ((ex.Message.Contains("(403)") OrElse ex.Message.Contains("(429)")) AndAlso Not Th.Source.Url.Contains("bmclapi")) OrElse 'BMCLAPI 的部分源在高频率请求下会返回 403/429,所以不应因此禁用下载源
  1140. (Th.Source.FailCount >= NetTaskThreadLimit.Clamp(5, 30) AndAlso DownloadDone < 1) OrElse Th.Source.FailCount > NetTaskThreadLimit + 2 Then
  1141. '当一个下载源有多个线程在下载时,只选择其中一个线程进行后续处理
  1142. Dim IsThisFail As Boolean = False
  1143. SyncLock LockSource
  1144. If Not Th.Source.IsFailed OrElse Th.Source.SingleThread = Th Then
  1145. IsThisFail = True
  1146. Th.Source.IsFailed = True
  1147. End If
  1148. End SyncLock
  1149. '……后续处理
  1150. If IsThisFail Then
  1151. Log($"[Download] {LocalName}:下载源被禁用({Th.Source.Id},Range 问题:{IsRangeNotSupported}):{Th.Source.Url}")
  1152. Log(ex, $"{If(SourcesOnce.FirstOrDefault?.SingleThread Is Nothing, "", "单线程")}下载源 {Th.Source.Id} 已被禁用",
  1153. If(IsRangeNotSupported OrElse ex.Message.Contains("(404)"), NotifyLevel.DevelopOnly, NotifyLevel.DebugModeOnly))
  1154. SyncLock LockSource
  1155. SourcesOnce.Remove(Th.Source)
  1156. End SyncLock
  1157. If ex.Message.Contains("空间不足") Then
  1158. '硬盘空间不足:强制失败
  1159. Fail(ex)
  1160. ElseIf HasAvailableSource() AndAlso Not IsMergeFailure Then
  1161. '当前源失败,但还有下载源:正常地继续执行
  1162. ElseIf Not Retried Then
  1163. '合并失败或首次下载失败,未重试:将所有下载源重新标记为不允许断点续传的下载源,逐个重新尝试下载
  1164. '若所有源均不支持 Range,也会走到这里重试
  1165. If Not IsRangeNotSupported Then Log($"[Download] {LocalName}:文件下载失败,正在自动重试……", NotifyLevel.DebugModeOnly)
  1166. Retried = True
  1167. SyncLock LockSource
  1168. SourcesOnce.Clear()
  1169. For Each Source In Sources
  1170. SourcesOnce.Add(Source)
  1171. Source.IsFailed = True
  1172. Next
  1173. End SyncLock
  1174. Reset()
  1175. SyncLock LockState
  1176. State = NetState.WaitingToDownload
  1177. End SyncLock
  1178. ElseIf HasAvailableSource() AndAlso IsMergeFailure Then
  1179. '合并失败且单个源失败:继续下一个源
  1180. Reset()
  1181. SyncLock LockState
  1182. State = NetState.WaitingToDownload
  1183. End SyncLock
  1184. Else
  1185. '失败
  1186. Log($"[Download] {LocalName}:已无可用下载源,下载失败")
  1187. Dim ExampleEx As Exception = Nothing
  1188. SyncLock LockSource
  1189. For Each Source As NetSource In Sources
  1190. Log("[Download] 已禁用的下载源:" & Source.Url)
  1191. If Source.Ex IsNot Nothing Then
  1192. ExampleEx = Source.Ex
  1193. Log(Source.Ex, "下载源禁用原因", NotifyLevel.DevelopOnly)
  1194. End If
  1195. Next
  1196. End SyncLock
  1197. Fail(ExampleEx)
  1198. End If
  1199. End If
  1200. End If
  1201. '清理当前已下载的内容
  1202. If FileSize = -2 Then Reset()
  1203. End Sub
  1204. Private Sub Reset()
  1205. FileSize = -2
  1206. Cache?.Dispose() : Cache = Nothing
  1207. SyncLock LockChain
  1208. Threads = Nothing
  1209. End SyncLock
  1210. Interlocked.Add(NetManager.DownloadDone, -DownloadDone)
  1211. DownloadDone = 0
  1212. SpeedLastDone = 0
  1213. End Sub
  1214. '最终收束事件
  1215. ''' <summary>
  1216. ''' 下载完成。合并文件。
  1217. ''' </summary>
  1218. Private Sub Merge(Th As NetThread)
  1219. '状态判断
  1220. SyncLock LockState
  1221. If State < NetState.Merging Then
  1222. State = NetState.Merging
  1223. Else
  1224. Return
  1225. End If
  1226. End SyncLock
  1227. Dim RetryCount As Integer = 0
  1228. Try
  1229. Retry:
  1230. '创建文件夹
  1231. DirectoryUtils.Create(LocalPath, isFilePath:=True)
  1232. If File.Exists(LocalPath) Then File.Delete(LocalPath)
  1233. SyncLock LockChain
  1234. '合并文件
  1235. If IsNoSplit Then
  1236. '仅有一个线程,从内存中输出
  1237. If ModeDebug Then Log($"[Download] {LocalName}:下载结束,从内存输出文件")
  1238. FileUtils.Write(LocalPath, Cache)
  1239. ElseIf Threads.DownloadDone = DownloadDone AndAlso Threads.Temp IsNot Nothing Then
  1240. '仅有一个文件,直接复制
  1241. If ModeDebug Then Log($"[Download] {LocalName}:下载结束,仅有一个文件,无需合并")
  1242. CopyFile(Threads.Temp, LocalPath)
  1243. Else
  1244. '有多个线程,合并
  1245. If ModeDebug Then Log($"[Download] {LocalName}:下载结束,开始合并文件")
  1246. Using MergeFile As New FileStream(LocalPath, FileMode.Create)
  1247. Using AddWriter As New BinaryWriter(MergeFile)
  1248. For Each Thread As NetThread In Threads
  1249. If Thread.DownloadDone = 0 OrElse Thread.Temp Is Nothing Then Continue For
  1250. Using fs As New FileStream(Thread.Temp, FileMode.Open, FileAccess.Read, FileShare.Read)
  1251. Using TempReader As New BinaryReader(fs)
  1252. AddWriter.Write(TempReader.ReadBytes(Thread.DownloadDone))
  1253. End Using
  1254. End Using
  1255. Next
  1256. End Using
  1257. End Using
  1258. End If
  1259. '检查文件
  1260. Dim CheckResult As String = Check?.Check(LocalPath)
  1261. If CheckResult Is Nothing AndAlso Not IsUnknownSize AndAlso Check IsNot Nothing Then
  1262. If Check.ActualSize = -1 Then
  1263. CheckResult = (New FileChecker With {.ActualSize = FileSize}).Check(LocalPath) '不修改原始的 Checker,以免污染原始实例
  1264. ElseIf Check.ActualSize <> FileSize Then
  1265. CheckResult = $"文件大小不一致:任务校验要求为 {Check.ActualSize},请求结果为 {FileSize}"
  1266. End If
  1267. End If
  1268. If CheckResult IsNot Nothing Then
  1269. Log($"[Download] {LocalName} 文件校验失败,下载线程细节:")
  1270. For Each T As NetThread In Threads
  1271. Log($"[Download] - {T.Uuid}#,状态 {GetStringFromEnum(T.State)},范围 {T.DownloadStart}~{T.DownloadEnd},已下载 {T.DownloadDone},未下载 {T.DownloadUndone}")
  1272. Next
  1273. Throw New Exception(CheckResult)
  1274. End If
  1275. '后处理
  1276. If Not IsNoSplit Then
  1277. For Each Thread As NetThread In Threads
  1278. If Thread.Temp IsNot Nothing Then File.Delete(Thread.Temp)
  1279. Next
  1280. End If
  1281. Finish()
  1282. End SyncLock
  1283. Catch ex As Exception
  1284. RetryCount += 1
  1285. If State > NetState.Merging Then Return '通常是因为在合并时被中断了
  1286. Log(ex, $"合并文件出错,第 {RetryCount} 次尝试({LocalName})")
  1287. '重新尝试合并
  1288. If RetryCount < 3 Then
  1289. Threading.Thread.Sleep(500 * RetryCount)
  1290. GoTo Retry
  1291. End If
  1292. '失败,禁用当前下载源并重启下载
  1293. Try
  1294. If File.Exists(LocalPath) Then File.Delete(LocalPath)
  1295. Catch exx As Exception
  1296. Log(ex, $"删除合并失败的文件出错({LocalPath})")
  1297. End Try
  1298. SourceFail(Th, ex, True)
  1299. Finally
  1300. Cache?.Dispose()
  1301. End Try
  1302. End Sub
  1303. ''' <summary>
  1304. ''' 下载失败。
  1305. ''' </summary>
  1306. Private Sub Fail(Optional RaiseEx As Exception = Nothing)
  1307. SyncLock LockState
  1308. If State >= NetState.Finished Then Return
  1309. If RaiseEx IsNot Nothing Then Ex.Add(RaiseEx)
  1310. '凉凉
  1311. Log($"[Download] {LocalName}:已失败,当前状态 {State}")
  1312. State = NetState.Interrupted
  1313. End SyncLock
  1314. InterruptInternal()
  1315. For Each Task In Tasks
  1316. Task.OnFileFail(Me)
  1317. Next
  1318. End Sub
  1319. ''' <summary>
  1320. ''' 下载中断。
  1321. ''' </summary>
  1322. Public Sub Interrupt(InterruptedTask As LoaderDownload)
  1323. '从特定任务中移除,如果它还属于其他任务,则继续下载
  1324. Tasks.Remove(InterruptedTask)
  1325. If Tasks.Any Then Return
  1326. '确认中断
  1327. SyncLock LockState
  1328. If State >= NetState.Finished Then Return
  1329. Log($"[Download] {LocalName}:已中断,当前状态 {State}")
  1330. State = NetState.Interrupted
  1331. End SyncLock
  1332. InterruptInternal()
  1333. End Sub
  1334. Private Sub InterruptInternal()
  1335. On Error Resume Next
  1336. Reset()
  1337. Interlocked.Decrement(NetManager.FileRemain)
  1338. End Sub
  1339. '状态改变接口
  1340. ''' <summary>
  1341. ''' 将该文件设置为已下载完成。
  1342. ''' </summary>
  1343. Public Sub Finish(Optional PrintLog As Boolean = True)
  1344. SyncLock LockState
  1345. If State >= NetState.Finished Then Return
  1346. State = NetState.Finished
  1347. End SyncLock
  1348. Interlocked.Decrement(NetManager.FileRemain)
  1349. If PrintLog Then Log($"[Download] {LocalName}:已完成")
  1350. For Each Task In Tasks
  1351. Task.OnFileFinish(Me)
  1352. Next
  1353. End Sub
  1354. End Class
  1355. Private Class RangeNotSupportedException
  1356. Inherits WebException
  1357. Public Sub New(Message As String)
  1358. MyBase.New(Message)
  1359. End Sub
  1360. End Class
  1361. ''' <summary>
  1362. ''' 下载一系列文件的加载器。
  1363. ''' </summary>
  1364. Public Class LoaderDownload
  1365. Inherits LoaderBase
  1366. #Region "属性"
  1367. ''' <summary>
  1368. ''' 需要下载的文件。
  1369. ''' </summary>
  1370. Public Files As ConcurrentList(Of NetFile)
  1371. ''' <summary>
  1372. ''' 剩余未完成的文件数。(用于减轻 FilesLock 的占用)
  1373. ''' </summary>
  1374. Private FileRemain As Integer
  1375. Private ReadOnly FileRemainLock As New Object
  1376. ''' <summary>
  1377. ''' 用于显示的百分比进度。
  1378. ''' </summary>
  1379. Public Overrides Property Progress As Double
  1380. Get
  1381. If State >= LoadState.Finished Then Return 1
  1382. If Not Files.Any() Then Return 0 '必须返回 0,否则在获取列表的时候会错觉已经下载完了
  1383. Return _Progress
  1384. End Get
  1385. Set(value As Double)
  1386. Throw New Exception("文件下载不允许指定进度")
  1387. End Set
  1388. End Property
  1389. Private _Progress As Double = 0
  1390. ''' <summary>
  1391. ''' 任务中的文件的连续失败计数。
  1392. ''' </summary>
  1393. Public Property FailCount As Integer
  1394. Get
  1395. Return _FailCount
  1396. End Get
  1397. Set(value As Integer)
  1398. _FailCount = value
  1399. If State = LoadState.Loading AndAlso value >= Math.Min(10000, Math.Max(FileRemain * 5.5, NetTaskThreadLimit * 5.5 + 3)) Then
  1400. Log("[Download] 由于同加载器中失败次数过多引发强制失败:连续失败了 " & value & " 次", NotifyLevel.DebugModeOnly)
  1401. On Error Resume Next
  1402. Dim ExList As New List(Of Exception)
  1403. For Each File In Files
  1404. For Each Source In File.Sources
  1405. If Source.Ex IsNot Nothing Then
  1406. ExList.Add(Source.Ex)
  1407. If ExList.Count > 10 Then GoTo FinishExCatch
  1408. End If
  1409. Next
  1410. Next
  1411. FinishExCatch:
  1412. OnFail(ExList)
  1413. End If
  1414. End Set
  1415. End Property
  1416. Private _FailCount As Integer = 0
  1417. #End Region
  1418. ''' <summary>
  1419. ''' 刷新公开属性。由 NetManager 每 0.1 秒调用一次。
  1420. ''' </summary>
  1421. Public Sub RefreshStat()
  1422. '计算进度
  1423. Dim NewProgress As Double = 0
  1424. Dim TotalProgress As Double = 0
  1425. For Each File In Files
  1426. If File.IsCopy Then
  1427. NewProgress += File.Progress * 0.2
  1428. TotalProgress += 0.2
  1429. Else
  1430. NewProgress += File.Progress
  1431. TotalProgress += 1
  1432. End If
  1433. Next
  1434. If TotalProgress > 0 AndAlso Not Double.IsNaN(TotalProgress) Then NewProgress /= TotalProgress
  1435. '刷新进度
  1436. _Progress = NewProgress
  1437. End Sub
  1438. Public Sub New(Name As String, FileTasks As List(Of NetFile))
  1439. Me.Name = Name
  1440. Files = New ConcurrentList(Of NetFile)(FileTasks)
  1441. End Sub
  1442. Public Overrides Sub Start(Optional Input As Object = Nothing, Optional IsForceRestart As Boolean = False)
  1443. If Input IsNot Nothing Then Files = New ConcurrentList(Of NetFile)(Input)
  1444. '去重
  1445. Files = New ConcurrentList(Of NetFile)(Files.DistinctBy(Function(a) a.LocalPath))
  1446. '设置剩余文件数
  1447. SyncLock FileRemainLock
  1448. FileRemain += Files.Where(Function(f) f.State <> NetState.Finished).Count
  1449. End SyncLock
  1450. State = LoadState.Loading
  1451. '开始执行
  1452. RunInNewThread(
  1453. Sub()
  1454. Try
  1455. '输入检测
  1456. If Not Files.Any() Then
  1457. OnFinish()
  1458. Return
  1459. End If
  1460. For Each File As NetFile In Files
  1461. If File Is Nothing Then Throw New ArgumentException("存在空文件请求!")
  1462. For Each Source As NetSource In File.Sources
  1463. If Not (Source.Url.StartsWithF("https://", True) OrElse Source.Url.StartsWithF("http://", True)) Then
  1464. Source.Ex = New ArgumentException("输入的下载链接不正确:" & Source.Url)
  1465. Source.IsFailed = True
  1466. End If
  1467. Next
  1468. If Not File.HasAvailableSource() Then Throw New ArgumentException("输入的下载链接不正确!")
  1469. File.LocalPath = File.LocalPath.Replace("/", "\")
  1470. If Not File.LocalPath.Lower.Contains(":\") Then Throw New ArgumentException("输入的本地文件地址不正确:" & File.LocalPath)
  1471. If File.LocalPath.EndsWithF("\") Then Throw New ArgumentException("请输入含文件名的完整文件路径:" & File.LocalPath)
  1472. DirectoryUtils.Create(File.LocalPath, isFilePath:=True) '创建目标文件夹
  1473. Next
  1474. '接入下载管理器,获取新开始下载的文件列表
  1475. Dim NewFiles = NetManager.Start(Me)
  1476. '====================================
  1477. ' 已存在文件查找
  1478. '====================================
  1479. '整理允许进行查找的文件
  1480. Dim FilesToCheck As New List(Of NetFile)
  1481. For Each File In NewFiles
  1482. If File.Check?.CanUseExistsFile Then
  1483. FilesToCheck.Add(File)
  1484. Else '不允许,直接开始下载
  1485. SyncLock LockState
  1486. File.State = NetState.WaitingToDownload
  1487. File.IsCopy = False
  1488. End SyncLock
  1489. End If
  1490. Next
  1491. If Not FilesToCheck.Any Then Return
  1492. '获取 MC 文件夹列表
  1493. Dim Folders As New List(Of String)
  1494. Folders.Add(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\.minecraft\") '总是添加官启文件夹,因为 HMCL 会把所有文件存在这里
  1495. Folders.AddRange(McFolderList.Select(Function(f) f.Location))
  1496. Folders = Folders.Distinct.Where(Function(f) Directory.Exists(f)).ToList
  1497. '平均分配到多个检查线程
  1498. Dim ThreadCount As Integer = (FilesToCheck.Count \ 40).Clamp(1, 8) '每个线程至少 40 个文件,最多 8 线程
  1499. If ThreadCount = 1 Then '只有一个线程,直接执行
  1500. CheckExistingFiles(FilesToCheck, Folders)
  1501. Else
  1502. Dim BaseSize = FilesToCheck.Count \ ThreadCount
  1503. Dim Remainder = FilesToCheck.Count Mod ThreadCount
  1504. Dim Index = 0
  1505. For i = 0 To ThreadCount - 1
  1506. Dim Size = BaseSize + If(i < Remainder, 1, 0)
  1507. Dim ThreadFiles = FilesToCheck.GetRange(Index, Size)
  1508. Index += Size
  1509. RunInNewThread(Sub() CheckExistingFiles(ThreadFiles, Folders), $"下载 文件复制 {Uuid}/{GetUuid()}")
  1510. Next
  1511. End If
  1512. Catch ex As Exception
  1513. OnFail(New List(Of Exception) From {New Exception("下载初始化失败", ex)})
  1514. End Try
  1515. End Sub, "L/下载 " & Uuid)
  1516. End Sub
  1517. Private Sub CheckExistingFiles(Files As List(Of NetFile), FolderList As List(Of String))
  1518. Try
  1519. If ModeDebug Then Log($"[Download] 文件检查开始,本线程负责的文件数:{Files.Count}")
  1520. '列出 MC 文件夹中的各个版本文件夹
  1521. Dim VersionFolders As New List(Of String)
  1522. For Each McFolder In FolderList
  1523. Dim VersionsFolder As New DirectoryInfo(McFolder & "versions\")
  1524. If VersionsFolder.Exists() Then
  1525. For Each VersionFolder In VersionsFolder.GetDirectories
  1526. VersionFolders.Add(VersionFolder.FullName & "\")
  1527. Next
  1528. End If
  1529. Next
  1530. '处理每个文件
  1531. For Each File As NetFile In Files
  1532. Dim Target As String = CheckExistingFile(FolderList, VersionFolders, File)
  1533. If ModeDebug Then Log($"[Download] 文件检查结果:{File.LocalName} → {Target},当前状态 {File.State}")
  1534. If File.State >= NetState.WaitingToDownload Then Continue For '中断
  1535. '已找到相同文件
  1536. If Target IsNot Nothing Then
  1537. File.IsCopy = True
  1538. Dim RetryCount As Integer = 0
  1539. Retry:
  1540. Try
  1541. If Target <> File.LocalPath Then
  1542. Log($"[Download] 复制已存在的文件:{Target} → {File.LocalPath}")
  1543. CopyFile(Target, File.LocalPath)
  1544. Else
  1545. If ModeDebug Then Log($"[Download] 需要下载的文件已存在,并通过校验:{Target}")
  1546. End If
  1547. File.Finish(False)
  1548. Continue For
  1549. Catch ex As Exception
  1550. RetryCount += 1
  1551. Log(ex, $"复制已存在的文件失败,第 {RetryCount} 次重试({Target} → {File.LocalPath})")
  1552. If RetryCount < 3 Then
  1553. Thread.Sleep(2000)
  1554. GoTo Retry
  1555. End If
  1556. End Try
  1557. End If
  1558. '回退到下载
  1559. SyncLock LockState
  1560. File.State = NetState.WaitingToDownload
  1561. File.IsCopy = False
  1562. End SyncLock
  1563. Next
  1564. Catch ex As Exception
  1565. OnFail(New List(Of Exception) From {New Exception("下载已存在文件查找失败", ex)})
  1566. End Try
  1567. End Sub
  1568. Private Function CheckExistingFile(FolderList As List(Of String), VersionFolders As List(Of String), File As NetFile) As String
  1569. '目标文件已存在
  1570. If File.Check.Check(File.LocalPath) Is Nothing Then Return File.LocalPath
  1571. '在设置中禁用了复制
  1572. If Settings.Get("SystemDebugSkipCopy") Then Return Nothing
  1573. '没有可用的检查规则,只能开始下载
  1574. If File.Check.Hash Is Nothing AndAlso File.Check.ActualSize < 0 Then Return Nothing
  1575. '大致判断文件类别
  1576. Dim TypeIndexes =
  1577. {"\assets\", "\libraries\", "\versions\", "\mods\", "\coremods\", "\lib\", "\resourcepacks\", "\texturepacks\", "\shaderpacks\"}.
  1578. Select(Function(FolderName) (FolderName, File.LocalPath.IndexOfF(FolderName, True))).
  1579. Where(Function(kv) kv.Item2 >= 0).ToList
  1580. If Not TypeIndexes.Any Then
  1581. If File.LocalName.EndsWithF(".jar") Then
  1582. TypeIndexes.Add(("\versions\", 1)) '总是对 jar 进行版本文件检查,以包括另存为 jar 的情况
  1583. Else
  1584. Return Nothing
  1585. End If
  1586. End If
  1587. Dim Type = TypeIndexes.MaxBy(Function(kv) kv.Item2).FolderName.TrimStart("\"c)
  1588. '根据类别进行查找
  1589. Static Sizes As New ConcurrentDictionary(Of String, Long)
  1590. Select Case Type
  1591. Case "assets\", "libraries\"
  1592. 'assets/libraries:查找 MC 文件夹下的相同路径
  1593. For Each Folder In FolderList
  1594. Dim Candidate = Folder & Type & File.LocalPath.AfterFirst(Type)
  1595. If File.Check.Check(Candidate) Is Nothing Then Return Candidate
  1596. Next
  1597. Case "versions\"
  1598. '版本 jar 或 json:查找 MC 文件夹下的各个版本文件夹
  1599. For Each VersionFolder In VersionFolders
  1600. For Each Candidate In Directory.GetFiles(VersionFolder,
  1601. "*." & GetFileNameFromPath(File.LocalPath).AfterLast(".").Lower, SearchOption.TopDirectoryOnly)
  1602. '快速进行大小校验
  1603. Dim Length = Sizes.GetOrAdd(Candidate, Function(c) New FileInfo(c).Length)
  1604. If File.Check.ActualSize <> Length Then Continue For
  1605. 'Hash 校验
  1606. If File.Check.Check(Candidate) Is Nothing Then Return Candidate
  1607. Next
  1608. Next
  1609. Case Else
  1610. '社区资源
  1611. If File.Check.ActualSize < 0 OrElse File.Check.Hash Is Nothing Then Return Nothing '必须要求指定了文件大小和 Hash
  1612. For Each Folder In FolderList.Concat(VersionFolders)
  1613. Dim TargetFolder = Folder & Type
  1614. If Not Directory.Exists(TargetFolder) Then Continue For
  1615. For Each Candidate In Directory.GetFiles(TargetFolder)
  1616. '快速进行大小校验
  1617. Dim Length = Sizes.GetOrAdd(Candidate, Function(c) New FileInfo(c).Length)
  1618. If File.Check.ActualSize <> Length Then Continue For
  1619. 'Hash 校验
  1620. If File.Check.Check(Candidate) Is Nothing Then Return Candidate
  1621. Next
  1622. Next
  1623. End Select
  1624. Return Nothing
  1625. End Function
  1626. Public Sub OnFileFinish(File As NetFile)
  1627. '要求全部文件完成
  1628. SyncLock FileRemainLock
  1629. FileRemain -= 1
  1630. If FileRemain > 0 Then Return
  1631. End SyncLock
  1632. OnFinish()
  1633. End Sub
  1634. Public Sub OnFinish()
  1635. RaisePreviewFinish()
  1636. SyncLock LockState
  1637. If State > LoadState.Loading Then Return
  1638. State = LoadState.Finished
  1639. End SyncLock
  1640. End Sub
  1641. Public Sub OnFileFail(File As NetFile)
  1642. '将下载源的错误加入主错误列表
  1643. For Each Source In File.Sources
  1644. If Not IsNothing(Source.Ex) Then File.Ex.Add(Source.Ex)
  1645. Next
  1646. OnFail(File.Ex)
  1647. End Sub
  1648. Public Overrides Sub Failed(Ex As Exception)
  1649. OnFail(New List(Of Exception) From {Ex})
  1650. End Sub
  1651. Public Sub OnFail(ExList As List(Of Exception))
  1652. SyncLock LockState
  1653. If State >= LoadState.Finished Then Return
  1654. If ExList Is Nothing OrElse Not ExList.Any() Then ExList = New List(Of Exception) From {New Exception("未知错误!")}
  1655. '寻找有效的错误信息
  1656. Dim UsefulExs = ExList.Where(Function(e) TypeOf e IsNot OperationCanceledException AndAlso TypeOf e IsNot TimeoutException AndAlso TypeOf e IsNot ThreadInterruptedException).ToList
  1657. [Error] = If(UsefulExs.FirstOrDefault, ExList.FirstOrDefault)
  1658. '获取实际失败的文件
  1659. For Each File In Files
  1660. If File.State <> NetState.Interrupted Then Continue For
  1661. If File.Sources.All(Function(s) TypeOf s.Ex Is OperationCanceledException OrElse TypeOf s.Ex Is TimeoutException OrElse TypeOf s.Ex Is ThreadInterruptedException) Then Continue For
  1662. Dim Detail As String = File.Sources.Select(Function(s) $"{If(s.Ex Is Nothing, "无错误信息。", s.Ex.GetBrief())}({s.Url})").Join(vbCrLf)
  1663. [Error] = New Exception("文件下载失败:" & File.LocalPath & vbCrLf &
  1664. "各下载源的错误如下:" & vbCrLf & Detail, [Error])
  1665. '上报
  1666. Telemetry("文件下载失败",
  1667. "FileName", File.LocalName,
  1668. "Exception", Detail)
  1669. Exit For
  1670. Next
  1671. '在设置 Error 对象后再更改为失败,避免 WaitForExit 无法捕获错误
  1672. State = LoadState.Failed
  1673. End SyncLock
  1674. '中断所有文件
  1675. For Each TaskFile In Files
  1676. TaskFile.Interrupt(Me)
  1677. Next
  1678. '在退出同步锁后再进行日志输出
  1679. Dim ErrOutput As New List(Of String)
  1680. For Each Ex As Exception In ExList
  1681. ErrOutput.Add(Ex.GetDetail())
  1682. Next
  1683. Log("[Download] " & ErrOutput.Distinct.Join(vbCrLf))
  1684. End Sub
  1685. Public Overrides Sub Interrupt()
  1686. SyncLock LockState
  1687. If State >= LoadState.Finished Then Return
  1688. State = LoadState.Interrupted
  1689. End SyncLock
  1690. Log("[Download] " & Name & " 已取消!")
  1691. '中断所有文件
  1692. For Each TaskFile In Files
  1693. TaskFile.Interrupt(Me)
  1694. Next
  1695. End Sub
  1696. End Class
  1697. Public NetManager As New NetManagerClass
  1698. ''' <summary>
  1699. ''' 下载文件管理。
  1700. ''' </summary>
  1701. Public Class NetManagerClass
  1702. #Region "属性"
  1703. ''' <summary>
  1704. ''' 需要下载的文件。为“本地地址 - 文件对象”键值对。
  1705. ''' </summary>
  1706. Public AllFiles As New ConcurrentDictionary(Of String, NetFile)
  1707. ''' <summary>
  1708. ''' 当前的所有下载任务。
  1709. ''' </summary>
  1710. Public Tasks As New ConcurrentList(Of LoaderDownload)
  1711. ''' <summary>
  1712. ''' 已下载完成的大小。
  1713. ''' </summary>
  1714. Public DownloadDone As Long = 0
  1715. ''' <summary>
  1716. ''' 尚未完成下载的文件数。
  1717. ''' </summary>
  1718. Public FileRemain As Integer = 0
  1719. '这些属性由 RefreshStat 刷新
  1720. ''' <summary>
  1721. ''' 当前的全局下载速度,单位为 Byte / 秒。
  1722. ''' </summary>
  1723. Public Speed As Long = 0
  1724. Public ReadOnly Uuid As Integer = GetUuid()
  1725. #End Region
  1726. ''' <summary>
  1727. ''' 进度与下载速度由下载管理线程每隔约 0.1 秒刷新一次。
  1728. ''' </summary>
  1729. Private Sub RefreshStat()
  1730. Try
  1731. Dim DeltaTime As Long = GetTimeMs() - RefreshStatLast
  1732. If DeltaTime = 0 Then Return
  1733. RefreshStatLast += DeltaTime
  1734. #Region "刷新整体速度"
  1735. '计算瞬时速度
  1736. Static SpeedLast As New List(Of Long) '记录至多最近 30 次下载速度的记录,较新的在前面
  1737. Static SpeedLastDone As Long = 0 '上次记速时的已下载大小
  1738. Dim ActualSpeed As Double = Math.Max(0, (DownloadDone - SpeedLastDone) / (DeltaTime / 1000))
  1739. SpeedLast.Insert(0, ActualSpeed)
  1740. If SpeedLast.Count >= 31 Then SpeedLast.RemoveAt(30)
  1741. SpeedLastDone = DownloadDone
  1742. '计算用于显示的速度
  1743. Dim SpeedSum As Long = 0, SpeedDiv As Long = 0, Weight = SpeedLast.Count
  1744. For Each SpeedRecord In SpeedLast
  1745. SpeedSum += SpeedRecord * Weight
  1746. SpeedDiv += Weight
  1747. Weight -= 1
  1748. Next
  1749. Speed = If(SpeedDiv > 0, SpeedSum / SpeedDiv, 0)
  1750. '计算新的速度下限
  1751. Dim Limit As Long = 0
  1752. If SpeedLast.Count >= 10 Then Limit = SpeedLast.Take(10).Average * 0.85 '取近 1 秒的平均速度的 85%
  1753. If Limit > NetTaskSpeedLimitLow Then
  1754. NetTaskSpeedLimitLow = Limit
  1755. Log("[Download] " & "速度下限已提升到 " & FormatFileSize(Limit))
  1756. End If
  1757. #End Region
  1758. #Region "刷新下载任务属性"
  1759. For Each Task In Tasks
  1760. Task.RefreshStat()
  1761. Next
  1762. #End Region
  1763. Catch ex As Exception
  1764. Log(ex, "刷新下载公开属性失败")
  1765. End Try
  1766. End Sub
  1767. Private RefreshStatLast As Long
  1768. ''' <summary>
  1769. ''' 启动监控线程,用于新增下载线程。
  1770. ''' </summary>
  1771. Private Sub StartManager()
  1772. Static IsStarted As Boolean = False
  1773. If IsStarted Then Return
  1774. IsStarted = True
  1775. Dim ThreadStarter =
  1776. Sub(Id As Integer) '0 或 1
  1777. Try
  1778. While True
  1779. Thread.Sleep(20)
  1780. '获取文件列表
  1781. Dim WaitingFiles As New List(Of NetFile)
  1782. Dim OngoingFiles As New List(Of NetFile)
  1783. If Id = 0 AndAlso FileRemain = 0 Then AllFiles.Clear() '若已完成,则清空
  1784. For Each File As NetFile In AllFiles.Values
  1785. If File.Uuid Mod 2 = Id Then Continue For
  1786. If File.State = NetState.WaitingToDownload Then
  1787. WaitingFiles.Add(File)
  1788. ElseIf File.State < NetState.Merging AndAlso File.State >= NetState.WaitingToDownload Then
  1789. OngoingFiles.Add(File)
  1790. End If
  1791. Next
  1792. '为等待中的文件开始线程
  1793. For Each File As NetFile In WaitingFiles
  1794. If NetTaskThreadCount >= NetTaskThreadLimit Then Continue While '最大线程数检查
  1795. Dim NewThread = File.TryBeginThread()
  1796. If NewThread IsNot Nothing AndAlso NewThread.Source.Url.Contains("bmclapi") Then Thread.Sleep(100) '减少 BMCLAPI 请求频率
  1797. Next
  1798. '为进行中的文件追加线程
  1799. If Speed >= NetTaskSpeedLimitLow Then Continue While '下载速度足够,无需新增
  1800. For Each File As NetFile In OngoingFiles
  1801. If NetTaskThreadCount >= NetTaskThreadLimit Then Continue While '最大线程数检查
  1802. '线程种类计数
  1803. Dim PreparingCount = 0, DownloadingCount = 0
  1804. If File.Threads IsNot Nothing Then
  1805. For Each Thread As NetThread In File.Threads.ToList
  1806. If Thread.State < NetState.Downloading Then
  1807. PreparingCount += 1
  1808. ElseIf Thread.State = NetState.Downloading Then
  1809. DownloadingCount += 1
  1810. End If
  1811. Next
  1812. End If
  1813. '新增线程
  1814. If PreparingCount > DownloadingCount Then Continue For '准备中的线程已多于下载中的线程,不再新增
  1815. Dim NewThread = File.TryBeginThread()
  1816. If NewThread IsNot Nothing AndAlso NewThread.Source.Url.Contains("bmclapi") Then Thread.Sleep(100) '减少 BMCLAPI 请求频率
  1817. Next
  1818. End While
  1819. Catch ex As Exception
  1820. Log(ex, $"下载管理启动线程 {Id} 出错", NotifyLevel.Critical)
  1821. End Try
  1822. End Sub
  1823. RunInNewThread(Sub() ThreadStarter(0), "NetManager ThreadStarter 0")
  1824. RunInNewThread(Sub() ThreadStarter(1), "NetManager ThreadStarter 1")
  1825. RunInNewThread(
  1826. Sub()
  1827. Try
  1828. Dim NextTick As Long = GetTimeMs()
  1829. While True
  1830. '增加限速余量
  1831. If NetTaskSpeedLimitHigh > 0 Then Interlocked.Add(NetTaskSpeedLimitLeft, CLng(NetTaskSpeedLimitHigh / 10))
  1832. '刷新公开属性
  1833. RefreshStat()
  1834. '等待 100 ms
  1835. NextTick += 100
  1836. Dim SleepTime = NextTick - GetTimeMs()
  1837. If SleepTime > 0 Then
  1838. Thread.Sleep(SleepTime)
  1839. Else
  1840. NextTick = GetTimeMs() '超时,直接追帧,不等待
  1841. End If
  1842. End While
  1843. Catch ex As Exception
  1844. Log(ex, "下载管理刷新线程出错", NotifyLevel.Critical)
  1845. End Try
  1846. End Sub, "NetManager StatRefresher")
  1847. End Sub
  1848. Private DownloadCacheLock As New Object
  1849. Private IsDownloadCacheCleared As Boolean = False
  1850. ''' <summary>
  1851. ''' 开始一个下载任务。
  1852. ''' </summary>
  1853. Public Function Start(Task As LoaderDownload) As List(Of NetFile)
  1854. StartManager()
  1855. '清理缓存
  1856. SyncLock DownloadCacheLock '防止同时开启多个下载任务时重复清理
  1857. If Not IsDownloadCacheCleared Then
  1858. Try
  1859. Log("[Net] 开始清理下载缓存")
  1860. DeleteDirectory(PathTemp & "Download")
  1861. Log("[Net] 下载缓存已清理")
  1862. Catch ex As Exception
  1863. Log(ex, "清理下载缓存失败")
  1864. End Try
  1865. IsDownloadCacheCleared = True
  1866. End If
  1867. End SyncLock
  1868. '添加每个文件
  1869. Dim NewFiles As New List(Of NetFile)
  1870. For i = 0 To Task.Files.Count - 1
  1871. Dim File As NetFile = Task.Files(i)
  1872. Dim OngoingFile As NetFile = Nothing
  1873. If AllFiles.TryGetValue(File.LocalPath, OngoingFile) AndAlso OngoingFile.State < NetState.Finished Then
  1874. '该文件正在被另一个任务下载
  1875. If ModeDebug Then Log($"[Download] {File.LocalName}:无需开始,该文件已在下载中,目标 {File.LocalPath}")
  1876. File = OngoingFile '将列表中的文件替换成下载中的文件,即两个任务指向同一个文件;抛弃现在的 File 对象
  1877. Task.Files(i) = File
  1878. Else
  1879. '常规情况(该文件可能已在其他任务中下载完成,但这并不影响)
  1880. If ModeDebug Then Log($"[Download] {File.LocalName}:开始,目标 {File.LocalPath}")
  1881. AllFiles(File.LocalPath) = File
  1882. NewFiles.Add(File)
  1883. Interlocked.Increment(FileRemain)
  1884. End If
  1885. File.Tasks.Add(Task)
  1886. Next
  1887. Tasks.Add(Task)
  1888. Return NewFiles
  1889. End Function
  1890. End Class
  1891. ''' <summary>
  1892. ''' 是否有正在进行中、需要在下载管理页面显示的下载任务?
  1893. ''' </summary>
  1894. Public Function HasDownloadingTask(Optional IgnoreCustomDownload As Boolean = False) As Boolean
  1895. Return LoaderTaskbar.Any(
  1896. Function(Task) Task.Show AndAlso Task.State = LoadState.Loading AndAlso
  1897. (Not IgnoreCustomDownload OrElse Not Task.Name.ToString.Contains("自定义下载")))
  1898. End Function
  1899. #End Region
  1900. #Region "端口"
  1901. ''' <summary>
  1902. ''' 随机获取单个可用的端口。
  1903. ''' </summary>
  1904. Public Function FindFreePort() As Integer
  1905. Dim Listener As New TcpListener(IPAddress.Loopback, 0)
  1906. Listener.Start()
  1907. Dim port As Integer = CType(Listener.LocalEndpoint, IPEndPoint).Port
  1908. Listener.Stop()
  1909. Return port
  1910. End Function
  1911. ''' <summary>
  1912. ''' 获取当前已被占用的端口列表。
  1913. ''' </summary>
  1914. Public Function GetUsedPorts() As List(Of Integer)
  1915. Dim IPProperties = NetworkInformation.IPGlobalProperties.GetIPGlobalProperties()
  1916. Dim UsedPorts As New List(Of Integer)
  1917. UsedPorts.AddRange(IPProperties.GetActiveTcpListeners().Select(Function(ep) ep.Port))
  1918. UsedPorts.AddRange(IPProperties.GetActiveUdpListeners().Select(Function(ep) ep.Port))
  1919. UsedPorts.AddRange(IPProperties.GetActiveTcpConnections().Select(Function(conn) conn.LocalEndPoint.Port))
  1920. Return UsedPorts.Distinct().ToList()
  1921. End Function
  1922. ''' <summary>
  1923. ''' 寻找数个连续编号的可用端口。
  1924. ''' </summary>
  1925. Public Function FindFreePorts(ConsecutiveCount As Integer, ParamArray ExtraBlackLists As Integer()) As List(Of Integer)
  1926. Dim UsedPorts = GetUsedPorts().Concat(ExtraBlackLists)
  1927. For port = 12000 + RandomInteger(0, 1000) To 65000 - ConsecutiveCount
  1928. Dim Range = Enumerable.Range(port, ConsecutiveCount)
  1929. If Not Range.Any(Function(p) UsedPorts.Contains(p)) Then Return Range.ToList
  1930. Next
  1931. Throw New Exception("未能找到可用的端口!")
  1932. End Function
  1933. #End Region
  1934. ''' <summary>
  1935. ''' 测试 Ping。失败则返回 -1。
  1936. ''' </summary>
  1937. Public Function Ping(Ip As String, Optional Timeout As Integer = 10000, Optional MakeLog As Boolean = True) As Integer
  1938. Dim PingResult As NetworkInformation.PingReply
  1939. Try
  1940. PingResult = (New NetworkInformation.Ping).Send(Ip)
  1941. Catch ex As Exception
  1942. If MakeLog Then Log("[Net] Ping " & Ip & " 失败:" & ex.Message)
  1943. Return -1
  1944. End Try
  1945. If PingResult.Status = NetworkInformation.IPStatus.Success Then
  1946. If MakeLog Then Log("[Net] Ping " & Ip & " 结束:" & PingResult.RoundtripTime & "ms")
  1947. Return PingResult.RoundtripTime
  1948. Else
  1949. If MakeLog Then Log("[Net] Ping " & Ip & " 失败")
  1950. Return -1
  1951. End If
  1952. End Function
  1953. ''' <summary>
  1954. ''' 判断某个 Exception 是否为网络问题所导致。
  1955. ''' </summary>
  1956. <Extension> Public Function IsNetworkRelated(Ex As Exception) As Boolean
  1957. '提取 Message(不能用 GetDetail,因为堆栈的方法参数中就有 timeout 字样)
  1958. Dim Detail As String = ""
  1959. Dim InnerEx As Exception = Ex
  1960. Detail += InnerEx.Message
  1961. Do Until InnerEx.InnerException Is Nothing
  1962. InnerEx = InnerEx.InnerException
  1963. Detail += InnerEx.Message
  1964. Loop
  1965. '判断
  1966. If Detail.Contains("(403)") Then Return False
  1967. Return {
  1968. "(408)", "超时", "timeout", "网络请求失败", "连接尝试失败", "远程主机强迫关闭了", "远程方已关闭传输流", "未能解析此远程名称",
  1969. "由于目标计算机积极拒绝", "基础连接已经关闭"
  1970. }.Any(Function(k) Detail.ContainsIgnoreCase(k))
  1971. End Function
  1972. ''' <summary>
  1973. ''' 设置是否应当在正版登录时校验 SSL 证书。
  1974. ''' </summary>
  1975. Public Sub ShouldValidateSslCertificateOnLogin(Enabled As Boolean)
  1976. ServicePointManager.ServerCertificateValidationCallback =
  1977. Function(Sender, Certificate, Chain, Failure)
  1978. Dim Request As HttpWebRequest = TryCast(Sender, HttpWebRequest)
  1979. If Failure = Net.Security.SslPolicyErrors.None Then Return True '已通过验证
  1980. '基于 #3018 和 #5879,只在访问正版登录 API 时跳过证书验证
  1981. Log($"[System] 未通过 SSL 证书验证({Failure}),提供的证书为 {Certificate?.Subject},URL:{Request?.Address}", NotifyLevel.DebugModeOnly)
  1982. If Request Is Nothing Then
  1983. Return Not Enabled
  1984. ElseIf Request.Address.Host.Contains("xboxlive") OrElse Request.Address.Host.Contains("minecraftservices") Then
  1985. Return Not Enabled '根据设置决定是否忽略错误
  1986. Else
  1987. Return False
  1988. End If
  1989. End Function
  1990. End Sub
  1991. End Module