2009-12-02 Jb Evain <jbevain@novell.com>
[mono.git] / mcs / class / corlib / System.Runtime.Serialization.Formatters.Binary / BinaryFormatter.cs
1 // BinaryFormatter.cs
2 //
3 // Author:
4 //      Dick Porter (dick@ximian.com)
5 //  Lluis Sanchez Gual (lluis@ideary.com)
6 //
7 // (C) 2002 Ximian, Inc.  http://www.ximian.com
8 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
17 // 
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 // 
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 //
29
30 using System.Collections;
31 using System.IO;
32 using System.Reflection;
33 using System.Runtime.InteropServices;
34 using System.Runtime.Remoting.Messaging;
35 using System.Security.Permissions;
36
37 namespace System.Runtime.Serialization.Formatters.Binary {
38
39         [ComVisible (true)]
40         public sealed class BinaryFormatter : IRemotingFormatter, IFormatter 
41         {
42                 private FormatterAssemblyStyle assembly_format = FormatterAssemblyStyle.Simple;
43                 private SerializationBinder binder;
44                 private StreamingContext context;
45                 private ISurrogateSelector surrogate_selector;
46                 private FormatterTypeStyle type_format = FormatterTypeStyle.TypesAlways;
47                 private TypeFilterLevel filter_level = TypeFilterLevel.Full;
48                 
49                 public BinaryFormatter()
50                 {
51                         surrogate_selector=null;
52                         context=new StreamingContext(StreamingContextStates.All);
53                 }
54                 
55                 public BinaryFormatter(ISurrogateSelector selector, StreamingContext context)
56                 {
57                         surrogate_selector=selector;
58                         this.context=context;
59                 }
60
61                 public FormatterAssemblyStyle AssemblyFormat
62                 {
63                         get {
64                                 return(assembly_format);
65                         }
66                         set {
67                                 assembly_format=value;
68                         }
69                 }
70
71                 public SerializationBinder Binder
72                 {
73                         get {
74                                 return(binder);
75                         }
76                         set {
77                                 binder=value;
78                         }
79                 }
80
81                 public StreamingContext Context 
82                 {
83                         get {
84                                 return(context);
85                         }
86                         set {
87                                 context=value;
88                         }
89                 }
90                 
91                 public ISurrogateSelector SurrogateSelector 
92                 {
93                         get {
94                                 return(surrogate_selector);
95                         }
96                         set {
97                                 surrogate_selector=value;
98                         }
99                 }
100                 
101                 public FormatterTypeStyle TypeFormat 
102                 {
103                         get {
104                                 return(type_format);
105                         }
106                         set {
107                                 type_format=value;
108                         }
109                 }
110
111                 public TypeFilterLevel FilterLevel 
112                 {
113                         get { return filter_level; }
114                         set { filter_level = value; }
115                 }
116
117                 [SecurityPermission (SecurityAction.Demand, SerializationFormatter = true)]
118                 public object Deserialize (Stream serializationStream)
119                 {
120                         return NoCheckDeserialize (serializationStream, null);
121                 }
122
123                 [SecurityPermission (SecurityAction.Demand, SerializationFormatter = true)]
124                 public object Deserialize (Stream serializationStream, HeaderHandler handler) 
125                 {
126                         return NoCheckDeserialize (serializationStream, handler);
127                 }
128
129                 // shared by Deserialize and UnsafeDeserialize which both involve different security checks
130                 private object NoCheckDeserialize (Stream serializationStream, HeaderHandler handler)
131                 {
132                         if(serializationStream==null) 
133                         {
134                                 throw new ArgumentNullException("serializationStream");
135                         }
136                         if(serializationStream.CanSeek &&
137                                 serializationStream.Length==0) 
138                         {
139                                 throw new SerializationException("serializationStream supports seeking, but its length is 0");
140                         }
141
142                         BinaryReader reader = new BinaryReader (serializationStream);
143
144                         bool hasHeader;
145                         ReadBinaryHeader (reader, out hasHeader);
146
147                         // Messages are read using a special static method, which does not use ObjectReader
148                         // if it is not needed. This saves time and memory.
149
150                         BinaryElement elem = (BinaryElement) reader.Read ();
151
152                         if (elem == BinaryElement.MethodCall) {
153                                 return MessageFormatter.ReadMethodCall (elem, reader, hasHeader, handler, this);
154                         }
155                         else if (elem == BinaryElement.MethodResponse) {
156                                 return MessageFormatter.ReadMethodResponse (elem, reader, hasHeader, handler, null, this);
157                         }
158                         else {
159                                 ObjectReader serializer = new ObjectReader (this);
160
161                                 object result;
162                                 Header[] headers;
163                                 serializer.ReadObjectGraph (elem, reader, hasHeader, out result, out headers);
164                                 if (handler != null) handler(headers);
165                                 return result;
166                         }
167                 }
168                 
169                 [SecurityPermission (SecurityAction.Demand, SerializationFormatter = true)]
170                 public object DeserializeMethodResponse (Stream serializationStream, HeaderHandler handler, IMethodCallMessage methodCallMessage)
171                 {
172                         return NoCheckDeserializeMethodResponse (serializationStream, handler, methodCallMessage);
173                 }
174
175                 // shared by DeserializeMethodResponse and UnsafeDeserializeMethodResponse which both involve different security checks
176                 private object NoCheckDeserializeMethodResponse (Stream serializationStream, HeaderHandler handler, IMethodCallMessage methodCallMessage)
177                 {
178                         if(serializationStream==null) {
179                                 throw new ArgumentNullException("serializationStream");
180                         }
181                         if(serializationStream.CanSeek &&
182                            serializationStream.Length==0) {
183                                 throw new SerializationException("serializationStream supports seeking, but its length is 0");
184                         }
185
186                         BinaryReader reader = new BinaryReader (serializationStream);
187
188                         bool hasHeader;
189                         ReadBinaryHeader (reader, out hasHeader);
190                         return MessageFormatter.ReadMethodResponse (reader, hasHeader, handler, methodCallMessage, this);
191                 }
192
193                 public void Serialize(Stream serializationStream, object graph)
194                 {
195                         Serialize (serializationStream, graph, null);
196                 }
197
198                 [SecurityPermission (SecurityAction.Demand, SerializationFormatter = true)]
199                 public void Serialize(Stream serializationStream, object graph, Header[] headers)
200                 {
201                         if(serializationStream==null) {
202                                 throw new ArgumentNullException ("serializationStream");
203                         }
204
205                         BinaryWriter writer = new BinaryWriter (serializationStream);
206                         WriteBinaryHeader (writer, headers!=null);
207
208                         if (graph is IMethodCallMessage) {
209                                 MessageFormatter.WriteMethodCall (writer, graph, headers, surrogate_selector, context, assembly_format, type_format);
210                         }
211                         else if (graph is IMethodReturnMessage)  {
212                                 MessageFormatter.WriteMethodResponse (writer, graph, headers, surrogate_selector, context, assembly_format, type_format);
213                         }
214                         else {
215                                 ObjectWriter serializer = new ObjectWriter (surrogate_selector, context, assembly_format, type_format);
216                                 serializer.WriteObjectGraph (writer, graph, headers);
217                         }
218                         writer.Flush();
219                 }
220
221                 // faster version (under CAS) as this requires a LinkDemand versus full Demand (i.e. a stack-walk)
222                 // shouldn't be called unless the code is intended to be executed at full-trust
223                 [ComVisible (false)]
224                 [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
225                 public object UnsafeDeserialize (Stream serializationStream, HeaderHandler handler) 
226                 {
227                         return NoCheckDeserialize (serializationStream, handler);
228                 }
229                 
230                 // faster version (under CAS) as this requires a LinkDemand versus full Demand (i.e. a stack-walk)
231                 // shouldn't be called unless the code is intended to be executed at full-trust
232                 [ComVisible (false)]
233                 [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)]
234                 public object UnsafeDeserializeMethodResponse (Stream serializationStream, HeaderHandler handler, IMethodCallMessage methodCallMessage)
235                 {
236                         return NoCheckDeserializeMethodResponse (serializationStream, handler, methodCallMessage);
237                 }
238                 
239                 private void WriteBinaryHeader (BinaryWriter writer, bool hasHeaders)
240                 {
241                         writer.Write ((byte)BinaryElement.Header);
242                         writer.Write ((int)1);
243                         if (hasHeaders) writer.Write ((int)2);
244                         else writer.Write ((int)-1);
245                         writer.Write ((int)1);
246                         writer.Write ((int)0);
247                 }
248
249                 private void ReadBinaryHeader (BinaryReader reader, out bool hasHeaders)
250                 {
251                         reader.ReadByte();
252                         reader.ReadInt32();
253                         int val = reader.ReadInt32();
254                         hasHeaders = (val==2);
255                         reader.ReadInt32();
256                         reader.ReadInt32();
257                 }
258         }
259 }