corrade-vassal – Blame information for rev 1
?pathlinks?
Rev | Author | Line No. | Line |
---|---|---|---|
1 | vero | 1 | /* |
2 | * Copyright (c) 2006-2014, openmetaverse.org |
||
3 | * All rights reserved. |
||
4 | * |
||
5 | * - Redistribution and use in source and binary forms, with or without |
||
6 | * modification, are permitted provided that the following conditions are met: |
||
7 | * |
||
8 | * - Redistributions of source code must retain the above copyright notice, this |
||
9 | * list of conditions and the following disclaimer. |
||
10 | * - Neither the name of the openmetaverse.org nor the names |
||
11 | * of its contributors may be used to endorse or promote products derived from |
||
12 | * this software without specific prior written permission. |
||
13 | * |
||
14 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
||
15 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
||
16 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
||
17 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE |
||
18 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
||
19 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
||
20 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
||
21 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
||
22 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
||
23 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
||
24 | * POSSIBILITY OF SUCH DAMAGE. |
||
25 | */ |
||
26 | |||
27 | using System; |
||
28 | using System.Net; |
||
29 | using System.Net.Security; |
||
30 | using System.IO; |
||
31 | using System.Text; |
||
32 | using System.Threading; |
||
33 | using System.Security.Cryptography.X509Certificates; |
||
34 | |||
35 | namespace OpenMetaverse.Http |
||
36 | { |
||
37 | public class TrustAllCertificatePolicy : ICertificatePolicy |
||
38 | { |
||
39 | public bool CheckValidationResult(ServicePoint sp, X509Certificate cert, WebRequest req, int problem) |
||
40 | { |
||
41 | return true; |
||
42 | } |
||
43 | |||
44 | public static bool TrustAllCertificateHandler(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) |
||
45 | { |
||
46 | return true; |
||
47 | } |
||
48 | } |
||
49 | |||
50 | public static class CapsBase |
||
51 | { |
||
52 | public delegate void OpenWriteEventHandler(HttpWebRequest request); |
||
53 | public delegate void DownloadProgressEventHandler(HttpWebRequest request, HttpWebResponse response, int bytesReceived, int totalBytesToReceive); |
||
54 | public delegate void RequestCompletedEventHandler(HttpWebRequest request, HttpWebResponse response, byte[] responseData, Exception error); |
||
55 | |||
56 | static CapsBase() |
||
57 | { |
||
58 | ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy(); |
||
59 | // Even though this will compile on Mono 2.4, it throws a runtime exception |
||
60 | //ServicePointManager.ServerCertificateValidationCallback = TrustAllCertificatePolicy.TrustAllCertificateHandler; |
||
61 | } |
||
62 | |||
63 | private class RequestState |
||
64 | { |
||
65 | public HttpWebRequest Request; |
||
66 | public byte[] UploadData; |
||
67 | public int MillisecondsTimeout; |
||
68 | public OpenWriteEventHandler OpenWriteCallback; |
||
69 | public DownloadProgressEventHandler DownloadProgressCallback; |
||
70 | public RequestCompletedEventHandler CompletedCallback; |
||
71 | |||
72 | public RequestState(HttpWebRequest request, byte[] uploadData, int millisecondsTimeout, OpenWriteEventHandler openWriteCallback, |
||
73 | DownloadProgressEventHandler downloadProgressCallback, RequestCompletedEventHandler completedCallback) |
||
74 | { |
||
75 | Request = request; |
||
76 | UploadData = uploadData; |
||
77 | MillisecondsTimeout = millisecondsTimeout; |
||
78 | OpenWriteCallback = openWriteCallback; |
||
79 | DownloadProgressCallback = downloadProgressCallback; |
||
80 | CompletedCallback = completedCallback; |
||
81 | } |
||
82 | } |
||
83 | |||
84 | public static HttpWebRequest UploadDataAsync(Uri address, X509Certificate2 clientCert, string contentType, byte[] data, |
||
85 | int millisecondsTimeout, OpenWriteEventHandler openWriteCallback, DownloadProgressEventHandler downloadProgressCallback, |
||
86 | RequestCompletedEventHandler completedCallback) |
||
87 | { |
||
88 | // Create the request |
||
89 | HttpWebRequest request = SetupRequest(address, clientCert); |
||
90 | request.ContentLength = data.Length; |
||
91 | if (!String.IsNullOrEmpty(contentType)) |
||
92 | request.ContentType = contentType; |
||
93 | request.Method = "POST"; |
||
94 | |||
95 | // Create an object to hold all of the state for this request |
||
96 | RequestState state = new RequestState(request, data, millisecondsTimeout, openWriteCallback, |
||
97 | downloadProgressCallback, completedCallback); |
||
98 | |||
99 | // Start the request for a stream to upload to |
||
100 | IAsyncResult result = request.BeginGetRequestStream(OpenWrite, state); |
||
101 | // Register a timeout for the request |
||
102 | ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, state, millisecondsTimeout, true); |
||
103 | |||
104 | return request; |
||
105 | } |
||
106 | |||
107 | public static HttpWebRequest DownloadStringAsync(Uri address, X509Certificate2 clientCert, int millisecondsTimeout, |
||
108 | DownloadProgressEventHandler downloadProgressCallback, RequestCompletedEventHandler completedCallback) |
||
109 | { |
||
110 | // Create the request |
||
111 | HttpWebRequest request = SetupRequest(address, clientCert); |
||
112 | request.Method = "GET"; |
||
113 | DownloadDataAsync(request, millisecondsTimeout, downloadProgressCallback, completedCallback); |
||
114 | return request; |
||
115 | } |
||
116 | |||
117 | public static void DownloadDataAsync(HttpWebRequest request, int millisecondsTimeout, |
||
118 | DownloadProgressEventHandler downloadProgressCallback, RequestCompletedEventHandler completedCallback) |
||
119 | { |
||
120 | // Create an object to hold all of the state for this request |
||
121 | RequestState state = new RequestState(request, null, millisecondsTimeout, null, downloadProgressCallback, |
||
122 | completedCallback); |
||
123 | |||
124 | // Start the request for the remote server response |
||
125 | IAsyncResult result = request.BeginGetResponse(GetResponse, state); |
||
126 | // Register a timeout for the request |
||
127 | ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, state, millisecondsTimeout, true); |
||
128 | } |
||
129 | |||
130 | static HttpWebRequest SetupRequest(Uri address, X509Certificate2 clientCert) |
||
131 | { |
||
132 | if (address == null) |
||
133 | throw new ArgumentNullException("address"); |
||
134 | |||
135 | // Create the request |
||
136 | HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(address); |
||
137 | |||
138 | // Add the client certificate to the request if one was given |
||
139 | if (clientCert != null) |
||
140 | request.ClientCertificates.Add(clientCert); |
||
141 | |||
142 | // Leave idle connections to this endpoint open for up to 60 seconds |
||
143 | request.ServicePoint.MaxIdleTime = 1000 * 60; |
||
144 | // Disable stupid Expect-100: Continue header |
||
145 | request.ServicePoint.Expect100Continue = false; |
||
146 | // Crank up the max number of connections per endpoint |
||
147 | // We set this manually here instead of in ServicePointManager to avoid intereference with callers. |
||
148 | if (request.ServicePoint.ConnectionLimit < Settings.MAX_HTTP_CONNECTIONS) |
||
149 | { |
||
150 | Logger.Log( |
||
151 | string.Format( |
||
152 | "In CapsBase.SetupRequest() setting conn limit for {0}:{1} to {2}", |
||
153 | address.Host, address.Port, Settings.MAX_HTTP_CONNECTIONS), Helpers.LogLevel.Debug); |
||
154 | request.ServicePoint.ConnectionLimit = Settings.MAX_HTTP_CONNECTIONS; |
||
155 | } |
||
156 | // Caps requests are never sent as trickles of data, so Nagle's |
||
157 | // coalescing algorithm won't help us |
||
158 | request.ServicePoint.UseNagleAlgorithm = false; |
||
159 | // If not on mono, set accept-encoding header that allows response compression |
||
160 | request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; |
||
161 | return request; |
||
162 | } |
||
163 | |||
164 | static void OpenWrite(IAsyncResult ar) |
||
165 | { |
||
166 | RequestState state = (RequestState)ar.AsyncState; |
||
167 | |||
168 | try |
||
169 | { |
||
170 | // Get the stream to write our upload to |
||
171 | using (Stream uploadStream = state.Request.EndGetRequestStream(ar)) |
||
172 | { |
||
173 | // Fire the callback for successfully opening the stream |
||
174 | if (state.OpenWriteCallback != null) |
||
175 | state.OpenWriteCallback(state.Request); |
||
176 | |||
177 | // Write our data to the upload stream |
||
178 | uploadStream.Write(state.UploadData, 0, state.UploadData.Length); |
||
179 | } |
||
180 | |||
181 | // Start the request for the remote server response |
||
182 | IAsyncResult result = state.Request.BeginGetResponse(GetResponse, state); |
||
183 | // Register a timeout for the request |
||
184 | ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, state, |
||
185 | state.MillisecondsTimeout, true); |
||
186 | } |
||
187 | catch (Exception ex) |
||
188 | { |
||
189 | //Logger.Log.Debug("CapsBase.OpenWrite(): " + ex.Message); |
||
190 | if (state.CompletedCallback != null) |
||
191 | state.CompletedCallback(state.Request, null, null, ex); |
||
192 | } |
||
193 | } |
||
194 | |||
195 | static void GetResponse(IAsyncResult ar) |
||
196 | { |
||
197 | RequestState state = (RequestState)ar.AsyncState; |
||
198 | HttpWebResponse response = null; |
||
199 | byte[] responseData = null; |
||
200 | Exception error = null; |
||
201 | |||
202 | try |
||
203 | { |
||
204 | using (response = (HttpWebResponse)state.Request.EndGetResponse(ar)) |
||
205 | { |
||
206 | // Get the stream for downloading the response |
||
207 | using (Stream responseStream = response.GetResponseStream()) |
||
208 | { |
||
209 | #region Read the response |
||
210 | |||
211 | // If Content-Length is set we create a buffer of the exact size, otherwise |
||
212 | // a MemoryStream is used to receive the response |
||
213 | bool nolength = (response.ContentLength <= 0) || (Type.GetType("Mono.Runtime") != null); |
||
214 | int size = (nolength) ? 8192 : (int)response.ContentLength; |
||
215 | MemoryStream ms = (nolength) ? new MemoryStream() : null; |
||
216 | byte[] buffer = new byte[size]; |
||
217 | |||
218 | int bytesRead = 0; |
||
219 | int offset = 0; |
||
220 | int totalBytesRead = 0; |
||
221 | int totalSize = nolength ? 0 : size; |
||
222 | |||
223 | while ((bytesRead = responseStream.Read(buffer, offset, size)) != 0) |
||
224 | { |
||
225 | totalBytesRead += bytesRead; |
||
226 | |||
227 | if (nolength) |
||
228 | { |
||
229 | totalSize += (size - bytesRead); |
||
230 | ms.Write(buffer, 0, bytesRead); |
||
231 | } |
||
232 | else |
||
233 | { |
||
234 | offset += bytesRead; |
||
235 | size -= bytesRead; |
||
236 | } |
||
237 | |||
238 | // Fire the download progress callback for each chunk of received data |
||
239 | if (state.DownloadProgressCallback != null) |
||
240 | state.DownloadProgressCallback(state.Request, response, totalBytesRead, totalSize); |
||
241 | } |
||
242 | |||
243 | if (nolength) |
||
244 | { |
||
245 | responseData = ms.ToArray(); |
||
246 | ms.Close(); |
||
247 | ms.Dispose(); |
||
248 | } |
||
249 | else |
||
250 | { |
||
251 | responseData = buffer; |
||
252 | } |
||
253 | |||
254 | #endregion Read the response |
||
255 | } |
||
256 | } |
||
257 | } |
||
258 | catch (Exception ex) |
||
259 | { |
||
260 | // Logger.DebugLog("CapsBase.GetResponse(): " + ex.Message); |
||
261 | error = ex; |
||
262 | } |
||
263 | |||
264 | if (state.CompletedCallback != null) |
||
265 | state.CompletedCallback(state.Request, response, responseData, error); |
||
266 | } |
||
267 | |||
268 | static void TimeoutCallback(object state, bool timedOut) |
||
269 | { |
||
270 | if (timedOut) |
||
271 | { |
||
272 | RequestState requestState = state as RequestState; |
||
273 | //Logger.Log.Debug("CapsBase.TimeoutCallback(): Request to " + requestState.Request.RequestUri + |
||
274 | // " timed out after " + requestState.MillisecondsTimeout + " milliseconds"); |
||
275 | if (requestState != null && requestState.Request != null) |
||
276 | requestState.Request.Abort(); |
||
277 | } |
||
278 | } |
||
279 | } |
||
280 | } |