[System.Runtime.Serialization] Static writer fix.
[mono.git] / mcs / class / System / System.Net / ServicePoint.cs
1 //
2 // System.Net.ServicePoint
3 //
4 // Authors:
5 //      Lawrence Pit (loz@cable.a2000.nl)
6 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 //
8 // (c) 2002 Lawrence Pit
9 // (c) 2003 Ximian, Inc. (http://www.ximian.com)
10 //
11
12 //
13 // Permission is hereby granted, free of charge, to any person obtaining
14 // a copy of this software and associated documentation files (the
15 // "Software"), to deal in the Software without restriction, including
16 // without limitation the rights to use, copy, modify, merge, publish,
17 // distribute, sublicense, and/or sell copies of the Software, and to
18 // permit persons to whom the Software is furnished to do so, subject to
19 // the following conditions:
20 // 
21 // The above copyright notice and this permission notice shall be
22 // included in all copies or substantial portions of the Software.
23 // 
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
28 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
29 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 //
32
33 using System;
34 using System.Collections.Generic;
35 using System.Diagnostics;
36 using System.Collections;
37 using System.Net.Sockets;
38 using System.Security.Cryptography.X509Certificates;
39 using System.Threading;
40
41 namespace System.Net 
42 {
43         public class ServicePoint
44         {
45                 Uri uri;
46                 int connectionLimit;
47                 int maxIdleTime;
48                 int currentConnections;
49                 DateTime idleSince;
50                 DateTime lastDnsResolve;
51                 Version protocolVersion;
52                 X509Certificate certificate;
53                 X509Certificate clientCertificate;
54                 IPHostEntry host;
55                 bool usesProxy;
56                 Dictionary<string,WebConnectionGroup> groups;
57                 bool sendContinue = true;
58                 bool useConnect;
59                 object hostE = new object ();
60                 bool useNagle;
61                 BindIPEndPoint endPointCallback = null;
62                 bool tcp_keepalive;
63                 int tcp_keepalive_time;
64                 int tcp_keepalive_interval;
65                 Timer idleTimer;
66
67                 // Constructors
68
69                 internal ServicePoint (Uri uri, int connectionLimit, int maxIdleTime)
70                 {
71                         this.uri = uri;  
72                         this.connectionLimit = connectionLimit;
73                         this.maxIdleTime = maxIdleTime; 
74                         this.currentConnections = 0;
75                         this.idleSince = DateTime.UtcNow;
76                 }
77                 
78                 // Properties
79                 
80                 public Uri Address {
81                         get { return uri; }
82                 }
83
84                 static Exception GetMustImplement ()
85                 {
86                         return new NotImplementedException ();
87                 }
88
89                 public BindIPEndPoint BindIPEndPointDelegate
90                 {
91                         get { return endPointCallback; }
92                         set { endPointCallback = value; }
93                 }
94                 
95                 public X509Certificate Certificate {
96                         get { return certificate; }
97                 }
98                 
99                 public X509Certificate ClientCertificate {
100                         get { return clientCertificate; }
101                 }
102
103                 [MonoTODO]
104                 public int ConnectionLeaseTimeout
105                 {
106                         get {
107                                 throw GetMustImplement ();
108                         }
109                         set {
110                                 throw GetMustImplement ();
111                         }
112                 }
113                 
114                 public int ConnectionLimit {
115                         get { return connectionLimit; }
116                         set {
117                                 if (value <= 0)
118                                         throw new ArgumentOutOfRangeException ();
119
120                                 connectionLimit = value;
121                         }
122                 }
123                 
124                 public string ConnectionName {
125                         get { return uri.Scheme; }
126                 }
127
128                 public int CurrentConnections {
129                         get {
130                                 return currentConnections;
131                         }
132                 }
133
134                 public DateTime IdleSince {
135                         get {
136                                 return idleSince.ToLocalTime ();
137                         }
138                 }
139
140                 public int MaxIdleTime {
141                         get { return maxIdleTime; }
142                         set { 
143                                 if (value < Timeout.Infinite || value > Int32.MaxValue)
144                                         throw new ArgumentOutOfRangeException ();
145
146                                 lock (this) {
147                                         maxIdleTime = value;
148                                         if (idleTimer != null)
149                                                 idleTimer.Change (maxIdleTime, maxIdleTime);
150                                 }
151                         }
152                 }
153                 
154                 public virtual Version ProtocolVersion {
155                         get { return protocolVersion; }
156                 }
157
158                 [MonoTODO]
159                 public int ReceiveBufferSize
160                 {
161                         get {
162                                 throw GetMustImplement ();
163                         }
164                         set {
165                                 throw GetMustImplement ();
166                         }
167                 }
168                 
169                 public bool SupportsPipelining {
170                         get { return HttpVersion.Version11.Equals (protocolVersion); }
171                 }
172
173
174                 public bool Expect100Continue {
175                         get { return SendContinue; }
176                         set { SendContinue = value; }
177                 }
178
179                 public bool UseNagleAlgorithm {
180                         get { return useNagle; }
181                         set { useNagle = value; }
182                 }
183
184                 internal bool SendContinue {
185                         get { return sendContinue &&
186                                      (protocolVersion == null || protocolVersion == HttpVersion.Version11); }
187                         set { sendContinue = value; }
188                 }
189                 // Methods
190
191                 public void SetTcpKeepAlive (bool enabled, int keepAliveTime, int keepAliveInterval)
192                 {
193                         if (enabled) {
194                                 if (keepAliveTime <= 0)
195                                         throw new ArgumentOutOfRangeException ("keepAliveTime", "Must be greater than 0");
196                                 if (keepAliveInterval <= 0)
197                                         throw new ArgumentOutOfRangeException ("keepAliveInterval", "Must be greater than 0");
198                         }
199
200                         tcp_keepalive = enabled;
201                         tcp_keepalive_time = keepAliveTime;
202                         tcp_keepalive_interval = keepAliveInterval;
203                 }
204
205                 internal void KeepAliveSetup (Socket socket)
206                 {
207                         if (!tcp_keepalive)
208                                 return;
209
210                         byte [] bytes = new byte [12];
211                         PutBytes (bytes, (uint) (tcp_keepalive ? 1 : 0), 0);
212                         PutBytes (bytes, (uint) tcp_keepalive_time, 4);
213                         PutBytes (bytes, (uint) tcp_keepalive_interval, 8);
214                         socket.IOControl (IOControlCode.KeepAliveValues, bytes, null);
215                 }
216
217                 static void PutBytes (byte [] bytes, uint v, int offset)
218                 {
219                         if (BitConverter.IsLittleEndian) {
220                                 bytes [offset] = (byte) (v & 0x000000ff);
221                                 bytes [offset + 1] = (byte) ((v & 0x0000ff00) >> 8);
222                                 bytes [offset + 2] = (byte) ((v & 0x00ff0000) >> 16);
223                                 bytes [offset + 3] = (byte) ((v & 0xff000000) >> 24);
224                         } else {
225                                 bytes [offset + 3] = (byte) (v & 0x000000ff);
226                                 bytes [offset + 2] = (byte) ((v & 0x0000ff00) >> 8);
227                                 bytes [offset + 1] = (byte) ((v & 0x00ff0000) >> 16);
228                                 bytes [offset] = (byte) ((v & 0xff000000) >> 24);
229                         }
230                 }
231
232                 // Internal Methods
233
234                 internal bool UsesProxy {
235                         get { return usesProxy; }
236                         set { usesProxy = value; }
237                 }
238
239                 internal bool UseConnect {
240                         get { return useConnect; }
241                         set { useConnect = value; }
242                 }
243
244                 WebConnectionGroup GetConnectionGroup (string name)
245                 {
246                         if (name == null)
247                                 name = "";
248
249                         /*
250                          * Optimization:
251                          * 
252                          * In the vast majority of cases, we only have one single WebConnectionGroup per ServicePoint, so we
253                          * don't need to allocate a dictionary.
254                          * 
255                          */
256
257                         WebConnectionGroup group;
258                         if (groups != null && groups.TryGetValue (name, out group))
259                                 return group;
260
261                         group = new WebConnectionGroup (this, name);
262                         group.ConnectionClosed += (s, e) => currentConnections--;
263
264                         if (groups == null)
265                                 groups = new Dictionary<string, WebConnectionGroup> ();
266                         groups.Add (name, group);
267
268                         return group;
269                 }
270
271                 void RemoveConnectionGroup (WebConnectionGroup group)
272                 {
273                         if (groups == null || groups.Count == 0)
274                                 throw new InvalidOperationException ();
275
276                         groups.Remove (group.Name);
277                 }
278
279                 bool CheckAvailableForRecycling (out DateTime outIdleSince)
280                 {
281                         outIdleSince = DateTime.MinValue;
282
283                         TimeSpan idleTimeSpan;
284                         List<WebConnectionGroup> groupList = null, removeList = null;
285                         lock (this) {
286                                 if (groups == null || groups.Count == 0) {
287                                         idleSince = DateTime.MinValue;
288                                         return true;
289                                 }
290
291                                 idleTimeSpan = TimeSpan.FromMilliseconds (maxIdleTime);
292
293                                 /*
294                                  * WebConnectionGroup.TryRecycle() must run outside the lock, so we need to
295                                  * copy the group dictionary if it exists.
296                                  * 
297                                  * In most cases, we only have a single connection group, so we can simply store
298                                  * that in a local variable instead of copying a collection.
299                                  * 
300                                  */
301
302                                 groupList = new List<WebConnectionGroup> (groups.Values);
303                         }
304
305                         foreach (var group in groupList) {
306                                 if (!group.TryRecycle (idleTimeSpan, ref outIdleSince))
307                                         continue;
308                                 if (removeList == null)
309                                         removeList = new List<WebConnectionGroup> ();
310                                 removeList.Add (group);
311                         }
312
313                         lock (this) {
314                                 idleSince = outIdleSince;
315
316                                 if (removeList != null && groups != null) {
317                                         foreach (var group in removeList)
318                                                 if (groups.ContainsKey (group.Name))
319                                                         RemoveConnectionGroup (group);
320                                 }
321
322                                 if (groups != null && groups.Count == 0)
323                                         groups = null;
324
325                                 if (groups == null) {
326                                         if (idleTimer != null) {
327                                                 idleTimer.Dispose ();
328                                                 idleTimer = null;
329                                         }
330                                         return true;
331                                 }
332
333                                 return false;
334                         }
335                 }
336
337                 void IdleTimerCallback (object obj)
338                 {
339                         DateTime dummy;
340                         CheckAvailableForRecycling (out dummy);
341                 }
342
343                 private bool HasTimedOut
344                 {
345                         get {
346                                 int timeout = ServicePointManager.DnsRefreshTimeout;
347                                 return timeout != Timeout.Infinite &&
348                                         (lastDnsResolve + TimeSpan.FromMilliseconds (timeout)) < DateTime.UtcNow;
349                         }
350                 }
351
352                 internal IPHostEntry HostEntry
353                 {
354                         get {
355                                 lock (hostE) {
356                                         string uriHost = uri.Host;
357
358                                         if (host == null || HasTimedOut) {
359                                                 lastDnsResolve = DateTime.UtcNow;
360
361                                                 try {
362                                                         host = Dns.GetHostEntry (uriHost);
363                                                 }
364                                                 catch (Exception) {
365                                                         return null;
366                                                 }
367                                         }
368                                 }
369
370                                 return host;
371                         }
372                 }
373
374                 internal void SetVersion (Version version)
375                 {
376                         protocolVersion = version;
377                 }
378
379                 internal EventHandler SendRequest (HttpWebRequest request, string groupName)
380                 {
381                         WebConnection cnc;
382                         
383                         lock (this) {
384                                 bool created;
385                                 WebConnectionGroup cncGroup = GetConnectionGroup (groupName);
386                                 cnc = cncGroup.GetConnection (request, out created);
387                                 if (created) {
388                                         ++currentConnections;
389                                         if (idleTimer == null)
390                                                 idleTimer = new Timer (IdleTimerCallback, null, maxIdleTime, maxIdleTime);
391                                 }
392                         }
393                         
394                         return cnc.SendRequest (request);
395                 }
396                 public bool CloseConnectionGroup (string connectionGroupName)
397                 {
398                         WebConnectionGroup cncGroup = null;
399
400                         lock (this) {
401                                 cncGroup = GetConnectionGroup (connectionGroupName);
402                                 if (cncGroup != null) {
403                                         RemoveConnectionGroup (cncGroup);
404                                 }
405                         }
406
407                         // WebConnectionGroup.Close() must *not* be called inside the lock
408                         if (cncGroup != null) {
409                                 cncGroup.Close ();
410                                 return true;
411                         }
412
413                         return false;
414                 }
415
416                 internal void SetServerCertificate (X509Certificate server)
417                 {
418                         var cloned = server != null ? new X509Certificate (server) : null;
419                         var old = Interlocked.Exchange (ref certificate, cloned);
420                         if (old != null)
421                                 old.Dispose ();
422                 }
423
424                 internal void SetClientCertificate (X509Certificate clientCertificate)
425                 {
426                         var cloned = clientCertificate != null ? new X509Certificate (clientCertificate) : null;
427                         var old = Interlocked.Exchange (ref clientCertificate, cloned);
428                         if (old != null)
429                                 old.Dispose ();
430                 }
431
432                 internal bool CallEndPointDelegate (Socket sock, IPEndPoint remote)
433                 {
434                         if (endPointCallback == null)
435                                 return true;
436
437                         int count = 0;
438                         for (;;) {
439                                 IPEndPoint local = null;
440                                 try {
441                                         local = endPointCallback (this,
442                                                 remote, count);
443                                 } catch {
444                                         // This is to differentiate from an
445                                         // OverflowException, which should propagate.
446                                         return false;
447                                 }
448
449                                 if (local == null)
450                                         return true;
451
452                                 try {
453                                         sock.Bind (local);
454                                 } catch (SocketException) {
455                                         // This is intentional; the docs say
456                                         // that if the Bind fails, we keep
457                                         // going until there is an
458                                         // OverflowException on the retry
459                                         // count.
460                                         checked { ++count; }
461                                         continue;
462                                 }
463
464                                 return true;
465                         }
466                 }
467         }
468 }
469
470