Compare commits

...
112 Commits
Author SHA1 Message Date
Daniel J Sell 5d600522ed [asp.net] Fix for bug #653192. making MasterPageFile handle relative paths
MasterPageFile should be relative to the file being parsed, not the
request path
2010-11-12 11:24:41 +01:00
Gonzalo Paniagua Javier 2427b2b861 Don't cache child nodes when security trimming is enabled.
When SecurityTrimmingEnabled is set to true for the node, the cached children
collection also depends on the IPrincipal set for the current context.

Fixes bug #641449.
2010-11-11 21:19:43 -05:00
Marek Habersack 11aeecfa3a [corlib] Fix for bug #652807. Handle RegistryValueKind.QWord in Win32RegistryApi.{Get,Set}Value 2010-11-11 01:59:17 +01:00
Zoltan Varga e27b81a652 When single stepping from a exception throw site, single step to the catch site. Fixes #652590. 2010-11-10 18:27:01 +01:00
Zoltan Varga 8f3f18568c Fix a typo in process_breakpoint_inner which doesn't break our tests for some reason. 2010-11-08 20:23:34 +01:00
Zoltan Varga f886d89ef7 Enlarge try-finally blocks preceeded by a Monitor.Enter () call to include the call itself, to avoid races inherent in such code. Fixes #651546. 2010-11-05 19:12:35 +01:00
Zoltan Varga 44ea00024a Fix DISABLE_REFLECTION_EMIT build. 2010-11-05 16:30:40 +01:00
Marek Habersack 4aabcf3455 [asp.net,routing] Fix for bug #651593. Don't match all-literal routes for URLs with excessive segments. 2010-11-05 11:37:55 +01:00
Zoltan Varga a22f24834e Fix a bug introduced by the previous change to mono_jit_walk_stack_from_ctx_in_thread (). 2010-11-05 07:46:12 +01:00
Zoltan Varga cea5d2223b Fix crashes in the debugger stack walk code if a gshared method calls another using a managed-to-native translation. 2010-11-05 06:54:06 +01:00
Zoltan Varga bc1373c0d8 Fix more gshared problems in the soft debugger. 2010-11-05 06:38:19 +01:00
Zoltan Varga c8d96f618a Fix gshared support in the soft debugger. Fixes #651251. 2010-11-05 05:33:57 +01:00
Martin Baulig c530931921 Add mono_register_symfile_for_assembly() for bundles.
2010-11-03  Martin Baulig  <[email protected]>

	* mono-debug.c (mono_register_symfile_for_assembly): New method.
	This is used together with mono_register_bundled_assemblies() and
	mono_register_config_for_assembly() to support bundles.
2010-11-03 20:42:41 +01:00
Zoltan Varga e373b1cf49 Fix encoding of large strings in the soft debugger api. Fixes #648832. 2010-11-03 19:17:27 +01:00
Gonzalo Paniagua Javier ba5de9d036 Revert change in FromBinary 2010-11-02 18:58:16 -04:00
Andrew Jorgensen a51e35bbec Map libcups for mac
Fixes bnc#649994
2010-11-02 15:18:54 -06:00
Gonzalo Paniagua Javier 681aff17d2 Renaming a dangling symlink works now
Ditto.

	Fixes bug #650779.
2010-11-02 14:50:58 -04:00
Marek Habersack d1703c40ef [asp.net] 4.0-only types don't need the NET_4_0 ifdef and should be in net_4_0_System.Web.dll.sources 2010-11-02 11:31:55 +01:00
Marek Habersack c53bce8e0a [asp.net] ObjectStateFormatter.{De}serialize methods taking stream use a magic value to mark the stream. 2010-11-02 11:23:35 +01:00
Sebastien Pouliot 3aad88e828 Fix (likely copy-paste) typo on FormsAuthPasswordFormat
* System.Web.Security/FormsAuthentication.cs: Fix typo (MD5->SHA1).
I suspect the later is not used very much by mono users

* Test/System.Web.Security/FormsAuthenticationTest.cs: Small change to
make sure the hash name is not case sensitive
2010-11-02 11:22:45 +01:00
Sebastien Pouliot 2037a51576 Adjust System.Web.Extensions[_1.0].dll.sources wrt MachineKeySectionUtils.cs move 2010-11-02 11:22:23 +01:00
Sebastien Pouliot 8d8cae9016 A few moves/changes following previous patch review
* Makefile: Compile tests with TEST defined (to include System.Web.Util.
MachineKeySectionUtils unit tests)
* System.Web.dll.sources: Move MachineKeySectionUtils.cs from System.
Web.Configuration_2.0 to System.Web.Util
* System.Web_test.dll.sources: Move MachineKeySectionUtilsTest.cs from
System.Web.Configuration_2.0 to System.Web.Util

* System.Web.Configuration_2.0/MachineKeySection.cs: Adjust using
clauses. Uncomment some code. Fix TripleDES versus 3DES for Validation
under NET_4_0. Remove 'private' on fields/methods.
* System.Web.Handlers/AssemblyResourceLoader.cs: Adjust using clauses
* System.Web.Security/MembershipHelper.cs: Adjust using clauses
* System.Web.Security/RolePrincipal.cs: Adjust using clauses
* System.Web.SessionState_2.0/SessionId.cs: Adjust using clauses
* System.Web.UI/LosFormatter.cs: Adjust using clauses.
* System.Web.Util/MachineKeySectionUtils.cs: Moved from System.Web.
Configuration_2.0. Rename namespace and remove 'internal' on type
declaration

* Test/System.Web.Util/MachineKeySectionUtilsTest.cs: Moved from Test/
System.Web.Configuration/MachineKeySectionTest.cs. Add test case for
TripleDES versus 3DES
2010-11-02 11:22:06 +01:00
Sebastien Pouliot 4106e07cca Normalization of cryptographic uses in asp.net
* System.Web.Configuration_2.0/MachineKeyRegistryStorage.cs:
Remove key length check and generic key generation.

* System.Web.Configuration_2.0/MachineKeySection.cs: Add support for 4.0
ValidationAlgorithm and the use of custom algorithms (validation and
decryption). Allow the use of any, valid, key length (based on the
algorithm). Let each algorithm creates its own key (e.g. special needs,
default length...)

* System.Web.Configuration_2.0/MachineKeySectionUtils.cs: Remove key
generation (from random) code and 192bits key length hack (won't work
with custom algorithms). Add support for new (4.0) algorithms, including
custom ones. Provide uniform/shared code to Encrypt/Decrypt, Sign/Verify
and EncryptSign/VerifyDecrypt using MachineKeySection data.

* System.Web.Configuration_2.0/MachineKeyValidation.cs: Add new (4.0)
values.

* System.Web.Configuration_2.0/MachineKeyValidationConverter.cs: Add
support for new (4.0) algorithms.

* System.Web.Handlers/AssemblyResourceLoader.cs: Use the new common
cryptographic code and base64 the encrypted data.

* System.Web.Security/FormsAuthentication.cs: Use the new common
cryptographic code and base64 the signed and/or encrypted data.

* System.Web.Security/MembershipHelper.cs: Use the new common
cryptographic code - this should be 100% compatible with existing data.

* System.Web.Security/RolePrincipal.cs: Use the new common cryptographic
code.

* System.Web.Security/SqliteMembershipProvider.cs: Adapt code for
internal API change.

* System.Web.UI/LosFormatter.cs: Adapt code for internal API change.
Fix some small behaviro changes wrt NET_4_0

* System.Web.UI/ObjectStateFormatter.cs: Use the new common cryptographic
code.

* System.Web.UI/Page.cs: Remove code that is now unneeded (with the new
common cryptogrraphic code).

* System.Web.Configuration_2.0/MachineKeyCompatibilityMode.cs: New.

* Test/System.Web.Configuration/MachineKeyValidationConverterTest.cs:
Add more, mostly 4.0, test cases.

* Test/System.Web.Security/FormsAuthenticationTest.cs: Add test case to
ensure HashPasswordForStoringInConfigFile is not case sensitive.

* Test/System.Web.UI/LosFormatterTest.cs: Add some rountrip test cases
with the different ctors
2010-11-02 11:16:12 +01:00
Marek Habersack 963f28f38b [runtime] mono_cfg_set_exception is not present in 2.8. Fixes the build. 2010-11-02 11:09:52 +01:00
Gonzalo Paniagua Javier bd045fc008 Avoid killing the thread if socket already null
In some weird cases socket is null when we try to close it.
2010-11-01 18:53:53 -04:00
Marek Safar cff2890d8d Set correct result type for chained folded enum subtraction 2010-11-01 11:42:35 +00:00
Zoltan Varga 101eaf3215 Cache the array of classes in find_typespec_for_class (). 2010-11-01 00:44:58 +01:00
Zoltan Varga 5cfa597a30 Avoid asserts if a forced inline fails. Fix typos. Fixes #650407. 2010-11-01 00:44:43 +01:00
Brian Luczkiewicz 84be0b20e5 Enable --aot (but not --aot=full) on osx/x86 2010-10-31 21:48:41 +01:00
Miguel de Icaza e7de26c774 Expose some of our internals to the Mono.Winforms assembly 2010-10-31 15:59:51 -04:00
Miguel de Icaza 8a31a4b263 Fix broken patch 2010-10-31 15:54:41 -04:00
Miguel de Icaza 06e2e82bb0 Allow this file to expose its types as public if needed 2010-10-31 15:51:38 -04:00
Zoltan Varga 47429fb521 Fix the generation of GenericEqualityComparer () instances in AOT. 2010-10-31 02:57:30 +02:00
Geoff Norton 42459678e9 Fix the build 2010-10-30 18:22:49 -04:00
Geoff Norton 44dc98ddd1 [OSX] Reintroduce Cocoa System.Drawing support
The old Cocoa backend for System.Drawing appears to still work.  You must
pass in a NSView.Handle while in the DrawRect method, or with lockFocus
called to prepare the NSGraphicsContext.
2010-10-30 14:53:18 -04:00
Marek Habersack 32832e39bb [asp.net] Fix for bug #649551. The LosFormatter (bool, string) constructor does not expect a base64-encoded string.
Telerik controls pass the string "string" as the macKeyModifier parameter to the constructor. Tests show that .NET
accepts such input without throwing an error. The passed string is now converted into a byte array and passed to
the LosFormatter (bool, byte[]) constructor.

This is a backport of 19e5207189
2010-10-29 16:18:53 +02:00
Marek Habersack de60018067 [asp.net] Fix for bug #649034. Control.FindControl continues to search for controls above itself if it's a naming container.
When a control is a naming container and an attempt to find a control with non-segmented id (e.g. 'myControl') is made,
the search continues to the control's naming container if pathOffset is 0, that is we're at the start of the search.
2010-10-29 14:49:52 +02:00
Geoff Norton 06e3b0379b [OSX] Fix debug=casts on OSX (Bug: 639172)
mono --debug=casts requires fast tls access and the jit tls intrinsic.
We already had support for OP_TLS_GET on darwin/x86, but we did not
expose the "tls offset (pthread_key_t)" from mini to the intrinsic,
instead falling back on the io-layer keys.  We now store mono_lmf_addr
in a pthread_key for darwin/x86 so that we can do fast-tls in the jit
and fix this feature.  X86 only for now.

r: kumpera
2010-10-28 19:52:58 -04:00
Marek Safar 2626e53a2e [646997] Correctly emit platform ILOnly flag 2010-10-27 13:40:46 +01:00
Rodrigo Kumpera 5015ec260b Fix some counters under 32bits. 2010-10-26 23:26:01 -02:00
Marek Habersack 91f700f9d4 [asp.net] HttpRuntime.AppDomainAppPath may be null during tests, check it before using. 2010-10-26 02:02:21 +02:00
Marek Habersack 63f589c152 [asp.net,routing] Fix for bug #648901. Matching engine must ignore trailing slash in the URLs. 2010-10-26 02:01:44 +02:00
Zoltan Varga c223d5999b Disable catchpoints when the DISABLE_BREAKPOINTS flag is used during an invoke. Fixes #632224. 2010-10-25 18:09:32 +02:00
Marek Habersack 6d8bafaa07 [asp.net] Better handling of application's AppDomain restart
* HttpRuntime.cs: disable filesystem watchers on appdomain shutdown and refuse to process
  requests while the current AppDomain is unloading
* HttpApplicationFactory.cs: if the current AppDomain is unloading, ignore FileSystemWatcher
  notifications
* WebConfigurationManager.cs: work around a deadlock issue when entering a ReaderWriterLockSlim
  upgradeable read lock very early during ASP.NET runtime/AppDomain initialization. Every few runs
  the attempt would lock up and since adding a section to cache is not a critical operation we can
  afford timing the lock out in this case. The lockup is probably due to the fact that RWLS is using
  thread local storage to store the current thread's lock status and it may happen that the TLS is
  not cleared during thread object finalization (see metadata/threads.c, the start_wrapper function)
2010-10-25 14:30:35 +02:00
Zoltan Varga 5625f3afe8 Use int 3 as G_BREAKPOINT on x86-64 too. Hopefully fixes #648838. 2010-10-23 20:38:59 +02:00
Zoltan Varga 59959cefb2 Fix another regression in the Array.Sort () methods, allow keys and items to be of different length. Fixes #648828. 2010-10-23 16:48:11 +02:00
Zoltan Varga 217ec2ce11 Implement memory barriers for amd64/x86. Fixes #648831. 2010-10-23 16:31:09 +02:00
Zoltan Varga 4f47316df0 Emit GenericEqualityComparer<T> instances for each EqualityComparer<T> instance in AOT, the former is created dynamically by the latter. 2010-10-22 17:58:08 +02:00
Zoltan Varga 589a83dfa4 Use locale_charset() from iconv which will use nl_langinfo (CODESET) anyways but it will
do canonicalization so we will get the correct charset name, because nl_langinfo (CODESET)
can return different things on different systems. This at least fixes OpenBSD.
2010-10-22 17:28:47 +02:00
Marek Habersack b54ac46230 [asp.net] Part of fix for bug #579837. AuthorizationRule.SerializeElement will not process unmodified elements.
* AuthorizationRule.cs: if the configuration save is not Full, SerializeElement checks whether the rule being
  serialized is modified. If it isn't, validation and serialization are not performed.
* AuthorizationRuleCollection.cs: there is no element name for the collection.
2010-10-22 15:48:14 +02:00
Marek Habersack 7c22cb0135 [configuration] Part of fix for bug #579837. CommaDelimitedStringCollection must properly note that it was modified.
When one manipulates the collection as an instance of StringCollection, the 'modified' field will not
be set (Add, Remove etc. from the underlying StringCollection type will be used). To work around it
a check has to be performed in IsModified whether the contents of the collection changed. It is done
by comparing string hash codes of the original vs current string.
CommaDelimitedStringCollectionConverter forces string hash code update on the new collection, so that IsModified
works correctly on collections converted from comma-delimited strings.
2010-10-22 15:47:57 +02:00
Paolo Molaro 8e890a3bf8 Search for dllimported shared libs in the base directory, not cwd.
* loader.c: we don't search the current directory anymore for shared
libraries referenced in DllImport attributes, as it has a slight
security risk. We search in the same directory where the referencing
image was loaded from, instead. Fixes bug# 641915.
2010-10-22 10:51:15 +02:00
Gonzalo Paniagua Javier b80ffc9882 Replace EnumProcesses with OpenProcess
namedmutex_prewait was (partially) listing the running processes and
	then searching through them. Now we use OpenProcess to verify the owner
	of the mutex is still alive.

	Fixes bug #648133 (note that you need MONO_ENABLE_SHM for this to work)
2010-10-21 18:58:45 -04:00
Ankit Jain 61c8b99b3f [xbuild] Fix bug #646941. Add explicit System.Core for >=3.5 projects.
For projects targeting TargetFrameworkVersion >= 3.5, automatically
add a reference to System.Core . This can be controlled via two
properties:

 $(AddAdditionalExplicitAssemblyReferences) and
 $(AdditionalExplicitAssemblyReferences) .

This is used only for projects built with ToolsVersion=4.0 .
2010-10-22 02:57:07 +05:30
Ankit Jain 4a60b3f3fa [xbuild] Set default TargetFrameworkVersion=4.0 for ToolsVersion=4.0 2010-10-22 02:57:07 +05:30
Ankit Jain d2bb6fe8e1 [xbuild] Add ResolveAssemblyReferencesDependsOn .
Add GetFrameworkPaths and PrepareForBuild as dependencies for
the ResolveAssemblyReferences target. This is required when it is
invoked directly from MD.

Patch from Michael Hutchinson ([email protected]).
2010-10-22 02:57:06 +05:30
Ankit Jain 9f384277cd [xbuild] Reset cache of built targets, on a new project build.
All targets that get built are tracked by the engine, to avoid
unnecessary builds of targets. This should be reset on engine.Build,
unless it is explicitly requested *not to* reset it, via BuildFlags.
2010-10-22 02:57:06 +05:30
Ankit Jain 10b7c361bb [xbuild] Reset ConsoleLogger when a build finishes.
MSBuild hosts like monodevelop, which use the same logger
for multiple builds, get errors/warnings from older builds.
So, reset them whenever the BuildFinished event is raised.

ILogger.Shutdown () is invoked when the host is about to quit,
according to msdn, so can't use that.
2010-10-22 02:57:05 +05:30
Ankit Jain 1e535e61d3 [xbuild] Log TaskFinished even when task fails to initialize. 2010-10-22 02:57:05 +05:30
Ankit Jain fb42e1e12b [xbuild] Update regex to not require EndProject in a sln file.
In a solution file, a Project might not have a corresponding
EndProject. This seems to be supported by VS, so updating xbuild
to support that too. Updated the regex.
2010-10-22 02:57:05 +05:30
Ankit Jain 7358969934 [xbuild] Use files referenced by resx for dependency check.
For .resx resource files, check files referenced by the resx
file also, to determine whether to resgen it or not.

IsResgenRequired () has been taken from MonoDevelop
(main/src/core/MonoDevelop.Core/MonoDevelop.Projects.Formats.MD1/MD1DotNetProjectHandler.cs)
2010-10-22 02:57:04 +05:30
Ankit Jain 89c7bb82d4 [xbuild] Fix case sensitive environment variables for ToolTask.
Use ProcessStringDictionary in ToolTask for EnvironmentVariables,
as this retains the original case of the keys. Without this
environment vars would all be passed as lowercase!

This was removed in a previous patch by mistake.
2010-10-22 02:57:04 +05:30
Ankit Jain c28b4ea9d7 [xbuild] Add ToolTask.EnvironmentVariables property.
* class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolTask.cs
	(EnvironmentVariables): New.
	(ExecuteTool): Merge EnvironmentVariables with
	EnvironmentOverride
	* class/Microsoft.Build.Tasks/Microsoft.Build.Tasks/GenerateResource.cs
	(Resgen.Execute): Use EnvironmentVariables to set MONO_IOMAP=drive .
2010-10-22 02:57:03 +05:30
Ankit Jain b80d1ca6eb [xbuild] Fix a race condition in ToolTask.
* class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolTask.cs
 (ExecuteTool): When StartProcess returns, the process has already .Start()'ed
 If we subscribe to the output events after that, then for processes that
 finish executing before we can subscribe, we won't get the output/error
 events at all! So, pass the handlers to StartProcess itself, so that
 they get added before the process is started.
2010-10-22 02:57:03 +05:30
Ankit Jain 5f80fd9448 [xbuild] Fix handling of tool output.
The *StreamChanged event for ProcessWrapper may get parts of
long lines, so process the complete ones that we have (for matching
error/warning), and save rest for processing when the rest of it
is received.

Also, don't ignore empty lines.

* class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolTask.cs
2010-10-22 02:57:02 +05:30
Ankit Jain e53a4c3776 [xbuild] Fix ConsoleLogger's output, extra blank lines etc. 2010-10-22 02:57:02 +05:30
Ankit Jain 69a95ff53d [xbuild] Reduce ConsoleLogger's unnecessary output.
ConsoleLogger was emitting target names, even if they didn't have
any useful output, which resulted in lots of "Target foo:" in the
output, with no other related msgs.

 Target Foo:
 Target Bar:
 Target Xyz:

Emit project/target/task headers only if they result in a message,
error or warning. This results in much cleaner output.
2010-10-22 02:57:01 +05:30
Ankit Jain 5025f28490 [xbuild] Log default msg for TargetSkipped if @reason is null or empty. 2010-10-22 02:57:01 +05:30
Gonzalo Paniagua Javier e3c340f1c1 FromBinary does not need ToLocalTime
When converting to DateTime from a long, we don't need ToLocalTime().
	Setting the kind to Local is enough.
	Patch from Mig.

	Fixes bug #648252.
2010-10-21 16:02:43 -04:00
Zoltan Varga 2fdbdc2bc0 Fix building the logging profiler. 2010-10-21 21:57:45 +02:00
Miguel de Icaza 2875496241 Document server option to --debugger-agent 2010-10-21 14:13:45 -04:00
Andrew Jorgensen f98dc57542 Bump version to 2.8.1 2010-10-21 11:54:30 -06:00
Zoltan Varga 905e43efe2 Fix an assert in the LLVM backend if a long value was passed to 'localloc'. 2010-10-21 19:01:55 +02:00
Rodrigo Kumpera b6a25dfdd2 Disable cardtable unde 64bits as it is broken for 2.8. 2010-10-21 14:40:59 -02:00
Geoff Norton 16c125bc9b Fix a crash when using the embedding api
error_msg is null when passed into this function from a few places, so
lets not do a null deref here.
2010-10-21 12:29:02 -04:00
Michael Hutchinson 33d466d421 [Embedding] Make mono-dl-fallback.h public-safe 2010-10-21 12:29:01 -04:00
Miguel de Icaza 4b0101dd80 Do not install sample header, add to EXTRA_DIST 2010-10-21 12:29:01 -04:00
Miguel de Icaza 84e9b39b17 [Embedded] Add new fallback API to allow hooking up to the P/Invoke lookup system
This patch allows a developer to register a fallback for P/Invoke when
embedding Mono.   Typically this is done when you statically link all of your
libraries in some embedded systems and you need to dynamically resolve symbol
names.

There is a *sample* API included (but not compiled into Mono itself) called
mono-embed.c that shows a layman use of the API.   A full implementation would
mandate sorted tables, and would use a bsearch or a hashtable instead of having
linear searches.
2010-10-21 12:29:00 -04:00
Gonzalo Paniagua Javier 8a5647b1d6 Allow ordinal entry points in windows.
Windows allows entry point names like "#10" which refer to the Nth
	function (n > 1 and less than the highest ordinal value in the .def
	file).

	Fixes bug #636966.
2010-10-21 12:24:53 -04:00
Gonzalo Paniagua Javier 733d3f45d1 Linux /proc/mounts might have escaped characters
Translate escaped characters in mount paths.

	Fixes bug #637078.
2010-10-21 12:24:43 -04:00
Gonzalo Paniagua Javier 29ffd5258c Use UTF8 instead of ASCII when reading mount info
This allows for mount points with UTF8 characters in them.
2010-10-21 12:24:27 -04:00
Gonzalo Paniagua Javier e845f96a79 Fixed GetLogicalDriveString
When calling GetLogicalDriveString, icall.c was passing the
	length in the wrong units.

	GetLogicalDriveString now translates any octal sequence found
	into its corresponding byte. Use the UTF16 length
	('items_written') instead of the UTF8 input string length
	('items_read') when computing the total size.
2010-10-21 12:24:02 -04:00
Gonzalo Paniagua Javier 51e0ca445a Fix return value of items_read
items_read was not being initialized and it was not being set in the
	fast common case of g_utf8_to_utf16().
2010-10-21 12:23:43 -04:00
Gonzalo Paniagua Javier f95ed5726f UDP sockets allow connections to Any
UDP sockets that call Connect() to set a default address for datagrams
	sent, can call Connect() again with IPv6Any or Any to 'disconnect'.

	Fixes bug #639098.
2010-10-21 12:22:05 -04:00
Gonzalo Paniagua Javier 03af9e4c5d GetProcessById now works on the Mac too
Ditto.
	This should fix MD problems when SHM is disabled.
2010-10-21 12:21:16 -04:00
Gonzalo Paniagua Javier 921a0951d8 Map SO_EXCLUSIVEADDRUSE to !SO_REUSEADDR
This will make windows app that use that property work on *nix.
	Fixes bug #643475.
2010-10-21 12:18:04 -04:00
Gonzalo Paniagua Javier c6ee6980ce Fix the collision handling code
After the fix for bug #605092, inserting timers with an equal due time
	was failing because searching in the list was also using a reference
	comparison. Now, when adding a new timer, we search using just the due
	time.
	Fixes bug #648130.
2010-10-21 11:36:52 -04:00
Zoltan Varga 429c26b022 Avoid caching stuff in socket-io.c in static variables, since the socket assembly can be unloaded, cache them in MonoDomain instead. 2010-10-21 16:17:50 +02:00
Marek Habersack 5b4ab167be [asp.net,wcf] WCF proxies are generated using a slightly different mode of operation.
WCF proxies don't include full namespace of the contract.
2010-10-21 10:29:16 +02:00
Marek Habersack 58e8a395c4 [wcf] make /js and /jsdebug dispatchers work.
There were several issues here:

- The IChannelDispatcherBoundListener was defined twice, in two different namespaces, and it caused code in
  ChannelDispatcher.Attach not to set its associated listener's ChannelDispatcher property to the correct value.
  This, in turn, caused incorrect HttpListenerManagerTable operation, where it would put the "/js" and "/jsdebug"
  dispatchers in separate HttpListenerManagers, instead of in the main (base) service's one.
- After fixing the above, it turned out that SvcHttpHandler selected the manager based on the host's base address,
  when it should first try to find one whose URL matches the current request exactly.
2010-10-21 10:28:58 +02:00
Marek Habersack 0e93173683 [asp.net] make sure the string we pass to DecryptAssemblyResource is a valid Base64 string 2010-10-21 10:27:21 +02:00
Marek Habersack 20f6a72044 [wcf] ServiceHost directive can span several lines. 2010-10-21 10:27:07 +02:00
Marek Habersack 552a1f5c7e [wcf] Don't close HTTP response prematurely.
Service is invoked in the context of the System.Web pipeline and closing the response before the final
output stream flush causes the generated response not to ever reach the client. This patch makes sure
the System.Web pipeline takes care of all the response housekeeping.
2010-10-21 10:26:53 +02:00
Atsushi Eno d3b4997ff1 Remove extra call to HttpResponse.Flush() which would crash. 2010-10-21 10:26:39 +02:00
Gonzalo Paniagua Javier 722e143cc0 Set have_response
Set have_response to true when there's a protocol error or a previous
	exception for POST/PUT.
	Patch by Bassam Tabbara.
2010-10-20 13:57:25 -04:00
Gonzalo Paniagua Javier 0875d61ca2 Add support for EnableSsl in smtp config.
Ditto.
	Fixes bug #644816.
2010-10-20 13:57:24 -04:00
Gonzalo Paniagua Javier 0d8e8f7df9 Handle special case when disposing a socket.
When disposing a socket that has more than one asynchronous read/write
	pending, one of the callbacks could call DisposeAllOnClose() while
	another one is waiting on the lock. Once the lock is acquired,
	queue.Count will be 0 and Dequeue would fail.
	This is fixed now.

	Fixes bug #645675.
2010-10-20 13:57:23 -04:00
Gonzalo Paniagua Javier 135e5eb0df Able to read MS serialized nullable<primitive>
Handle boxed primitive types for nullable fields.
	Fixes bug #646556.
2010-10-20 01:37:26 -04:00
Zoltan Varga b2ba1f46f7 Avoid trying to read the gc name in the AOT runtime from older AOT images. Fixes #647918. 2010-10-20 05:10:30 +02:00
Tak 15e954d508 [Fix] Ensure that exceptions are propagated when embedding
* metadata/object.c:
* mini/mini.c:
Ensure that exceptions get propagated back to the caller
when mono is being embedded.
License: MIT/X11
2010-10-19 14:20:20 +02:00
Zoltan Varga 86bc7170e5 Avoid calling sem_post on a uninitialized semaphore during thread attach, it works under linux, but fails under *bsd. Fixes #647248. 2010-10-18 01:57:05 +02:00
Gonzalo Paniagua Javier 3779a70dcc [ThreadPool] Clear the thread state
Clear the thread state after finishing a work item. We were only
	resetting the background state.
2010-10-14 16:49:46 -04:00
Zoltan Varga 160cf6a24e Fix crashes in the AOT compiler when the loaded LLVM module is used. Fixes #646314. 2010-10-14 22:20:06 +02:00
Zoltan Varga 1cd68dd08c Update the IMT thunk creation code on sparc to support net 4.0. 2010-10-14 21:57:28 +02:00
Zoltan Varga 0ee4f2dbd1 Avoid a crash in g_convert () if iconv_open () fails. 2010-10-14 21:56:33 +02:00
Jb Evain 44d00f87d5 Add pretty print support for null values in JsonObjects 2010-10-14 14:23:37 +02:00
Jb Evain b214e1e693 Allow null values in JsonObjects 2010-10-14 14:23:19 +02:00
Marek Safar cda5880b42 [646298] Compile multiple interface event declarators 2010-10-14 10:57:25 +01:00
Robert Nagy e97de6b450 merge from head 2010-10-14 02:23:20 +02:00
Marek Safar d8034534d0 [642975] Fix initializer of partially static multidimensional arrays 2010-10-08 12:36:34 -04:00
Gonzalo Paniagua Javier b49c845d35 X509Chain always uses the LM store
X509Chain will now add the LM store certificates always, even when the
	CU store is selected.
2010-10-08 02:08:21 -04:00
Zoltan Varga b6a60964d8 Fix the sparc build. 2010-10-08 05:16:34 +02:00
141 changed files with 3819 additions and 1456 deletions

No files matched your search

+1 -1
View File
@@ -6,7 +6,7 @@ AC_CANONICAL_SYSTEM
m4_ifdef([_A][M_PROG_TAR],[_A][M_SET_OPTION([tar-ustar])])
AM_CONFIG_HEADER(config.h)
AM_INIT_AUTOMAKE(mono,2.8)
AM_INIT_AUTOMAKE(mono,2.8.1)
AM_MAINTAINER_MODE
API_VER=2.0
+1
View File
@@ -18,6 +18,7 @@
<dllmap dll="libX11" target="@X11@" os="!windows" />
<dllmap dll="libcairo-2.dll" target="libcairo.so.2" os="!windows"/>
<dllmap dll="libcups" target="libcups.so.2" os="!windows"/>
<dllmap dll="libcups" target="libcups.dylib" os="osx"/>
<dllmap dll="i:kernel32.dll">
<dllentry dll="__Internal" name="CopyMemory" target="mono_win32_compat_CopyMemory"/>
<dllentry dll="__Internal" name="FillMemory" target="mono_win32_compat_FillMemory"/>
+2 -3
View File
@@ -14,9 +14,8 @@ BREAKPOINT="G_STMT_START { raise (SIGTRAP); } G_STMT_END"
if test x$GCC = xyes; then
GNUC_UNUSED='__attribute__((__unused__))'
GNUC_NORETURN='__attribute__((__noreturn__))'
echo target_cpu=$target_cpu
case $target_cpu in
i*86) BREAKPOINT="G_STMT_START { __asm__ (\"int \$03\"); } G_STMT_END" ;;
i*86|x86_64) BREAKPOINT="G_STMT_START { __asm__ (\"int \$03\"); } G_STMT_END" ;;
esac
fi
AC_SUBST(GNUC_PRETTY)
@@ -110,7 +109,7 @@ if test "x$have_iso_varargs" = "xyes"; then
fi
AC_SUBST(G_HAVE_ISO_VARARGS)
AC_CHECK_HEADERS(getopt.h sys/time.h sys/wait.h pwd.h langinfo.h iconv.h)
AC_CHECK_HEADERS(getopt.h sys/time.h sys/wait.h pwd.h langinfo.h iconv.h localcharset.h)
if test $ac_cv_sizeof_void_p != $ac_cv_sizeof_int; then
GPOINTER_TO_INT="((gint)(long) (ptr))"
+10 -3
View File
@@ -53,6 +53,9 @@
# ifdef HAVE_ICONV_H
# include <iconv.h>
# endif
# ifdef HAVE_LOCALCHARSET_H
# include <localcharset.h>
# endif
#endif
static char *my_charset;
@@ -217,8 +220,10 @@ g_convert (const gchar *str, gssize len,
convertor = iconv_open (to_codeset, from_codeset);
if (convertor == (iconv_t) -1){
*bytes_written = 0;
*bytes_read = 0;
if (bytes_written)
*bytes_written = 0;
if (bytes_read)
*bytes_read = 0;
return NULL;
}
@@ -303,7 +308,9 @@ g_get_charset (G_CONST_RETURN char **charset)
#else
if (my_charset == NULL){
/* These shouldn't be heap allocated */
#if HAVE_LANGINFO_H
#if HAVE_LOCALCHARSET_H
my_charset = locale_charset ();
#elif defined(HAVE_LANGINFO_H)
my_charset = nl_langinfo (CODESET);
#else
my_charset = "UTF-8";
+8 -1
View File
@@ -74,8 +74,11 @@ utf8_to_utf16_len (const gchar *str, glong len, glong *items_read, GError **erro
for (in_pos = 0; in_pos < len && str [in_pos] < 0x80; in_pos++)
ret ++;
if (in_pos == len)
if (in_pos == len) {
if (items_read)
*items_read = in_pos;
return ret;
}
mb_size = 0;
mb_remain = 0;
@@ -214,6 +217,8 @@ g_utf8_to_utf16 (const gchar *str, glong len, glong *items_read, glong *items_wr
if (len < 0)
len = strlen (str);
if (items_read)
*items_read = 0;
if (items_written)
*items_written = 0;
utf16_len = utf8_to_utf16_len (str, len, items_read, error);
@@ -311,6 +316,8 @@ g_utf16_to_utf8 (const gunichar2 *str, glong len, glong *items_read, glong *item
out_pos = 0;
surrogate = FALSE;
if (items_read)
*items_read = 0;
if (items_written)
*items_written = 0;
utf8_len = utf16_to_utf8_len (str, len, items_read, error);
+2 -1
View File
@@ -1341,7 +1341,8 @@ void * GC_start_routine_head(void * arg, void *base_addr,
if (start) *start = si -> start_routine;
if (start_arg) *start_arg = si -> arg;
sem_post(&(si -> registered)); /* Last action on si. */
if (!(si->flags & FOREIGN_THREAD))
sem_post(&(si -> registered)); /* Last action on si. */
/* OK to deallocate. */
# if defined(THREAD_LOCAL_ALLOC) && !defined(DBG_HDRS_ALL)
LOCK();
+7
View File
@@ -220,6 +220,13 @@ Specifies the diagnostics log level for
.Sp
Used to specify the file where the log will be stored, it defaults to
standard output.
.TP
.I server=[y/n]
Defaults to no, with the default option Mono will actively connect to the
host/port configured with the \fBaddress\fR option. If you set it to 'y', it
instructs the Mono runtime to start debugging in server mode, where Mono
actively waits for the debugger front end to connect to the Mono process.
Mono will print out to stdout the IP address and port where it is listening.
.ne
.RE
.TP
@@ -37,24 +37,14 @@ using System.Diagnostics;
[assembly: AssemblyDelaySign (true)]
[assembly: AssemblyKeyFile("../ecma.pub")]
#if NET_2_0
[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
[assembly: Debuggable (DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: CompilationRelaxations (CompilationRelaxations.NoStringInterning)]
[assembly: Dependency ("System.Drawing,", LoadHint.Always)]
[assembly: Dependency ("System,", LoadHint.Always)]
[assembly: StringFreezing]
[assembly: ComCompatibleVersion (1, 0, 3300, 0)]
#elif NET_1_1
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: ComCompatibleVersion (1, 0, 3300, 0)]
[assembly: TypeLibVersion (1, 10)]
#elif NET_1_0
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyConfiguration ("")]
#endif
[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
[assembly: Debuggable (DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: CompilationRelaxations (CompilationRelaxations.NoStringInterning)]
[assembly: Dependency ("System.Drawing,", LoadHint.Always)]
[assembly: Dependency ("System,", LoadHint.Always)]
[assembly: StringFreezing]
[assembly: ComCompatibleVersion (1, 0, 3300, 0)]
[assembly: InternalsVisibleTo("UIAutomationWinforms, PublicKey=00240000048000009400000006020000002400005253413100040000110000004bb98b1af6c1df0df8c02c380e116b7a7f0c8c827aecfccddc6e29b7c754cd608b49dfcef4df9699ad182e50f66afa4e68dabc7b6aeeec0aa4719a5f8e0aae8c193080a706adc3443a8356b1f254142034995532ac176398e12a30f6a74a119a89ac47672c9ae24d7e90de686557166e3b873cd707884431a0451d9d6f7fe795")]
[assembly: InternalsVisibleTo("Mono.WinformsSupport, PublicKey=00240000048000009400000006020000002400005253413100040000110000004bb98b1af6c1df0df8c02c380e116b7a7f0c8c827aecfccddc6e29b7c754cd608b49dfcef4df9699ad182e50f66afa4e68dabc7b6aeeec0aa4719a5f8e0aae8c193080a706adc3443a8356b1f254142034995532ac176398e12a30f6a74a119a89ac47672c9ae24d7e90de686557166e3b873cd707884431a0451d9d6f7fe795")]
#if NET_2_0
[assembly: InternalsVisibleTo("UIAutomationWinforms, PublicKey=00240000048000009400000006020000002400005253413100040000110000004bb98b1af6c1df0df8c02c380e116b7a7f0c8c827aecfccddc6e29b7c754cd608b49dfcef4df9699ad182e50f66afa4e68dabc7b6aeeec0aa4719a5f8e0aae8c193080a706adc3443a8356b1f254142034995532ac176398e12a30f6a74a119a89ac47672c9ae24d7e90de686557166e3b873cd707884431a0451d9d6f7fe795")]
#endif
@@ -30,9 +30,19 @@ using System;
using System.Drawing;
using System.Runtime.InteropServices;
namespace System.Windows.Forms {
#if PUBLIC_TYPES
namespace Mono.Winforms
#else
namespace System.Windows.Forms
#endif
{
[Flags]
internal enum WindowStyles : int {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum WindowStyles : int {
WS_OVERLAPPED = 0x00000000,
WS_POPUP = unchecked((int)0x80000000),
WS_CHILD = 0x40000000,
@@ -63,7 +73,12 @@ namespace System.Windows.Forms {
}
[Flags]
internal enum WindowExStyles : int {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum WindowExStyles : int {
// Extended Styles
WS_EX_DLGMODALFRAME = 0x00000001,
WS_EX_DRAGDETECT = 0x00000002,
@@ -99,14 +114,24 @@ namespace System.Windows.Forms {
}
[Flags]
internal enum ToolBarStyles : int {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum ToolBarStyles : int {
TBSTYLE_TOOLTIPS = 0x100,
TBSTYLE_FLAT = 0x800,
TBSTYLE_LIST = 0x1000,
TBSTYLE_TRANSPARENT = 0x8000
}
internal enum Msg {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum Msg {
WM_NULL = 0x0000,
WM_CREATE = 0x0001,
WM_DESTROY = 0x0002,
@@ -358,7 +383,12 @@ namespace System.Windows.Forms {
NIN_BALLOONUSERCLICK = WM_USER + 0x0005
}
internal enum MsgButtons {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum MsgButtons {
MK_LBUTTON = 0x0001,
MK_RBUTTON = 0x0002,
MK_SHIFT = 0x0004,
@@ -367,8 +397,13 @@ namespace System.Windows.Forms {
MK_XBUTTON1 = 0x0020,
MK_XBUTTON2 = 0x0040,
}
internal enum MsgUIState {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum MsgUIState {
UIS_SET = 1,
UIS_CLEAR = 2,
UIS_INITIALIZE = 3,
@@ -378,17 +413,22 @@ namespace System.Windows.Forms {
}
[StructLayout(LayoutKind.Sequential)]
internal struct POINT {
internal int x;
internal int y;
#if PUBLIC_TYPES
public
#else
internal
#endif
struct POINT {
public int x;
public int y;
internal POINT (int x, int y)
public POINT (int x, int y)
{
this.x = x;
this.y = y;
}
internal Point ToPoint ()
public Point ToPoint ()
{
return new Point (x, y);
}
@@ -400,7 +440,12 @@ namespace System.Windows.Forms {
}
[StructLayout(LayoutKind.Sequential)]
internal struct MSG {
#if PUBLIC_TYPES
public
#else
internal
#endif
struct MSG {
internal IntPtr hwnd;
internal Msg message;
internal IntPtr wParam;
@@ -416,26 +461,46 @@ namespace System.Windows.Forms {
}
[Flags]
internal enum TransparencySupport {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum TransparencySupport {
None = 0x00,
Get = 0x01,
Set = 0x02,
GetSet = 0x03
}
internal enum WindowActiveFlags {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum WindowActiveFlags {
WA_INACTIVE = 0,
WA_ACTIVE = 1,
WA_CLICKACTIVE = 2
}
internal enum KeybdEventFlags {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum KeybdEventFlags {
None = 0,
ExtendedKey = 0x0001,
KeyUp = 0x0002
}
internal enum VirtualKeys {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum VirtualKeys {
VK_LBUTTON = 0x01,
VK_RBUTTON = 0x02,
VK_CANCEL = 0x03,
@@ -590,7 +655,12 @@ namespace System.Windows.Forms {
VK_OEM_CLEAR = 0xFE,
}
internal enum TtyKeys {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum TtyKeys {
XK_BackSpace = 0xff08, /* Back space, back char */
XK_Tab = 0xff09,
XK_Linefeed = 0xff0a, /* Linefeed, LF */
@@ -603,7 +673,12 @@ namespace System.Windows.Forms {
XK_Delete = 0xffff /* Delete, rubout */
}
internal enum MiscKeys {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum MiscKeys {
XK_ISO_Lock = 0xfe01,
XK_ISO_Last_Group_Lock = 0xfe0f,
XK_Select = 0xff60,
@@ -622,7 +697,12 @@ namespace System.Windows.Forms {
XK_Num_Lock = 0xff7f
}
internal enum KeypadKeys {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum KeypadKeys {
XK_KP_Space = 0xff80,
XK_KP_Tab = 0xff89,
XK_KP_Enter = 0xff8d, /* Enter */
@@ -663,7 +743,12 @@ namespace System.Windows.Forms {
XK_KP_9 = 0xffb9
}
internal enum DeadKeys {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum DeadKeys {
XK_dead_grave = 0xfe50,
XK_dead_acute = 0xfe51,
XK_dead_circumflex = 0xfe52,
@@ -687,7 +772,12 @@ namespace System.Windows.Forms {
}
[StructLayout(LayoutKind.Sequential)]
internal struct HELPINFO {
#if PUBLIC_TYPES
public
#else
internal
#endif
struct HELPINFO {
internal uint cbSize;
internal int iContextType;
internal int iCtrlId;
@@ -696,13 +786,23 @@ namespace System.Windows.Forms {
internal POINT MousePos;
}
internal enum PeekMessageFlags {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum PeekMessageFlags {
PM_NOREMOVE = 0x00000000,
PM_REMOVE = 0x00000001,
PM_NOYIELD = 0x00000002
}
internal enum StdCursor {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum StdCursor {
Default = 0,
AppStarting = 1,
Arrow = 2,
@@ -733,7 +833,12 @@ namespace System.Windows.Forms {
WaitCursor = 27
}
internal enum HitTest {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum HitTest {
HTERROR = -2,
HTTRANSPARENT = -1,
HTNOWHERE = 0,
@@ -765,14 +870,24 @@ namespace System.Windows.Forms {
HTHELP = 21
}
internal enum TitleStyle {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum TitleStyle {
None = 0,
Normal = 1,
Tool = 2
}
[StructLayout(LayoutKind.Sequential)]
internal struct BITMAPINFOHEADER {
#if PUBLIC_TYPES
public
#else
internal
#endif
struct BITMAPINFOHEADER {
internal uint biSize;
internal int biWidth;
internal int biHeight;
@@ -786,7 +901,12 @@ namespace System.Windows.Forms {
internal uint biClrImportant;
}
internal enum ClipboardFormats : ushort {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum ClipboardFormats : ushort {
CF_TEXT = 1,
CF_BITMAP = 2,
CF_METAFILEPICT = 3,
@@ -807,7 +927,12 @@ namespace System.Windows.Forms {
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
internal struct MINMAXINFO {
#if PUBLIC_TYPES
public
#else
internal
#endif
struct MINMAXINFO {
internal POINT ptReserved;
internal POINT ptMaxSize;
internal POINT ptMaxPosition;
@@ -816,7 +941,12 @@ namespace System.Windows.Forms {
}
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
internal struct KeyFilterData {
#if PUBLIC_TYPES
public
#else
internal
#endif
struct KeyFilterData {
internal bool Down;
internal int keycode;
internal int keysym;
@@ -824,7 +954,12 @@ namespace System.Windows.Forms {
internal String str;
}
internal enum ScrollBarCommands {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum ScrollBarCommands {
SB_LINEUP = 0,
SB_LINELEFT = 0,
SB_LINEDOWN = 1,
@@ -842,7 +977,12 @@ namespace System.Windows.Forms {
SB_ENDSCROLL = 8
}
internal enum ClipCombineMode {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum ClipCombineMode {
RGN_AND = 1,
RGN_OR,
RGN_XOR,
@@ -853,7 +993,12 @@ namespace System.Windows.Forms {
RGN_MAX = RGN_COPY
}
internal enum SystemCommands {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum SystemCommands {
SC_SIZE = 0xF000,
SC_MOVE = 0xF010,
SC_MINIMIZE = 0xF020,
@@ -875,7 +1020,12 @@ namespace System.Windows.Forms {
SC_CONTEXTHELP = 0xF180
}
internal enum AlertType {
#if PUBLIC_TYPES
public
#else
internal
#endif
enum AlertType {
Default = 1,
Error = 2,
Question = 3,
@@ -84,36 +84,38 @@ namespace Microsoft.Build.BuildEngine {
[MonoTODO]
public bool Execute ()
{
bool result;
bool result = false;
TaskEngine taskEngine;
LogTaskStarted ();
ITask task = null;
try {
task = InitializeTask ();
} catch (Exception e) {
LogError ("Error initializing task {0}: {1}", taskElement.LocalName, e.Message);
LogMessage (MessageImportance.Low, "Error initializing task {0}: {1}",
taskElement.LocalName, e.ToString ());
return false;
try {
task = InitializeTask ();
} catch (Exception e) {
LogError ("Error initializing task {0}: {1}", taskElement.LocalName, e.Message);
LogMessage (MessageImportance.Low, "Error initializing task {0}: {1}",
taskElement.LocalName, e.ToString ());
return false;
}
try {
taskEngine = new TaskEngine (parentTarget.Project);
taskEngine.Prepare (task, this.taskElement, GetParameters (), this.Type);
result = taskEngine.Execute ();
if (result)
taskEngine.PublishOutput ();
} catch (Exception e) {
task_logger.LogError ("Error executing task {0}: {1}", taskElement.LocalName, e.Message);
task_logger.LogMessage (MessageImportance.Low,
"Error executing task {0}: {1}", taskElement.LocalName, e.ToString ());
result = false;
}
} finally {
LogTaskFinished (result);
}
try {
taskEngine = new TaskEngine (parentTarget.Project);
taskEngine.Prepare (task, this.taskElement, GetParameters (), this.Type);
result = taskEngine.Execute ();
if (result)
taskEngine.PublishOutput ();
} catch (Exception e) {
task_logger.LogError ("Error executing task {0}: {1}", taskElement.LocalName, e.Message);
task_logger.LogMessage (MessageImportance.Low,
"Error executing task {0}: {1}", taskElement.LocalName, e.ToString ());
result = false;
}
LogTaskFinished (result);
return result;
}
@@ -59,7 +59,7 @@ namespace Microsoft.Build.BuildEngine {
bool no_message_color, use_colors;
bool noItemAndPropertyList;
List<BuildStatusEventArgs> events;
List<BuildEvent> events;
Dictionary<string, List<string>> errorsTable;
Dictionary<string, List<string>> warningsTable;
SortedDictionary<string, PerfInfo> targetPerfTable, tasksPerfTable;
@@ -96,7 +96,7 @@ namespace Microsoft.Build.BuildEngine {
this.colorSet = colorSet;
this.colorReset = colorReset;
events = new List<BuildStatusEventArgs> ();
events = new List<BuildEvent> ();
errorsTable = new Dictionary<string, List<string>> ();
warningsTable = new Dictionary<string, List<string>> ();
targetPerfTable = new SortedDictionary<string, PerfInfo> ();
@@ -205,19 +205,23 @@ namespace Microsoft.Build.BuildEngine {
{
this.eventSource = eventSource;
eventSource.BuildStarted += new BuildStartedEventHandler (BuildStartedHandler);
eventSource.BuildFinished += new BuildFinishedEventHandler (BuildFinishedHandler);
eventSource.ProjectStarted += new ProjectStartedEventHandler (ProjectStartedHandler);
eventSource.ProjectFinished += new ProjectFinishedEventHandler (ProjectFinishedHandler);
eventSource.TargetStarted += new TargetStartedEventHandler (TargetStartedHandler);
eventSource.TargetFinished += new TargetFinishedEventHandler (TargetFinishedHandler);
eventSource.TaskStarted += new TaskStartedEventHandler (TaskStartedHandler);
eventSource.TaskFinished += new TaskFinishedEventHandler (TaskFinishedHandler);
eventSource.MessageRaised += new BuildMessageEventHandler (MessageHandler);
eventSource.WarningRaised += new BuildWarningEventHandler (WarningHandler);
eventSource.ErrorRaised += new BuildErrorEventHandler (ErrorHandler);
eventSource.BuildStarted += BuildStartedHandler;
eventSource.BuildFinished += BuildFinishedHandler;
eventSource.ProjectStarted += PushEvent;
eventSource.ProjectFinished += PopEvent;
eventSource.TargetStarted += PushEvent;
eventSource.TargetFinished += PopEvent;
eventSource.TaskStarted += PushEvent;
eventSource.TaskFinished += PopEvent;
eventSource.MessageRaised += MessageHandler;
eventSource.WarningRaised += WarningHandler;
eventSource.ErrorRaised += ErrorHandler;
}
public void BuildStartedHandler (object sender, BuildStartedEventArgs args)
{
if (IsVerbosityGreaterOrEqual (LoggerVerbosity.Normal)) {
@@ -231,9 +235,28 @@ namespace Microsoft.Build.BuildEngine {
}
public void BuildFinishedHandler (object sender, BuildFinishedEventArgs args)
{
BuildFinishedHandlerActual (args);
// Reset
events.Clear ();
errorsTable.Clear ();
warningsTable.Clear ();
targetPerfTable.Clear ();
tasksPerfTable.Clear ();
errors.Clear ();
warnings.Clear ();
indent = 0;
errorCount = 0;
warningCount = 0;
projectFailed = false;
}
void BuildFinishedHandlerActual (BuildFinishedEventArgs args)
{
if (!IsVerbosityGreaterOrEqual (LoggerVerbosity.Normal)) {
PopEvent ();
PopEvent (args);
return;
}
@@ -288,8 +311,9 @@ namespace Microsoft.Build.BuildEngine {
WriteLine (String.Format ("\t {0} Error(s)", errorCount));
WriteLine (String.Empty);
WriteLine (String.Format ("Time Elapsed {0}", timeElapsed));
}
PopEvent ();
}
PopEvent (args);
}
public void ProjectStartedHandler (object sender, ProjectStartedEventArgs args)
@@ -299,11 +323,9 @@ namespace Microsoft.Build.BuildEngine {
WriteLine (String.Format ("Project \"{0}\" ({1} target(s)):", args.ProjectFile,
String.IsNullOrEmpty (args.TargetNames) ? "default" : args.TargetNames));
ResetColor ();
WriteLine (String.Empty);
DumpProperties (args.Properties);
DumpItems (args.Items);
}
PushEvent (args);
}
public void ProjectFinishedHandler (object sender, ProjectFinishedEventArgs args)
@@ -320,8 +342,6 @@ namespace Microsoft.Build.BuildEngine {
if (!projectFailed)
// no project has failed yet, so update the flag
projectFailed = !args.Succeeded;
PopEvent ();
}
public void TargetStartedHandler (object sender, TargetStartedEventArgs args)
@@ -329,10 +349,10 @@ namespace Microsoft.Build.BuildEngine {
if (IsVerbosityGreaterOrEqual (LoggerVerbosity.Normal)) {
indent++;
SetColor (eventColor);
WriteLine (String.Empty);
WriteLine (String.Format ("Target {0}:",args.TargetName));
ResetColor ();
}
PushEvent (args);
}
public void TargetFinishedHandler (object sender, TargetFinishedEventArgs args)
@@ -347,19 +367,16 @@ namespace Microsoft.Build.BuildEngine {
WriteLine (String.Empty);
}
indent--;
PopEvent ();
}
public void TaskStartedHandler (object sender, TaskStartedEventArgs args)
{
if (this.verbosity == LoggerVerbosity.Detailed) {
if (IsVerbosityGreaterOrEqual (LoggerVerbosity.Detailed)) {
SetColor (eventColor);
WriteLine (String.Format ("Task \"{0}\"",args.TaskName));
ResetColor ();
}
indent++;
PushEvent (args);
}
public void TaskFinishedHandler (object sender, TaskFinishedEventArgs args)
@@ -374,15 +391,16 @@ namespace Microsoft.Build.BuildEngine {
WriteLine (String.Format ("Task \"{0}\" execution -- FAILED", args.TaskName));
ResetColor ();
}
PopEvent ();
}
public void MessageHandler (object sender, BuildMessageEventArgs args)
{
if (IsMessageOk (args)) {
if (no_message_color) {
ExecutePendingEventHandlers ();
WriteLine (args.Message);
} else {
ExecutePendingEventHandlers ();
SetColor (args.Importance == MessageImportance.High ? highMessageColor : messageColor);
WriteLine (args.Message);
ResetColor ();
@@ -394,6 +412,7 @@ namespace Microsoft.Build.BuildEngine {
{
string msg = FormatWarningEvent (args);
if (IsVerbosityGreaterOrEqual (LoggerVerbosity.Quiet)) {
ExecutePendingEventHandlers ();
SetColor (warningColor);
WriteLineWithoutIndent (msg);
ResetColor ();
@@ -412,6 +431,7 @@ namespace Microsoft.Build.BuildEngine {
{
string msg = FormatErrorEvent (args);
if (IsVerbosityGreaterOrEqual (LoggerVerbosity.Quiet)) {
ExecutePendingEventHandlers ();
SetColor (errorColor);
WriteLineWithoutIndent (msg);
ResetColor ();
@@ -444,16 +464,36 @@ namespace Microsoft.Build.BuildEngine {
}
}
void PushEvent (BuildStatusEventArgs args)
void PushEvent<T> (object sender, T args) where T: BuildStatusEventArgs
{
events.Add (args);
PushEvent (args);
}
void PushEvent<T> (T args) where T: BuildStatusEventArgs
{
BuildEvent be = new BuildEvent {
EventArgs = args,
StartHandlerHasExecuted = false,
ConsoleLogger = this
};
events.Add (be);
current_events_string = null;
}
void PopEvent ()
void PopEvent<T> (object sender, T finished_args) where T: BuildStatusEventArgs
{
PopEvent (finished_args);
}
void PopEvent<T> (T finished_args) where T: BuildStatusEventArgs
{
if (events.Count == 0)
throw new InvalidOperationException ("INTERNAL ERROR: Trying to pop from an empty events stack");
BuildEvent be = events [events.Count - 1];
if (performanceSummary || verbosity == LoggerVerbosity.Diagnostic) {
var args = events [events.Count - 1];
var args = be.EventArgs;
TargetStartedEventArgs tgt_args = args as TargetStartedEventArgs;
if (tgt_args != null) {
AddPerfInfo (tgt_args.TargetName, args.Timestamp, targetPerfTable);
@@ -464,17 +504,24 @@ namespace Microsoft.Build.BuildEngine {
}
}
be.ExecuteFinishedHandler (finished_args);
events.RemoveAt (events.Count - 1);
current_events_string = null;
}
void ExecutePendingEventHandlers ()
{
foreach (var be in events)
be.ExecuteStartedHandler ();
}
string EventsToString ()
{
StringBuilder sb = new StringBuilder ();
string last_imported_target_file = String.Empty;
for (int i = 0; i < events.Count; i ++) {
var args = events [i];
var args = events [i].EventArgs;
ProjectStartedEventArgs pargs = args as ProjectStartedEventArgs;
if (pargs != null) {
sb.AppendFormat ("{0} ({1}) ->\n", pargs.ProjectFile,
@@ -580,14 +627,18 @@ namespace Microsoft.Build.BuildEngine {
if (eventSource == null)
return;
eventSource.BuildStarted -= BuildStartedHandler;
eventSource.BuildStarted -= BuildStartedHandler;
eventSource.BuildFinished -= BuildFinishedHandler;
eventSource.ProjectStarted -= ProjectStartedHandler;
eventSource.ProjectFinished -= ProjectFinishedHandler;
eventSource.TargetStarted -= TargetStartedHandler;
eventSource.TargetFinished -= TargetFinishedHandler;
eventSource.TaskStarted -= TaskStartedHandler;
eventSource.TaskFinished -= TaskFinishedHandler;
eventSource.ProjectStarted -= PushEvent;
eventSource.ProjectFinished -= PopEvent;
eventSource.TargetStarted -= PushEvent;
eventSource.TargetFinished -= PopEvent;
eventSource.TaskStarted -= PushEvent;
eventSource.TaskFinished -= PopEvent;
eventSource.MessageRaised -= MessageHandler;
eventSource.WarningRaised -= WarningHandler;
eventSource.ErrorRaised -= ErrorHandler;
@@ -673,7 +724,7 @@ namespace Microsoft.Build.BuildEngine {
return;
SetColor (eventColor);
WriteLine ("\n");
WriteLine (String.Empty);
WriteLine ("Initial Properties:");
ResetColor ();
@@ -686,7 +737,6 @@ namespace Microsoft.Build.BuildEngine {
foreach (KeyValuePair<string, string> pair in dict)
WriteLine (String.Format ("{0} = {1}", pair.Key, pair.Value));
WriteLine ("\n");
}
void DumpItems (IEnumerable items)
@@ -695,7 +745,7 @@ namespace Microsoft.Build.BuildEngine {
return;
SetColor (eventColor);
WriteLine ("\n");
WriteLine (String.Empty);
WriteLine ("Initial Items:");
ResetColor ();
if (items == null)
@@ -717,7 +767,6 @@ namespace Microsoft.Build.BuildEngine {
WriteLine (item.ItemSpec);
indent--;
}
WriteLine ("\n");
}
public string Parameters {
@@ -762,6 +811,44 @@ namespace Microsoft.Build.BuildEngine {
}
}
class BuildEvent {
public BuildStatusEventArgs EventArgs;
public bool StartHandlerHasExecuted;
public ConsoleLogger ConsoleLogger;
public void ExecuteStartedHandler ()
{
if (StartHandlerHasExecuted)
return;
if (EventArgs is ProjectStartedEventArgs)
ConsoleLogger.ProjectStartedHandler (null, (ProjectStartedEventArgs)EventArgs);
else if (EventArgs is TargetStartedEventArgs)
ConsoleLogger.TargetStartedHandler (null, (TargetStartedEventArgs)EventArgs);
else if (EventArgs is TaskStartedEventArgs)
ConsoleLogger.TaskStartedHandler (null, (TaskStartedEventArgs)EventArgs);
else if (!(EventArgs is BuildStartedEventArgs))
throw new InvalidOperationException ("Unexpected event on the stack, type: " + EventArgs.GetType ());
StartHandlerHasExecuted = true;
}
public void ExecuteFinishedHandler (BuildStatusEventArgs finished_args)
{
if (!StartHandlerHasExecuted)
return;
if (EventArgs is ProjectStartedEventArgs)
ConsoleLogger.ProjectFinishedHandler (null, finished_args as ProjectFinishedEventArgs);
else if (EventArgs is TargetStartedEventArgs)
ConsoleLogger.TargetFinishedHandler (null, finished_args as TargetFinishedEventArgs);
else if (EventArgs is TaskStartedEventArgs)
ConsoleLogger.TaskFinishedHandler (null, finished_args as TaskFinishedEventArgs);
else if (!(EventArgs is BuildStartedEventArgs))
throw new InvalidOperationException ("Unexpected event on the stack, type: " + EventArgs.GetType ());
}
}
class PerfInfo {
public TimeSpan Time;
public int NumberOfCalls;
@@ -126,6 +126,7 @@ namespace Microsoft.Build.BuildEngine {
{
if (project == null)
throw new ArgumentException ("project");
builtTargetsOutputByName.Clear ();
return project.Build ();
}
@@ -164,6 +165,9 @@ namespace Microsoft.Build.BuildEngine {
if (targetNames == null)
return false;
if ((buildFlags & BuildSettings.DoNotResetPreviouslyBuiltTargets) != BuildSettings.DoNotResetPreviouslyBuiltTargets)
builtTargetsOutputByName.Clear ();
if (defaultToolsVersion != null)
// it has been explicitly set, xbuild does this..
project.ToolsVersion = defaultToolsVersion;
@@ -224,6 +228,9 @@ namespace Microsoft.Build.BuildEngine {
IDictionary targetOutputs,
BuildSettings buildFlags, string toolsVersion)
{
if ((buildFlags & BuildSettings.DoNotResetPreviouslyBuiltTargets) != BuildSettings.DoNotResetPreviouslyBuiltTargets)
builtTargetsOutputByName.Clear ();
Project project;
bool newProject = false;
@@ -241,8 +241,10 @@ namespace Microsoft.Build.BuildEngine {
void LogTargetSkipped (Target target, string reason)
{
BuildMessageEventArgs bmea;
bmea = new BuildMessageEventArgs (reason ?? String.Format ("Skipping target \"{0}\" because its outputs are up-to-date.", target.Name),
null, "MSBuild", MessageImportance.Normal);
bmea = new BuildMessageEventArgs (String.IsNullOrEmpty (reason)
? String.Format ("Skipping target \"{0}\" because its outputs are up-to-date.", target.Name)
: reason,
null, "MSBuild", MessageImportance.Normal);
target.Engine.EventSource.FireMessageRaised (this, bmea);
}
@@ -5,8 +5,11 @@
// Marek Sieradzki ([email protected])
// Paolo Molaro ([email protected])
// Gonzalo Paniagua Javier ([email protected])
// Lluis Sanchez Gual <[email protected]>
// Ankit Jain <[email protected]>
//
// (C) 2005 Marek Sieradzki
// Copyright 2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -36,6 +39,7 @@ using System.Collections;
using System.Collections.Generic;
using System.Resources;
using System.Reflection;
using System.Xml;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Mono.XBuild.Tasks.GenerateResourceInternal;
@@ -73,7 +77,8 @@ namespace Microsoft.Build.Tasks {
string sourceFile = source.ItemSpec;
string outputFile = Path.ChangeExtension (sourceFile, "resources");
result &= CompileResourceFile (sourceFile, outputFile);
if (IsResgenRequired (sourceFile, outputFile))
result &= CompileResourceFile (sourceFile, outputFile);
ITaskItem newItem = new TaskItem (source);
source.ItemSpec = outputFile;
@@ -93,7 +98,8 @@ namespace Microsoft.Build.Tasks {
continue;
}
result &= CompileResourceFile (sources [i].ItemSpec, outputResources [i].ItemSpec);
if (IsResgenRequired (sources [i].ItemSpec, outputResources [i].ItemSpec))
result &= CompileResourceFile (sources [i].ItemSpec, outputResources [i].ItemSpec);
temporaryFilesWritten.Add (outputResources [i]);
}
}
@@ -103,6 +109,78 @@ namespace Microsoft.Build.Tasks {
return result;
}
// true if the resx file or any file referenced
// by the resx is newer than the .resources file
//
// Code taken from monodevelop
// main/src/core/MonoDevelop.Core/MonoDevelop.Projects.Formats.MD1/MD1DotNetProjectHandler.cs
bool IsResgenRequired (string resx_filename, string resources_filename)
{
if (IsFileNewerThan (resx_filename, resources_filename)) {
Log.LogMessage (MessageImportance.Low,
"Resource file '{0}' is newer than the source file '{1}', skipping.",
resources_filename, resx_filename);
return true;
}
if (String.Compare (Path.GetExtension (resx_filename), ".resx", true) != 0)
return true;
// resx file, check for files referenced from there
XmlTextReader xr = null;
try {
// look for
// <data type="System.Resources.ResXFileRef, System.Windows.Forms" ..>
// <value>... filename;.. </value>
// </data>
xr = new XmlTextReader (resx_filename);
string basepath = Path.GetDirectoryName (resx_filename);
while (xr.Read ()) {
if (xr.NodeType != XmlNodeType.Element ||
String.Compare (xr.LocalName, "data") != 0)
continue;
string type = xr.GetAttribute ("type");
if (String.IsNullOrEmpty (type))
continue;
if (String.Compare (type, "System.Resources.ResXFileRef, System.Windows.Forms") != 0)
continue;
xr.ReadToDescendant ("value");
if (xr.NodeType != XmlNodeType.Element)
continue;
string value = xr.ReadElementContentAsString ();
string [] parts = value.Split (';');
if (parts.Length > 0) {
string referenced_filename = Utilities.FromMSBuildPath (
Path.Combine (basepath, parts [0]).Trim ());
if (File.Exists (referenced_filename) &&
IsFileNewerThan (referenced_filename, resources_filename))
return true;
}
}
} catch (XmlException) {
// Ignore xml errors, let resgen handle it
return true;
} finally {
if (xr != null)
xr.Close ();
}
return false;
}
// true if first is newer than second
static bool IsFileNewerThan (string first, string second)
{
FileInfo finfo_first = new FileInfo (first);
FileInfo finfo_second = new FileInfo (second);
return finfo_first.LastWriteTime > finfo_second.LastWriteTime;
}
#if false
private IResourceReader GetReader (Stream stream, string name)
{
@@ -154,13 +232,6 @@ namespace Microsoft.Build.Tasks {
return false;
}
if (File.GetLastWriteTime (sname) <= File.GetLastWriteTime (dname)) {
Log.LogMessage (MessageImportance.Low,
"Resource file '{0}' is newer than the source file '{1}', skipping.",
dname, sname);
return true;
}
Resgen resgen = new Resgen ();
resgen.BuildEngine = this.BuildEngine;
resgen.UseSourcePath = true;
@@ -298,7 +369,7 @@ namespace Microsoft.Build.Tasks {
public override bool Execute ()
{
if (String.IsNullOrEmpty (Environment.GetEnvironmentVariable ("MONO_IOMAP")))
EnvironmentOverride ["MONO_IOMAP"] = "drive";
EnvironmentVariables = new string [] { "MONO_IOMAP=drive" };
return base.Execute ();
}
@@ -28,6 +28,7 @@
#if NET_2_0
using System;
using System.IO;
namespace Microsoft.Build.Tasks {
internal static class Utilities {
@@ -42,6 +43,68 @@ namespace Microsoft.Build.Tasks {
}
}
internal static string FromMSBuildPath (string relPath)
{
if (relPath == null || relPath.Length == 0)
return null;
bool is_windows = Path.DirectorySeparatorChar == '\\';
string path = relPath;
if (!is_windows)
path = path.Replace ("\\", "/");
// a path with drive letter is invalid/unusable on non-windows
if (!is_windows && char.IsLetter (path [0]) && path.Length > 1 && path[1] == ':')
return null;
if (System.IO.File.Exists (path)){
return Path.GetFullPath (path);
}
if (Path.IsPathRooted (path)) {
// Windows paths are case-insensitive. When mapping an absolute path
// we can try to find the correct case for the path.
string[] names = path.Substring (1).Split ('/');
string part = "/";
for (int n=0; n<names.Length; n++) {
string[] entries;
if (names [n] == ".."){
if (part == "/")
return ""; // Can go further back. It's not an existing file
part = Path.GetFullPath (part + "/..");
continue;
}
entries = Directory.GetFileSystemEntries (part);
string fpath = null;
foreach (string e in entries) {
if (string.Compare (Path.GetFileName (e), names[n], true) == 0) {
fpath = e;
break;
}
}
if (fpath == null) {
// Part of the path does not exist. Can't do any more checking.
part = Path.GetFullPath (part);
for (; n < names.Length; n++)
part += "/" + names[n];
return part;
}
part = fpath;
}
return Path.GetFullPath (part);
} else {
return Path.GetFullPath (path);
}
}
}
}
@@ -46,7 +46,6 @@ namespace Microsoft.Build.Utilities
{
public abstract class ToolTask : Task
{
SCS.ProcessStringDictionary environmentOverride;
int exitCode;
int timeout;
string toolPath, toolExe;
@@ -76,7 +75,6 @@ namespace Microsoft.Build.Utilities
this.toolPath = MonoLocationHelper.GetBinDir ();
this.responseFileEncoding = Encoding.UTF8;
this.timeout = Int32.MaxValue;
this.environmentOverride = new SCS.ProcessStringDictionary ();
}
[MonoTODO]
@@ -111,11 +109,8 @@ namespace Microsoft.Build.Utilities
if (pathToTool == null)
throw new ArgumentNullException ("pathToTool");
string output, error, responseFileName;
StreamWriter outwr, errwr;
outwr = errwr = null;
responseFileName = output = error = null;
string responseFileName;
responseFileName = null;
toolOutput = new StringBuilder ();
try {
@@ -129,11 +124,6 @@ namespace Microsoft.Build.Utilities
LogToolCommand (String.Format ("Tool {0} execution started with arguments: {1} {2}",
pathToTool, commandLineCommands, responseFileCommands));
output = Path.GetTempFileName ();
error = Path.GetTempFileName ();
outwr = new StreamWriter (output);
errwr = new StreamWriter (error);
ProcessStartInfo pinfo = new ProcessStartInfo (pathToTool, arguments);
pinfo.WorkingDirectory = GetWorkingDirectory () ?? Environment.CurrentDirectory;
@@ -141,15 +131,27 @@ namespace Microsoft.Build.Utilities
pinfo.RedirectStandardOutput = true;
pinfo.RedirectStandardError = true;
var pendingLineFragmentOutput = new StringBuilder ();
var pendingLineFragmentError = new StringBuilder ();
var environmentOverride = GetAndLogEnvironmentVariables ();
try {
ProcessWrapper pw = ProcessService.StartProcess (pinfo, outwr, errwr, null, environmentOverride);
pw.OutputStreamChanged += delegate (object o, string msg) { ProcessLine (msg, StandardOutputLoggingImportance); };
pw.ErrorStreamChanged += delegate (object o, string msg) { ProcessLine (msg, StandardErrorLoggingImportance); };
// When StartProcess returns, the process has already .Start()'ed
// If we subscribe to the events after that, then for processes that
// finish executing before we can subscribe, we won't get the output/err
// events at all!
ProcessWrapper pw = ProcessService.StartProcess (pinfo,
(_, msg) => ProcessLine (pendingLineFragmentOutput, msg, StandardOutputLoggingImportance),
(_, msg) => ProcessLine (pendingLineFragmentError, msg, StandardErrorLoggingImportance),
null,
environmentOverride);
pw.WaitForOutput (timeout == Int32.MaxValue ? Int32.MaxValue : timeout);
// Process any remaining line
ProcessLine (pendingLineFragmentOutput, StandardOutputLoggingImportance, true);
ProcessLine (pendingLineFragmentError, StandardErrorLoggingImportance, true);
pw.WaitForOutput (timeout == Int32.MaxValue ? -1 : timeout);
exitCode = pw.ExitCode;
outwr.Close();
errwr.Close();
pw.Dispose ();
} catch (System.ComponentModel.Win32Exception e) {
Log.LogError ("Error executing tool '{0}': {1}", pathToTool, e.Message);
@@ -159,17 +161,13 @@ namespace Microsoft.Build.Utilities
if (typeLoadException)
ProcessTypeLoadException ();
pendingLineFragmentOutput.Length = 0;
pendingLineFragmentError.Length = 0;
Log.LogMessage (MessageImportance.Low, "Tool {0} execution finished.", pathToTool);
return exitCode;
} finally {
DeleteTempFile (responseFileName);
if (outwr != null)
outwr.Dispose ();
if (errwr != null)
errwr.Dispose ();
DeleteTempFile (output);
DeleteTempFile (error);
}
}
@@ -192,9 +190,39 @@ namespace Microsoft.Build.Utilities
Log.LogError (output_str);
}
void ProcessLine (string line, MessageImportance importance)
void ProcessLine (StringBuilder outputBuilder, MessageImportance importance, bool isLastLine)
{
foreach (string singleLine in line.Split (new string [] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)) {
if (outputBuilder.Length == 0)
return;
if (isLastLine && !outputBuilder.ToString ().EndsWith (Environment.NewLine))
// last line, but w/o an trailing newline, so add that
outputBuilder.Append (Environment.NewLine);
ProcessLine (outputBuilder, null, importance);
}
void ProcessLine (StringBuilder outputBuilder, string line, MessageImportance importance)
{
// Add to any line fragment from previous call
if (line != null)
outputBuilder.Append (line);
// Don't remove empty lines!
var lines = outputBuilder.ToString ().Split (new string [] {Environment.NewLine}, StringSplitOptions.None);
// Clear the builder. If any incomplete line is found,
// then it will get added back
outputBuilder.Length = 0;
for (int i = 0; i < lines.Length; i ++) {
string singleLine = lines [i];
if (i == lines.Length - 1 && !singleLine.EndsWith (Environment.NewLine)) {
// Last line doesn't end in newline, could be part of
// a bigger line. Save for later processing
outputBuilder.Append (singleLine);
continue;
}
toolOutput.AppendLine (singleLine);
// in case of typeLoadException, collect all the output
@@ -206,9 +234,10 @@ namespace Microsoft.Build.Utilities
protected virtual void LogEventsFromTextOutput (string singleLine, MessageImportance importance)
{
singleLine = singleLine.Trim ();
if (singleLine.Length == 0)
if (singleLine.Length == 0) {
Log.LogMessage (singleLine, importance);
return;
}
if (singleLine.StartsWith ("Unhandled Exception: System.TypeLoadException") ||
singleLine.StartsWith ("Unhandled Exception: System.IO.FileNotFoundException")) {
@@ -319,11 +348,50 @@ namespace Microsoft.Build.Utilities
}
}
// If EnvironmentVariables is defined, then merge EnvironmentOverride
// EnvironmentOverride is Obsolete'd in 4.0
//
// Returns the final set of environment variables and logs them
SCS.StringDictionary GetAndLogEnvironmentVariables ()
{
var env_vars = GetEnvironmentVariables ();
if (env_vars == null)
return env_vars;
Log.LogMessage (MessageImportance.Low, "Environment variables being passed to the tool:");
foreach (DictionaryEntry entry in env_vars)
Log.LogMessage (MessageImportance.Low, "\t{0}={1}", (string)entry.Key, (string)entry.Value);
return env_vars;
}
SCS.StringDictionary GetEnvironmentVariables ()
{
if (EnvironmentVariables == null || EnvironmentVariables.Length == 0)
return EnvironmentOverride;
var env_vars = new SCS.ProcessStringDictionary ();
foreach (string pair in EnvironmentVariables) {
string [] key_value = pair.Split ('=');
if (!String.IsNullOrEmpty (key_value [0]))
env_vars [key_value [0]] = key_value.Length > 1 ? key_value [1] : String.Empty;
}
if (EnvironmentOverride != null)
foreach (DictionaryEntry entry in EnvironmentOverride)
env_vars [(string)entry.Key] = (string)entry.Value;
return env_vars;
}
protected virtual StringDictionary EnvironmentOverride
{
get { return environmentOverride; }
get { return null; }
}
// Ignore EnvironmentOverride if this is set
public string[] EnvironmentVariables { get; set; }
[Output]
public int ExitCode {
get { return exitCode; }
@@ -678,32 +678,48 @@ namespace Mono.Debugger.Soft
int offset;
public PacketWriter () {
// FIXME:
data = new byte [1024];
offset = 0;
}
void MakeRoom (int size) {
if (offset + size >= data.Length) {
int new_len = data.Length * 2;
while (new_len < offset + size) {
new_len *= 2;
}
byte[] new_data = new byte [new_len];
Array.Copy (data, new_data, data.Length);
data = new_data;
}
}
public PacketWriter WriteByte (byte val) {
MakeRoom (1);
encode_byte (data, val, ref offset);
return this;
}
public PacketWriter WriteInt (int val) {
MakeRoom (4);
encode_int (data, val, ref offset);
return this;
}
public PacketWriter WriteId (long id) {
MakeRoom (8);
encode_id (data, id, ref offset);
return this;
}
public PacketWriter WriteLong (long val) {
MakeRoom (8);
encode_long (data, val, ref offset);
return this;
}
public PacketWriter WriteFloat (float f) {
MakeRoom (8);
byte[] b = DataConverter.GetBytesBE (f);
for (int i = 0; i < 4; ++i)
data [offset + i] = b [i];
@@ -712,6 +728,7 @@ namespace Mono.Debugger.Soft
}
public PacketWriter WriteDouble (double d) {
MakeRoom (8);
byte[] b = DataConverter.GetBytesBE (d);
for (int i = 0; i < 8; ++i)
data [offset + i] = b [i];
@@ -734,6 +751,7 @@ namespace Mono.Debugger.Soft
public PacketWriter WriteString (string s) {
encode_int (data, s.Length, ref offset);
byte[] b = Encoding.UTF8.GetBytes (s);
MakeRoom (b.Length);
Buffer.BlockCopy (b, 0, data, offset, b.Length);
offset += b.Length;
return this;
+21 -2
View File
@@ -409,7 +409,7 @@ public class Tests : TestsBase
[MethodImplAttribute (MethodImplOptions.NoInlining)]
public static void locals () {
locals1 (null);
locals2 (null, 5);
locals2<string> (null, 5, "ABC");
locals3 ();
}
@@ -423,13 +423,15 @@ public class Tests : TestsBase
}
[MethodImplAttribute (MethodImplOptions.NoInlining)]
public static void locals2 (string[] args, int arg) {
public static void locals2<T> (string[] args, int arg, T t) {
long i = 42;
string s = "AB";
for (int j = 0; j < 10; ++j) {
if (s != null)
i ++;
if (t != null)
i ++;
}
}
@@ -618,6 +620,23 @@ public class Tests : TestsBase
o.GetType ();
} catch (Exception) {
}
try {
exceptions2 ();
} catch (Exception) {
}
}
[MethodImplAttribute (MethodImplOptions.NoInlining)]
public static bool return_true () {
return true;
}
[MethodImplAttribute (MethodImplOptions.NoInlining)]
public static void exceptions2 () {
if (return_true ())
throw new Exception ();
Console.WriteLine ();
}
[MethodImplAttribute (MethodImplOptions.NoInlining)]
+48 -5
View File
@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Threading;
using System.Net;
using System.Reflection;
using System.Text;
using Mono.Cecil.Cil;
using Mono.Debugger.Soft;
using Diag = System.Diagnostics;
@@ -93,7 +94,7 @@ public class DebuggerTests
}
Assert.IsInstanceOfType (typeof (BreakpointEvent), e);
Assert.AreEqual (m, (e as BreakpointEvent).Method);
Assert.AreEqual (m.Name, (e as BreakpointEvent).Method.Name);
return (e as BreakpointEvent);
}
@@ -885,7 +886,6 @@ public class DebuggerTests
}
[Test]
[Category ("only")]
public void Type_SetValue () {
var e = run_until ("o1");
var frame = e.Thread.GetFrames () [0];
@@ -1319,8 +1319,8 @@ public class DebuggerTests
StackFrame frame = e.Thread.GetFrames () [0];
var locals = frame.Method.GetLocals ();
Assert.AreEqual (5, locals.Length);
for (int i = 0; i < 5; ++i) {
Assert.AreEqual (6, locals.Length);
for (int i = 0; i < 6; ++i) {
if (locals [i].Name == "args") {
Assert.IsTrue (locals [i].IsArg);
Assert.AreEqual ("String[]", locals [i].Type.Name);
@@ -1336,6 +1336,10 @@ public class DebuggerTests
} else if (locals [i].Name == "s") {
Assert.IsFalse (locals [i].IsArg);
Assert.AreEqual ("String", locals [i].Type.Name);
} else if (locals [i].Name == "t") {
// gshared
Assert.IsTrue (locals [i].IsArg);
Assert.AreEqual ("String", locals [i].Type.Name);
} else {
Assert.Fail ();
}
@@ -1343,6 +1347,7 @@ public class DebuggerTests
}
[Test]
[Category ("only")]
public void Locals () {
var be = run_until ("locals1");
@@ -1385,6 +1390,8 @@ public class DebuggerTests
AssertValue (42, vals [i]);
if (locals [i].Name == "s")
AssertValue ("AB", vals [i]);
if (locals [i].Name == "t")
AssertValue ("ABC", vals [i]);
}
// Argument checking
@@ -1654,6 +1661,12 @@ public class DebuggerTests
Assert.AreEqual ("ABC", s.Value);
Assert.AreEqual (vm.RootDomain, s.Domain);
// Long strings
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < 1024; ++i)
sb.Append ('A');
s = vm.RootDomain.CreateString (sb.ToString ());
// Argument checking
AssertThrows <ArgumentNullException> (delegate () {
s = vm.RootDomain.CreateString (null);
@@ -1661,7 +1674,6 @@ public class DebuggerTests
}
[Test]
[Category ("only")]
public void CreateBoxedValue () {
ObjectMirror o = vm.RootDomain.CreateBoxedValue (new PrimitiveValue (vm, 42));
@@ -1975,6 +1987,7 @@ public class DebuggerTests
}
[Test]
[Category ("only")]
public void Frame_SetValue () {
Event e = run_until ("locals2");
@@ -2000,6 +2013,11 @@ public class DebuggerTests
frame.SetValue (p, vm.CreateValue (7));
AssertValue (7, frame.GetValue (p));
// gshared
p = frame.Method.GetParameters ()[2];
frame.SetValue (p, vm.RootDomain.CreateString ("DEF"));
AssertValue ("DEF", frame.GetValue (p));
// argument checking
// variable null
@@ -2117,6 +2135,31 @@ public class DebuggerTests
Assert.AreEqual ("NullReferenceException", (e as ExceptionEvent).Exception.Type.Name);
req.Disable ();
// Single stepping after an exception
req = vm.CreateExceptionRequest (null);
req.Enable ();
vm.Resume ();
e = vm.GetNextEvent ();
Assert.IsInstanceOfType (typeof (ExceptionEvent), e);
Assert.AreEqual ("Exception", (e as ExceptionEvent).Exception.Type.Name);
frames = e.Thread.GetFrames ();
Assert.AreEqual ("exceptions2", frames [0].Method.Name);
req.Disable ();
var sreq = vm.CreateStepRequest (e.Thread);
sreq.Depth = StepDepth.Over;
sreq.Size = StepSize.Line;
sreq.Enable ();
vm.Resume ();
e = vm.GetNextEvent ();
Assert.IsInstanceOfType (typeof (StepEvent), e);
frames = e.Thread.GetFrames ();
Assert.AreEqual ("exceptions", frames [0].Method.Name);
sreq.Disable ();
// Argument checking
AssertThrows<ArgumentException> (delegate {
vm.CreateExceptionRequest (e.Thread.Type);
@@ -39,9 +39,19 @@ namespace System.Configuration {
bool modified;
bool readOnly;
int originalStringHash = 0;
public bool IsModified {
get { return modified; }
get {
if (modified)
return true;
string str = ToString ();
if (str == null)
return false;
return str.GetHashCode () != originalStringHash;
}
}
public new bool IsReadOnly {
@@ -89,6 +99,7 @@ namespace System.Configuration {
CopyTo (contents, 0);
col.AddRange (contents);
col.originalStringHash = originalStringHash;
return col;
}
@@ -125,6 +136,15 @@ namespace System.Configuration {
return String.Join (",", contents);
}
internal void UpdateStringHash ()
{
string str = ToString ();
if (str == null)
originalStringHash = 0;
else
originalStringHash = str.GetHashCode ();
}
}
}
@@ -48,6 +48,7 @@ namespace System.Configuration
foreach (string datum in datums)
col.Add (datum.Trim());
col.UpdateStringHash ();
return col;
}
@@ -8,7 +8,7 @@ System.Drawing/BufferedGraphics.cs
System.Drawing/BufferedGraphicsManager.cs
System.Drawing/BufferedGraphicsContext.cs
System.Drawing/CharacterRange.cs
System.Drawing/carbonFunctions.cs
System.Drawing/macFunctions.cs
System.Drawing/ColorConverter.cs
System.Drawing/Color.cs
System.Drawing/ColorTranslator.cs
@@ -49,7 +49,7 @@ namespace System.Drawing
#endif
{
internal IntPtr nativeObject = IntPtr.Zero;
internal CarbonContext context;
internal IMacContext maccontext;
private bool disposed = false;
private static float defDpiX = 0;
private static float defDpiY = 0;
@@ -190,6 +190,8 @@ namespace System.Drawing
CopyFromScreenX11 (sourceX, sourceY, destinationX, destinationY, blockRegionSize, copyPixelOperation);
} else if (GDIPlus.UseCarbonDrawable) {
CopyFromScreenMac (sourceX, sourceY, destinationX, destinationY, blockRegionSize, copyPixelOperation);
} else if (GDIPlus.UseCocoaDrawable) {
CopyFromScreenMac (sourceX, sourceY, destinationX, destinationY, blockRegionSize, copyPixelOperation);
} else {
CopyFromScreenWin32 (sourceX, sourceY, destinationX, destinationY, blockRegionSize, copyPixelOperation);
}
@@ -293,11 +295,11 @@ namespace System.Drawing
{
Status status;
if (! disposed) {
if (GDIPlus.UseCarbonDrawable && context.ctx != IntPtr.Zero) {
if (GDIPlus.UseCarbonDrawable || GDIPlus.UseCocoaDrawable) {
Flush ();
Carbon.CGContextSynchronize (context.ctx);
Carbon.ReleaseContext (context.port, context.ctx);
maccontext.Release ();
}
status = GDIPlus.GdipDeleteGraphics (nativeObject);
nativeObject = IntPtr.Zero;
GDIPlus.CheckStatus (status);
@@ -1681,8 +1683,9 @@ namespace System.Drawing
Status status = GDIPlus.GdipFlush (nativeObject, intention);
GDIPlus.CheckStatus (status);
if (GDIPlus.UseCarbonDrawable && context.ctx != IntPtr.Zero)
Carbon.CGContextSynchronize (context.ctx);
if (maccontext != null)
maccontext.Synchronize ();
}
[EditorBrowsable (EditorBrowsableState.Advanced)]
@@ -1714,12 +1717,22 @@ namespace System.Drawing
{
IntPtr graphics;
if (GDIPlus.UseCocoaDrawable) {
CocoaContext context = MacSupport.GetCGContextForNSView (hwnd);
GDIPlus.GdipCreateFromContext_macosx (context.ctx, context.width, context.height, out graphics);
Graphics g = new Graphics (graphics);
g.maccontext = context;
return g;
}
if (GDIPlus.UseCarbonDrawable) {
CarbonContext context = Carbon.GetCGContextForView (hwnd);
CarbonContext context = MacSupport.GetCGContextForView (hwnd);
GDIPlus.GdipCreateFromContext_macosx (context.ctx, context.width, context.height, out graphics);
Graphics g = new Graphics (graphics);
g.context = context;
g.maccontext = context;
return g;
}
@@ -61,6 +61,7 @@ namespace System.Drawing
public static IntPtr Display = IntPtr.Zero;
public static bool UseX11Drawable = false;
public static bool UseCarbonDrawable = false;
public static bool UseCocoaDrawable = false;
#region gdiplus.dll functions
@@ -138,12 +139,12 @@ namespace System.Drawing
static public bool RunningOnWindows ()
{
return !UseX11Drawable && !UseCarbonDrawable;
return !UseX11Drawable && !UseCarbonDrawable && !UseCocoaDrawable;
}
static public bool RunningOnUnix ()
{
return UseX11Drawable || UseCarbonDrawable;
return UseX11Drawable || UseCarbonDrawable || UseCocoaDrawable;
}
// Copies a Ptr to an array of Points and releases the memory
@@ -36,9 +36,9 @@ namespace System.Drawing {
[SuppressUnmanagedCodeSecurity]
#if NET_2_0
internal static class Carbon {
internal static class MacSupport {
#else
internal sealed class Carbon {
internal sealed class MacSupport {
#endif
internal static Hashtable contextReference = new Hashtable ();
internal static object lockobj = new object ();
@@ -52,7 +52,7 @@ namespace System.Drawing {
internal static int debug_threshold = 1;
#endif
static Carbon () {
static MacSupport () {
foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies ()) {
if (String.Equals (asm.GetName ().Name, "System.Windows.Forms")) {
Type driver_type = asm.GetType ("System.Windows.Forms.XplatUICarbon");
@@ -63,6 +63,16 @@ namespace System.Drawing {
}
}
internal static CocoaContext GetCGContextForNSView (IntPtr handle) {
IntPtr graphicsContext = objc_msgSend (objc_getClass ("NSGraphicsContext"), sel_registerName ("currentContext"));
IntPtr ctx = objc_msgSend (graphicsContext, sel_registerName ("graphicsPort"));
Rect bounds = new Rect ();
objc_msgSend_stret (ref bounds, handle, sel_registerName ("bounds"));
return new CocoaContext (ctx, (int) bounds.size.width, (int) bounds.size.height);
}
internal static CarbonContext GetCGContextForView (IntPtr handle) {
IntPtr context = IntPtr.Zero;
IntPtr port = IntPtr.Zero;
@@ -289,7 +299,7 @@ namespace System.Drawing {
public short right;
}
internal struct CarbonContext
internal struct CarbonContext : IMacContext
{
public IntPtr port;
public IntPtr ctx;
@@ -303,5 +313,44 @@ namespace System.Drawing {
this.width = width;
this.height = height;
}
public void Synchronize ()
{
MacSupport.CGContextSynchronize (ctx);
}
public void Release ()
{
MacSupport.ReleaseContext (port, ctx);
}
}
internal struct CocoaContext : IMacContext
{
public IntPtr ctx;
public int width;
public int height;
public CocoaContext (IntPtr ctx, int width, int height)
{
this.ctx = ctx;
this.width = width;
this.height = height;
}
public void Synchronize ()
{
MacSupport.CGContextSynchronize (ctx);
}
public void Release ()
{
}
}
internal interface IMacContext
{
void Synchronize ();
void Release ();
}
}
@@ -66,8 +66,6 @@ namespace System.Json
{
if (key == null)
throw new ArgumentNullException ("key");
if (value == null)
throw new ArgumentNullException ("value");
map.Add (key, value);
}
@@ -143,7 +141,13 @@ namespace System.Json
stream.WriteByte ((byte) '"');
stream.WriteByte ((byte) ',');
stream.WriteByte ((byte) ' ');
pair.Value.Save (stream);
if (pair.Value == null) {
stream.WriteByte ((byte) 'n');
stream.WriteByte ((byte) 'u');
stream.WriteByte ((byte) 'l');
stream.WriteByte ((byte) 'l');
} else
pair.Value.Save (stream);
}
stream.WriteByte ((byte) '}');
}
@@ -148,7 +148,10 @@ namespace System.Json
w.Write ('\"');
w.Write (EscapeString (pair.Key));
w.Write ("\": ");
pair.Value.SaveInternal (w);
if (pair.Value == null)
w.Write ("null");
else
pair.Value.SaveInternal (w);
following = true;
}
w.Write ('}');
@@ -107,8 +107,8 @@ namespace System.ServiceModel.Description
var uri = new Uri (String.Concat (baseUriString, baseUriString [baseUriString.Length - 1] == '/' ? String.Empty : "/", subPath));
var listener = endpoint.Binding.BuildChannelListener<IReplyChannel> (uri);
var cd = new ChannelDispatcher (listener, String.Empty);
cd.MessageVersion = MessageVersion.None;
cd.MessageVersion = MessageVersion.None;
cd.Endpoints.Add (new EndpointDispatcher (new EndpointAddress (uri), "InteropScriptService", String.Empty)
{ ContractFilter = new MatchAllMessageFilter () });
@@ -40,11 +40,6 @@ using System.Threading;
namespace System.ServiceModel.Channels.Http
{
internal interface IChannelDispatcherBoundListener
{
ChannelDispatcher ChannelDispatcher { get; set; }
}
internal class HttpChannelListener<TChannel> : InternalChannelListenerBase<TChannel>, IChannelDispatcherBoundListener
where TChannel : class, IChannel
{
@@ -325,14 +325,15 @@ namespace System.ServiceModel.Channels.Http
public override void Abort ()
{
res.Flush ();
res.Close ();
res.End ();
}
public override void Close ()
{
res.Flush ();
res.Close ();
// We must not close the response here, as everything is taking place in the
// HttpApplication's pipeline context and the output is sent to the client
// _after_ we leave this method. Closing the response here will stop any
// output from reaching the client.
}
public override void SetLength (long value)
@@ -99,16 +99,43 @@ namespace System.ServiceModel.Channels {
string line;
bool directive_found = false;
StringBuilder content = new StringBuilder ();
StringBuilder directiveBuffer = null;
while ((line = reader.ReadLine ()) != null) {
string trimmed = line.Trim ();
if (!directive_found && trimmed == String.Empty)
if (!directive_found && trimmed.Length == 0)
continue;
if (trimmed.StartsWith ("<%@")) {
int directiveEnd = trimmed.IndexOf ("%>");
if (directiveEnd == -1) {
if (directiveBuffer == null)
directiveBuffer = new StringBuilder ();
directiveBuffer.Append (line);
continue;
}
ParseDirective (trimmed);
directive_found = true;
continue;
} else if (!directive_found && directiveBuffer != null) {
int directiveEnd = trimmed.IndexOf ("%>");
if (directiveEnd == -1) {
directiveBuffer.Append (trimmed);
continue;
}
directiveEnd += 2;
int tlen = trimmed.Length;
if (tlen > directiveEnd)
content.Append (trimmed.Substring (directiveEnd) + "\n");
directiveBuffer.Append (trimmed.Substring (0, directiveEnd));
ParseDirective (directiveBuffer.ToString ());
directive_found = true;
directiveBuffer = null;
continue;
}
content.Append (line + "\n");
@@ -119,7 +146,7 @@ namespace System.ServiceModel.Channels {
throw new Exception ("No @ServiceHost directive found");
this.program = content.ToString ().Trim ();
if (this.program.Trim () == "")
if (this.program.Trim ().Length == 0)
this.program = null;
}
@@ -75,7 +75,9 @@ namespace System.ServiceModel.Channels
EnsureServiceHost ();
var table = HttpListenerManagerTable.GetOrCreate (host);
var manager = table.GetOrCreateManager (host.BaseAddresses [0]);
var manager = table.GetOrCreateManager (context.Request.Url);
if (manager == null)
manager = table.GetOrCreateManager (host.BaseAddresses [0]);
var wait = new ManualResetEvent (false);
wcf_wait_handles [context] = wait;
manager.ProcessNewContext (new System.ServiceModel.Channels.Http.AspNetHttpContextInfo (this, context));
@@ -37,11 +37,6 @@ using System.ServiceModel.Description;
namespace System.ServiceModel.Dispatcher
{
internal interface IChannelDispatcherBoundListener
{
ChannelDispatcher ChannelDispatcher { get; set; }
}
public class ChannelDispatcher : ChannelDispatcherBase
{
class EndpointDispatcherCollection : SynchronizedCollection<EndpointDispatcher>
@@ -0,0 +1,36 @@
//
// ChannelDispatcher.cs
//
// Author:
// Atsushi Enomoto <[email protected]>
//
// Copyright (C) 2005-2010 Novell, Inc. http://www.novell.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
namespace System.ServiceModel.Dispatcher
{
internal interface IChannelDispatcherBoundListener
{
ChannelDispatcher ChannelDispatcher { get; set; }
}
}
@@ -643,6 +643,7 @@ System.ServiceModel.Dispatcher/FaultContractInfo.cs
System.ServiceModel.Dispatcher/FilterInvalidBodyAccessException.cs
System.ServiceModel.Dispatcher/FinalizeProcessingHandler.cs
System.ServiceModel.Dispatcher/ICallContextInitializer.cs
System.ServiceModel.Dispatcher/IChannelDispatcherBoundListener.cs
System.ServiceModel.Dispatcher/IChannelInitializer.cs
System.ServiceModel.Dispatcher/IClientMessageFormatter.cs
System.ServiceModel.Dispatcher/IClientMessageInspector.cs
@@ -1,7 +1,7 @@
../../build/common/Consts.cs
../../build/common/Locale.cs
../../build/common/MonoTODOAttribute.cs
../System.Web/System.Web.Configuration_2.0/MachineKeySectionUtils.cs
../System.Web/System.Web.Util/MachineKeySectionUtils.cs
../System.Web/System.Web.Configuration_2.0/MachineKeyRegistryStorage.cs
../System.Web/System.Web.Handlers/AssemblyResourceLoader.cs
./Assembly/AssemblyInfo.cs
@@ -72,11 +72,13 @@ namespace System.Web.Script.Services
readonly MethodInfo _methodInfo;
internal readonly ParameterInfo [] _params;
internal readonly Dictionary<string, int> _paramMap;
LogicalTypeInfo _typeInfo;
protected LogicalMethodInfo (LogicalTypeInfo typeInfo, MethodInfo method)
{
_methodInfo = method;
_params = MethodInfo.GetParameters ();
_typeInfo = typeInfo;
if (HasParameters) {
_paramMap = new Dictionary<string, int> (_params.Length, StringComparer.Ordinal);
@@ -101,8 +103,10 @@ namespace System.Web.Script.Services
}
public void GenerateMethod (StringBuilder proxy, bool isPrototype, bool isPage) {
string service = isPage ? "PageMethods" : MethodInfo.DeclaringType.FullName;
string ns;
string service;// = isPage ? "PageMethods" : MethodInfo.DeclaringType.FullName;
_typeInfo.GetNamespaceAndServiceName (MethodInfo.DeclaringType, isPage, out ns, out service);
string useHttpGet = UseHttpGet ? "true" : "false";
string paramMap = GenerateParameters (true);
string paramList = GenerateParameters (false);
@@ -187,6 +191,12 @@ Type.registerNamespace('{0}');",
return name;
}
protected virtual void GetNamespaceAndServiceName (Type type, bool isPage, out string ns, out string service)
{
ns = isPage ? String.Empty : type.Namespace;
service = isPage ? "PageMethods" : type.FullName;
}
// instance members
internal readonly Type _type;
@@ -205,8 +215,9 @@ Type.registerNamespace('{0}');",
for (int i = 0; i < logicalMethods.Count; i++)
_methodMap.Add (logicalMethods [i].MethodName, logicalMethods [i]);
string ns = isPage ? String.Empty : t.Namespace;
string service = isPage ? "PageMethods" : t.FullName;
string ns;
string service;
GetNamespaceAndServiceName (t, isPage, out ns, out service);
StringBuilder proxy = new StringBuilder ();
List<string> registeredNamespaces = new List<string> ();
@@ -616,6 +627,16 @@ var gtc = Sys.Net.WebServiceProxy._generateTypedConstructor;");
yield break;
}
protected override void GetNamespaceAndServiceName (Type type, bool isPage, out string ns, out string service)
{
string name = type.Namespace;
int dot = name.LastIndexOf ('.');
if (dot > -1)
name = name.Substring (dot + 1);
ns = name;
service = name + "." + type.Name;
}
protected override void GenerateTypeRegistrationScript (StringBuilder proxy, List<string> registeredNamespaces)
{
bool gtc = false;
@@ -3,7 +3,7 @@
../../build/common/MonoTODOAttribute.cs
../System.Web/System.Web.Handlers/AssemblyResourceLoader.cs
../System.Web/System.Web.Configuration_2.0/MachineKeyRegistryStorage.cs
../System.Web/System.Web.Configuration_2.0/MachineKeySectionUtils.cs
../System.Web/System.Web.Util/MachineKeySectionUtils.cs
../System.Web.Extensions/Assembly/AssemblyInfo.cs
../System.Web.Extensions/System.Web.Handlers/ScriptModule.cs
../System.Web.Extensions/System.Web.Handlers/ScriptResourceHandler.cs
@@ -302,8 +302,10 @@ namespace System.Web.Routing
argSegs = path.Split ('/');
argsCount = argSegs.Length;
if (String.IsNullOrEmpty (argSegs [argsCount - 1]))
argsCount--; // path ends with a trailinig '/'
}
bool haveDefaults = defaults != null && defaults.Count > 0;
if (argsCount == 1 && String.IsNullOrEmpty (argSegs [0]))
@@ -353,7 +355,8 @@ namespace System.Web.Routing
if (!defaults.ContainsKey (tokens [0].Name))
return null;
}
}
} else if (!haveSegmentWithCatchAll && argsCount > segmentCount)
return null;
return AddDefaults (ret, defaults);
}
@@ -907,6 +907,59 @@ namespace MonoTests.System.Web.Routing
Assert.AreEqual ("3", rd.Values ["baz"], "#4-2");
}
[Test]
public void GetRouteData44 ()
{
// {} matches and substitutes even at partial state ...
var r = new Route ("{foo}/bartes{baz}", null);
var hc = new HttpContextStub ("~/x/bartest/", String.Empty);
var rd = r.GetRouteData (hc);
Assert.IsNotNull (rd, "#1");
Assert.AreEqual (r, rd.Route, "#2");
Assert.AreEqual (0, rd.DataTokens.Count, "#3");
Assert.AreEqual (2, rd.Values.Count, "#4");
Assert.AreEqual ("x", rd.Values ["foo"], "#4-1");
Assert.AreEqual ("t", rd.Values ["baz"], "#4-2");
}
[Test]
public void GetRouteData45 ()
{
var r = new Route ("{foo}/{bar}", null);
var hc = new HttpContextStub ("~/x/y/", String.Empty);
var rd = r.GetRouteData (hc);
Assert.IsNotNull (rd, "#1");
Assert.AreEqual (r, rd.Route, "#2");
Assert.AreEqual (0, rd.DataTokens.Count, "#3");
Assert.AreEqual (2, rd.Values.Count, "#4");
Assert.AreEqual ("x", rd.Values ["foo"], "#4-1");
Assert.AreEqual ("y", rd.Values ["bar"], "#4-2");
}
[Test (Description="Bug #651593")]
public void GetRouteData46 ()
{
var r = new Route ("Foo", null) {
Defaults = new RouteValueDictionary (new {
controller = "Foo",
action = "Index"
})
};
var hc = new HttpContextStub ("/Foo/123", String.Empty);
var rd = r.GetRouteData (hc);
Assert.IsNull (rd, "#1");
r = new Route ("Foo", null) {
Defaults = new RouteValueDictionary (new {
controller = "Foo",
action = "Index"
})
};
hc = new HttpContextStub ("~/Foo/123", String.Empty);
rd = r.GetRouteData (hc);
Assert.IsNull (rd, "#2");
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void GetVirtualPathNullContext ()
+2 -2
View File
@@ -287,7 +287,7 @@ TEST_MCS_FLAGS = $(LIB_MCS_FLAGS) -doc:$(test_lib:.dll=.xml) -nowarn:219,169,159
$(foreach file,$(NUNIT_APP_GLOBALRESOURCES_FILES),$(shell echo $(file) | sed -e 's;\(.*\)/\(.*\);/resource:\1/\2,App_GlobalResources/\2 ;g'))
ifeq (net_2_0, $(PROFILE))
TEST_MCS_FLAGS += -r:System.Web.Extensions.dll
TEST_MCS_FLAGS += -r:System.Web.Extensions.dll -d:TEST
endif
EXTRA_DISTFILES = \
@@ -442,4 +442,4 @@ ifdef STANDALONE_TEST_COMPILABLE_TESTS
done
endif
@@ -49,7 +49,8 @@ namespace System.Web.Configuration {
static ConfigurationPropertyCollection properties;
AuthorizationRuleAction action;
ConfigurationSaveMode saveMode = ConfigurationSaveMode.Full;
static AuthorizationRule ()
{
rolesProp = new ConfigurationProperty ("roles", typeof (StringCollection), null,
@@ -130,7 +131,10 @@ namespace System.Web.Configuration {
[MonoTODO ("Not implemented")]
protected override bool IsModified ()
{
throw new NotImplementedException ();
if (((CommaDelimitedStringCollection)Roles).IsModified || ((CommaDelimitedStringCollection)Users).IsModified || ((CommaDelimitedStringCollection)Verbs).IsModified)
return true;
return false;
}
void VerifyData ()
@@ -168,6 +172,9 @@ namespace System.Web.Configuration {
protected override bool SerializeElement (XmlWriter writer, bool serializeCollectionKey)
{
if (saveMode != ConfigurationSaveMode.Full && !IsModified ())
return true;
PreSerialize (writer);
writer.WriteStartElement (action == AuthorizationRuleAction.Allow ? "allow" : "deny");
@@ -191,6 +198,7 @@ namespace System.Web.Configuration {
protected override void Unmerge (ConfigurationElement sourceElement, ConfigurationElement parentElement, ConfigurationSaveMode saveMode)
{
base.Unmerge (sourceElement, parentElement, saveMode);
this.saveMode = saveMode;
}
public AuthorizationRuleAction Action {
@@ -108,9 +108,8 @@ namespace System.Web.Configuration {
get { return ConfigurationElementCollectionType.BasicMapAlternate; }
}
[MonoTODO ("is it okay to return a comma delimited string here?")]
protected override string ElementName {
get { return "allow,deny"; }
get { return String.Empty; }
}
public AuthorizationRule this [int index] {
@@ -0,0 +1,36 @@
//
// System.Web.Configuration.MachineKeyCompatibilityMode
//
// Authors:
// Sebastien Pouliot <[email protected]>
//
// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace System.Web.Configuration {
public enum MachineKeyCompatibilityMode {
Framework20SP1 = 0,
Framework20SP2 = 1
}
}
@@ -28,8 +28,6 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Security.Cryptography;
using Microsoft.Win32;
namespace System.Web.Configuration
@@ -42,9 +40,6 @@ namespace System.Web.Configuration
Encryption
};
const int encryptionKeyLength = 64;
const int validationKeyLength = 64;
static string keyEncryption;
static string keyValidation;
@@ -62,31 +57,16 @@ namespace System.Web.Configuration
}
public static byte[] Retrieve (KeyType kt)
{
byte[] ret = GetKey (kt);
if (ret == null) {
ret = Generate (kt);
if (ret != null)
Store (ret, kt);
}
return ret;
}
static byte[] GetKey (KeyType kt)
{
string key = null;
int len;
switch (kt) {
case KeyType.Validation:
key = keyValidation;
len = validationKeyLength;
break;
case KeyType.Encryption:
key = keyEncryption;
len = validationKeyLength;
break;
default:
@@ -107,11 +87,7 @@ namespace System.Web.Configuration
if (o == null || o.GetType () != typeof (byte[]))
return null;
byte[] ret = (byte[])o;
if (ret.Length != len)
return null;
return ret;
return (byte[]) o;
}
static RegistryKey OpenRegistryKey (string path, bool write)
@@ -134,23 +110,19 @@ namespace System.Web.Configuration
return ret;
}
static void Store (byte[] buf, KeyType kt)
public static void Store (byte[] buf, KeyType kt)
{
if (buf == null)
return;
string key = null;
int len;
switch (kt) {
case KeyType.Validation:
key = keyValidation;
len = validationKeyLength;
break;
case KeyType.Encryption:
key = keyEncryption;
len = validationKeyLength;
break;
default:
@@ -160,9 +132,6 @@ namespace System.Web.Configuration
if (key == null)
return;
if (buf.Length != len)
throw new ArgumentException ("Key has invalid length");
try {
using (RegistryKey rk = OpenRegistryKey (key, true)) {
#if NET_2_0
@@ -180,27 +149,5 @@ namespace System.Web.Configuration
throw new ApplicationException ("Failed to store encryption key in the registry.", ex);
}
}
static byte[] Generate (KeyType kt)
{
RandomNumberGenerator rng = RandomNumberGenerator.Create ();
byte[] ret = null;
switch (kt) {
case KeyType.Validation:
ret = new byte [validationKeyLength];
break;
case KeyType.Encryption:
ret = new byte [encryptionKeyLength];
break;
default:
throw new ArgumentException ("Unknown key type.");
}
rng.GetBytes (ret);
return ret;
}
}
}
@@ -3,8 +3,9 @@
//
// Authors:
// Chris Toshok ([email protected])
// Sebastien Pouliot <[email protected]>
//
// (c) Copyright 2005 Novell, Inc (http://www.novell.com)
// (c) Copyright 2005, 2010 Novell, Inc (http://www.novell.com)
//
//
@@ -28,12 +29,13 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_2_0
using System;
using System.ComponentModel;
using System.Configuration;
using System.Security.Cryptography;
#if NET_2_0
using System.Web.Util;
namespace System.Web.Configuration {
@@ -44,6 +46,10 @@ namespace System.Web.Configuration {
static ConfigurationProperty validationProp;
static ConfigurationProperty validationKeyProp;
static ConfigurationPropertyCollection properties;
static MachineKeyValidationConverter converter = new MachineKeyValidationConverter ();
#if NET_4_0
MachineKeyValidation validation;
#endif
static MachineKeySection ()
{
@@ -55,10 +61,17 @@ namespace System.Web.Configuration {
PropertyHelper.WhiteSpaceTrimStringConverter,
PropertyHelper.NonEmptyStringValidator,
ConfigurationPropertyOptions.None);
validationProp = new ConfigurationProperty ("validation", typeof (MachineKeyValidation), MachineKeyValidation.SHA1,
new MachineKeyValidationConverter (),
#if NET_4_0
validationProp = new ConfigurationProperty ("validation", typeof (string), "HMACSHA256",
PropertyHelper.WhiteSpaceTrimStringConverter,
PropertyHelper.NonEmptyStringValidator,
ConfigurationPropertyOptions.None);
#else
validationProp = new ConfigurationProperty ("validation", typeof (MachineKeyValidation),
MachineKeyValidation.SHA1, converter,
PropertyHelper.DefaultValidator,
ConfigurationPropertyOptions.None);
#endif
validationKeyProp = new ConfigurationProperty ("validationKey", typeof (string), "AutoGenerate,IsolateApps",
PropertyHelper.WhiteSpaceTrimStringConverter,
PropertyHelper.NonEmptyStringValidator,
@@ -71,12 +84,30 @@ namespace System.Web.Configuration {
properties.Add (validationProp);
properties.Add (validationKeyProp);
MachineKeySectionUtils.AutoGenKeys ();
Config.AutoGenerate (MachineKeyRegistryStorage.KeyType.Encryption);
Config.AutoGenerate (MachineKeyRegistryStorage.KeyType.Validation);
}
#if NET_4_0
public MachineKeySection ()
{
// get DefaultValue from ValidationAlgorithm
validation = (MachineKeyValidation) converter.ConvertFrom (null, null, ValidationAlgorithm);
}
[MonoTODO]
public MachineKeyCompatibilityMode CompatibilityMode {
get; set;
}
#endif
protected override void Reset (ConfigurationElement parentElement)
{
base.Reset (parentElement);
decryption_key = null;
validation_key = null;
decryption_template = null;
validation_template = null;
}
[TypeConverter (typeof (WhiteSpaceTrimStringConverter))]
@@ -84,7 +115,10 @@ namespace System.Web.Configuration {
[ConfigurationProperty ("decryption", DefaultValue = "Auto")]
public string Decryption {
get { return (string) base [decryptionProp];}
set { base[decryptionProp] = value; }
set {
decryption_template = MachineKeySectionUtils.GetDecryptionAlgorithm (value);
base[decryptionProp] = value;
}
}
[TypeConverter (typeof (WhiteSpaceTrimStringConverter))]
@@ -94,16 +128,49 @@ namespace System.Web.Configuration {
get { return (string) base [decryptionKeyProp];}
set {
base[decryptionKeyProp] = value;
MachineKeySectionUtils.SetDecryptionKey (value);
SetDecryptionKey (value);
}
}
#if NET_4_0
// property exists for backward compatibility
public MachineKeyValidation Validation {
get { return validation; }
set {
if (value == MachineKeyValidation.Custom)
throw new ArgumentException ();
string algo = value.ToString ();
// enum and accept values differs for TripleDES
ValidationAlgorithm = (algo == "TripleDES") ? "3DES" : algo;
}
}
[StringValidator (MinLength = 1)]
[TypeConverter (typeof (WhiteSpaceTrimStringConverter))]
[ConfigurationProperty ("validation", DefaultValue = "HMACSHA256")]
public string ValidationAlgorithm {
get { return (string) base [validationProp];}
set {
if (value == null)
return;
if (value.StartsWith ("alg:"))
validation = MachineKeyValidation.Custom;
else
validation = (MachineKeyValidation) converter.ConvertFrom (null, null, value);
base[validationProp] = value;
}
}
#else
[TypeConverter (typeof (MachineKeyValidationConverter))]
[ConfigurationProperty ("validation", DefaultValue = "SHA1")]
public MachineKeyValidation Validation {
get { return (MachineKeyValidation) base [validationProp];}
set { base[validationProp] = value; }
}
#endif
[TypeConverter (typeof (WhiteSpaceTrimStringConverter))]
[StringValidator (MinLength = 1)]
@@ -112,13 +179,142 @@ namespace System.Web.Configuration {
get { return (string) base [validationKeyProp];}
set {
base[validationKeyProp] = value;
MachineKeySectionUtils.SetValidationKey (value);
SetValidationKey (value);
}
}
protected override ConfigurationPropertyCollection Properties {
get { return properties; }
}
internal static MachineKeySection Config {
get { return WebConfigurationManager.GetSection ("system.web/machineKey") as MachineKeySection; }
}
byte[] decryption_key;
byte[] validation_key;
SymmetricAlgorithm decryption_template;
KeyedHashAlgorithm validation_template;
internal SymmetricAlgorithm GetDecryptionAlgorithm ()
{
// code location to help with unit testing the code
return MachineKeySectionUtils.GetDecryptionAlgorithm (Decryption);
}
// not to be reused outside algorithm and key validation purpose
SymmetricAlgorithm DecryptionTemplate {
get {
if (decryption_template == null)
decryption_template = GetDecryptionAlgorithm ();
return decryption_template;
}
}
internal byte [] GetDecryptionKey ()
{
if (decryption_key == null)
SetDecryptionKey (DecryptionKey);
return decryption_key;
}
void SetDecryptionKey (string key)
{
if ((key == null) || key.StartsWith ("AutoGenerate")) {
decryption_key = AutoGenerate (MachineKeyRegistryStorage.KeyType.Encryption);
} else {
try {
decryption_key = MachineKeySectionUtils.GetBytes (key, key.Length);
DecryptionTemplate.Key = decryption_key;
}
catch {
decryption_key = null;
throw new ArgumentException ("Invalid key length");
}
}
}
internal KeyedHashAlgorithm GetValidationAlgorithm ()
{
// code location to help with unit testing the code
return MachineKeySectionUtils.GetValidationAlgorithm (this);
}
// not to be reused outside algorithm and key validation purpose
KeyedHashAlgorithm ValidationTemplate {
get {
if (validation_template == null)
validation_template = GetValidationAlgorithm ();
return validation_template;
}
}
internal byte [] GetValidationKey ()
{
if (validation_key == null)
SetValidationKey (ValidationKey);
return validation_key;
}
// key can be expended for HMAC - i.e. a small key, e.g. 32 bytes, is still accepted as valid
// the HMAC class already deals with keys larger than what it can use (digested to right size)
void SetValidationKey (string key)
{
if ((key == null) || key.StartsWith ("AutoGenerate")) {
validation_key = AutoGenerate (MachineKeyRegistryStorage.KeyType.Validation);
} else {
try {
validation_key = MachineKeySectionUtils.GetBytes (key, key.Length);
ValidationTemplate.Key = validation_key;
}
catch (CryptographicException) {
// second chance, use the key length that the HMAC really wants
try {
byte[] expanded_key = new byte [ValidationTemplate.Key.Length];
Array.Copy (validation_key, 0, expanded_key, 0, validation_key.Length);
ValidationTemplate.Key = expanded_key;
validation_key = expanded_key;
}
catch {
validation_key = null;
throw new ArgumentException ("Invalid key length");
}
}
}
}
byte[] AutoGenerate (MachineKeyRegistryStorage.KeyType type)
{
byte[] key = null;
#if TARGET_J2EE
{
#else
try {
key = MachineKeyRegistryStorage.Retrieve (type);
// ensure the stored key is usable with the selection algorithm
if (type == MachineKeyRegistryStorage.KeyType.Encryption)
DecryptionTemplate.Key = key;
else if (type == MachineKeyRegistryStorage.KeyType.Validation)
ValidationTemplate.Key = key;
} catch (Exception) {
key = null;
}
#endif
// some algorithms have special needs for key (e.g. length, parity, weak keys...)
// so we better ask them to provide a default key (than to generate/use bad ones)
if (key == null) {
if (type == MachineKeyRegistryStorage.KeyType.Encryption)
key = DecryptionTemplate.Key;
else if (type == MachineKeyRegistryStorage.KeyType.Validation)
key = ValidationTemplate.Key;
#if !TARGET_J2EE
MachineKeyRegistryStorage.Store (key, type);
#endif
}
return key;
}
}
}
@@ -1,187 +0,0 @@
//
// System.Web.Configuration.MachineKeySection
//
// Authors:
// Chris Toshok ([email protected])
//
// (c) Copyright 2005 Novell, Inc (http://www.novell.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.ComponentModel;
using System.Configuration;
using System.Security.Cryptography;
#if NET_2_0
namespace System.Web.Configuration {
internal static class MachineKeySectionUtils
{
static byte [] autogenerated;
static byte [] autogenerated_decrypt;
static byte[] decryption_key;
static byte[] decryption_key_192bits;
static byte[] validation_key;
internal static void AutoGenKeys ()
{
#if TARGET_J2EE
{
#else
try {
if (autogenerated == null)
autogenerated = MachineKeyRegistryStorage.Retrieve (
MachineKeyRegistryStorage.KeyType.Validation);
if (autogenerated_decrypt == null)
autogenerated_decrypt = MachineKeyRegistryStorage.Retrieve (
MachineKeyRegistryStorage.KeyType.Encryption);
} catch (Exception) {
#endif
// Fall back to old method
RandomNumberGenerator rng = RandomNumberGenerator.Create ();
if (autogenerated == null) {
autogenerated = new byte [64];
rng.GetBytes (autogenerated);
}
if (autogenerated_decrypt == null) {
autogenerated_decrypt = new byte [64];
rng.GetBytes (autogenerated_decrypt);
}
}
}
static byte ToHexValue (char c, bool high)
{
byte v;
if (c >= '0' && c <= '9')
v = (byte) (c - '0');
else if (c >= 'a' && c <= 'f')
v = (byte) (c - 'a' + 10);
else if (c >= 'A' && c <= 'F')
v = (byte) (c - 'A' + 10);
else
throw new ArgumentException ("Invalid hex character");
if (high)
v <<= 4;
return v;
}
internal static byte [] GetBytes (string key, int len)
{
byte [] result = new byte [len / 2];
for (int i = 0; i < len; i += 2)
result [i / 2] = (byte) (ToHexValue (key [i], true) + ToHexValue (key [i + 1], false));
return result;
}
static byte [] MakeKey (string key, bool decryption) //, out bool isolate)
{
if (key == null || key.StartsWith ("AutoGenerate")){
//isolate = key.IndexOf ("IsolateApps") != 1;
AutoGenKeys ();
return (decryption) ? autogenerated_decrypt : autogenerated;
}
//isolate = false;
int len = key.Length;
if (len < 40 || len > 128 || (len % 2) == 1)
throw new ArgumentException ("Invalid key length");
return GetBytes (key, len);
}
internal static void SetDecryptionKey (string n)
{
decryption_key = MakeKey (n, true); //, out isolate_decryption);
decryption_key_192bits = new byte [24];
int count = 24;
if (decryption_key.Length < 24)
count = decryption_key.Length;
Buffer.BlockCopy (decryption_key, 0, decryption_key_192bits, 0, count);
}
internal static void SetValidationKey (string n)
{
validation_key = MakeKey (n, false); //, out isolate_validation);
}
static MachineKeySection Config {
get { return WebConfigurationManager.GetSection ("system.web/machineKey") as MachineKeySection; }
}
internal static byte [] ValidationKeyBytes ()
{
return ValidationKeyBytes (Config);
}
internal static byte [] ValidationKeyBytes (MachineKeySection section)
{
if (section == null)
throw new ArgumentNullException ("section");
if (validation_key == null)
SetValidationKey (section.ValidationKey);
return validation_key;
}
internal static byte [] DecryptionKeyBytes ()
{
return DecryptionKeyBytes (Config);
}
internal static byte [] DecryptionKeyBytes (MachineKeySection section)
{
if (section == null)
throw new ArgumentNullException ("section");
if (decryption_key == null)
SetDecryptionKey (section.DecryptionKey);
return decryption_key;
}
internal static byte [] DecryptionKey192Bits ()
{
return DecryptionKey192Bits (Config);
}
internal static byte [] DecryptionKey192Bits (MachineKeySection section)
{
if (section == null)
throw new ArgumentNullException ("section");
if (decryption_key_192bits == null)
SetDecryptionKey (section.DecryptionKey);
return decryption_key_192bits;
}
}
}
#endif
@@ -23,11 +23,9 @@
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
// Copyright (C) 2004, 2010 Novell, Inc (http://www.novell.com)
//
using System.Resources;
namespace System.Web.Configuration
{
#if NET_2_0
@@ -40,7 +38,13 @@ namespace System.Web.Configuration
MD5 = 0,
SHA1 = 1,
TripleDES = 2,
AES = 3
AES = 3,
#if NET_4_0
HMACSHA256 = 4,
HMACSHA384 = 5,
HMACSHA512 = 6,
Custom = 7
#endif
}
}
@@ -3,8 +3,9 @@
//
// Authors:
// Chris Toshok ([email protected])
// Sebastien Pouliot <[email protected]>
//
// (c) Copyright 2005 Novell, Inc (http://www.novell.com)
// Copyright (C) 2005, 2010 Novell, Inc (http://www.novell.com)
//
//
@@ -28,7 +29,6 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.ComponentModel;
using System.Configuration;
using System.Globalization;
@@ -39,40 +39,76 @@ namespace System.Web.Configuration {
public sealed class MachineKeyValidationConverter : ConfigurationConverterBase
{
#if NET_4_0
const string InvalidValue = "The enumeration value must be one of the following: SHA1, MD5, 3DES, AES, HMACSHA256, HMACSHA384, HMACSHA512.";
#else
const string InvalidValue = "The enumeration value must be one of the following: SHA1, MD5, 3DES, AES.";
#endif
public MachineKeyValidationConverter ()
{
}
public override object ConvertFrom (ITypeDescriptorContext ctx, CultureInfo ci, object data)
{
if ((string)data == "MD5")
switch ((string) data) {
case "MD5":
return MachineKeyValidation.MD5;
else if ((string)data == "SHA1")
case "SHA1":
return MachineKeyValidation.SHA1;
else if ((string)data == "3DES")
case "3DES":
return MachineKeyValidation.TripleDES;
else if ((string)data == "AES")
case "AES":
return MachineKeyValidation.AES;
else
throw new ArgumentException ("The enumeration value must be one of the following: SHA1, MD5, 3DES, AES.");
#if NET_4_0
case "HMACSHA256":
return MachineKeyValidation.HMACSHA256;
case "HMACSHA384":
return MachineKeyValidation.HMACSHA384;
case "HMACSHA512":
return MachineKeyValidation.HMACSHA512;
#endif
default:
throw new ArgumentException (InvalidValue);
}
}
public override object ConvertTo (ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type)
{
#if NET_4_0
if ((value == null) || (value.GetType () != typeof (MachineKeyValidation)))
throw new ArgumentException (InvalidValue);
#else
if (value.GetType () != typeof (MachineKeyValidation)) {
/* MS throws this exception on an invalid */
throw new FormatException ("invalid validation value");
throw new FormatException (InvalidValue);
}
#endif
MachineKeyValidation v = (MachineKeyValidation)value;
if (v == MachineKeyValidation.MD5) return "MD5";
else if (v == MachineKeyValidation.SHA1) return "SHA1";
else if (v == MachineKeyValidation.TripleDES) return "3DES";
else if (v == MachineKeyValidation.AES) return "AES";
else
switch ((MachineKeyValidation) value) {
case MachineKeyValidation.MD5:
return "MD5";
case MachineKeyValidation.SHA1:
return "SHA1";
case MachineKeyValidation.TripleDES:
return "3DES";
case MachineKeyValidation.AES:
return "AES";
#if NET_4_0
case MachineKeyValidation.HMACSHA256:
return "HMACSHA256";
case MachineKeyValidation.HMACSHA384:
return "HMACSHA384";
case MachineKeyValidation.HMACSHA512:
return "HMACSHA512";
default:
// includes MachineKeyValidation.Custom
throw new ArgumentException (InvalidValue);
#else
default:
/* MS throws this exception on an invalid */
throw new FormatException ("invalid validation value");
throw new FormatException (InvalidValue);
#endif
}
}
}
}
@@ -63,6 +63,7 @@ namespace System.Web.Configuration {
}
const int SAVE_LOCATIONS_CHECK_INTERVAL = 6000; // milliseconds
const int SECTION_CACHE_LOCK_TIMEOUT = 200; // milliseconds
static readonly char[] pathTrimChars = { '/' };
static readonly object suppressAppReloadLock = new object ();
@@ -585,8 +586,9 @@ namespace System.Web.Configuration {
HttpContext ctx = HttpContext.Current;
HttpRequest req = ctx != null ? ctx.Request : null;
string physPath = req != null ? VirtualPathUtility.AppendTrailingSlash (MapPath (req, path)) : null;
string appDomainPath = HttpRuntime.AppDomainAppPath;
if (physPath != null && !physPath.StartsWith (HttpRuntime.AppDomainAppPath, StringComparison.Ordinal))
if (physPath != null && appDomainPath != null && !physPath.StartsWith (appDomainPath, StringComparison.Ordinal))
inAnotherApp = true;
string dir;
@@ -685,19 +687,29 @@ namespace System.Web.Configuration {
object cachedSection;
try {
sectionCacheLock.EnterUpgradeableReadLock ();
if (!sectionCacheLock.TryEnterUpgradeableReadLock (SECTION_CACHE_LOCK_TIMEOUT))
return;
if (sectionCache.TryGetValue (key, out cachedSection) && cachedSection != null)
return;
try {
sectionCacheLock.EnterWriteLock ();
if (!sectionCacheLock.TryEnterWriteLock (SECTION_CACHE_LOCK_TIMEOUT))
return;
sectionCache.Add (key, section);
} finally {
sectionCacheLock.ExitWriteLock ();
try {
sectionCacheLock.ExitWriteLock ();
} catch (SynchronizationLockException) {
// we can ignore it here
}
}
} finally {
sectionCacheLock.ExitUpgradeableReadLock ();
try {
sectionCacheLock.ExitUpgradeableReadLock ();
} catch (SynchronizationLockException) {
// we can ignore it here
}
}
}
@@ -34,10 +34,10 @@ using System.Reflection;
using System.IO;
using System.Resources;
using System.Collections;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Configuration;
using System.Web.Util;
namespace System.Web.Handlers {
#if SYSTEM_WEB_EXTENSIONS
@@ -58,11 +58,6 @@ namespace System.Web.Handlers {
const char QueryParamSeparator = '&';
static readonly Hashtable _embeddedResources = Hashtable.Synchronized (new Hashtable ());
#if SYSTEM_WEB_EXTENSIONS
static ScriptResourceHandler () {
MachineKeySectionUtils.AutoGenKeys ();
}
#endif
static void InitEmbeddedResourcesUrls (Assembly assembly, Hashtable hashtable)
{
@@ -93,67 +88,25 @@ namespace System.Web.Handlers {
}
#endif
static string GetHexString (byte [] bytes)
{
const int letterPart = 55;
const int numberPart = 48;
char [] result = new char [bytes.Length * 2];
for (int i = 0; i < bytes.Length; i++) {
int tmp = (int) bytes [i];
int second = tmp & 15;
int first = (tmp >> 4) & 15;
result [(i * 2)] = (char) (first > 9 ? letterPart + first : numberPart + first);
result [(i * 2) + 1] = (char) (second > 9 ? letterPart + second : numberPart + second);
}
return new string (result);
}
static byte[] GetEncryptionKey ()
{
#if NET_2_0
return MachineKeySectionUtils.DecryptionKey192Bits ();
#else
MachineKeyConfig config = HttpContext.GetAppConfig ("system.web/machineKey") as MachineKeyConfig;
return config.DecryptionKey192Bits;
#endif
}
static byte[] GetBytes (string val)
{
#if NET_2_0
return MachineKeySectionUtils.GetBytes (val, val.Length);
#else
return MachineKeyConfig.GetBytes (val, val.Length);
#endif
}
static byte [] init_vector = { 0xD, 0xE, 0xA, 0xD, 0xB, 0xE, 0xE, 0xF };
static string EncryptAssemblyResource (string asmName, string resName)
{
byte[] key = GetEncryptionKey ();
byte[] bytes = Encoding.UTF8.GetBytes (String.Concat (asmName, ";", resName));
string result;
ICryptoTransform encryptor = TripleDES.Create ().CreateEncryptor (key, init_vector);
result = GetHexString (encryptor.TransformFinalBlock (bytes, 0, bytes.Length));
bytes = null;
return String.Concat ("d=", result.ToLowerInvariant ());
bytes = MachineKeySectionUtils.Encrypt (MachineKeySection.Config, bytes);
return Convert.ToBase64String (bytes);
}
static void DecryptAssemblyResource (string val, out string asmName, out string resName)
{
byte[] key = GetEncryptionKey ();
byte[] bytes = GetBytes (val);
byte[] result;
byte[] bytes = Convert.FromBase64String (val);
asmName = null;
resName = null;
ICryptoTransform decryptor = TripleDES.Create ().CreateDecryptor (key, init_vector);
result = decryptor.TransformFinalBlock (bytes, 0, bytes.Length);
byte[] result = MachineKeySectionUtils.Decrypt (MachineKeySection.Config, bytes);
bytes = null;
// null will be returned if, for any reason, decryption fails
if (result == null)
return;
string data = Encoding.UTF8.GetString (result);
result = null;
@@ -201,7 +154,7 @@ namespace System.Web.Handlers {
if (apath != String.Empty)
atime = String.Concat (QueryParamSeparator, "t=", File.GetLastWriteTimeUtc (apath).Ticks);
#endif
string href = HandlerFileName + "?" + EncryptAssemblyResource (aname, resourceName) + atime + extra;
string href = HandlerFileName + "?d=" + EncryptAssemblyResource (aname, resourceName) + atime + extra;
HttpContext ctx = HttpContext.Current;
if (ctx != null && ctx.Request != null) {
@@ -225,7 +178,13 @@ namespace System.Web.Handlers {
string asmName;
Assembly assembly;
DecryptAssemblyResource (request.QueryString ["d"], out asmName, out resourceName);
// val is URL-decoded, which means every + has been replaced with ' ', we
// need to revert that or the base64 conversion will fail.
string d = request.QueryString ["d"];
if (!String.IsNullOrEmpty (d))
d = d.Replace (' ', '+');
DecryptAssemblyResource (d, out asmName, out resourceName);
if (resourceName == null)
throw new HttpException (404, "No resource name given");
@@ -45,9 +45,6 @@ namespace System.Web.Security
[AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public sealed class FormsAuthentication
{
const int MD5_hash_size = 16;
const int SHA1_hash_size = 20;
static string authConfigPath = "system.web/authentication";
static string machineKeyConfigPath = "system.web/machineKey";
#if TARGET_J2EE
@@ -56,7 +53,6 @@ namespace System.Web.Security
const string Forms_cookiePath = "Forms.cookiePath";
const string Forms_timeout = "Forms.timeout";
const string Forms_protection = "Forms.protection";
const string Forms_init_vector = "Forms.init_vector";
static bool initialized
{
get {
@@ -88,11 +84,6 @@ namespace System.Web.Security
get { return (FormsProtectionEnum) AppDomain.CurrentDomain.GetData (Forms_protection); }
set { AppDomain.CurrentDomain.SetData (Forms_protection, value); }
}
static byte [] init_vector
{
get { return (byte []) AppDomain.CurrentDomain.GetData (Forms_init_vector); }
set { AppDomain.CurrentDomain.SetData (Forms_init_vector, value); }
}
static object locker = new object ();
#else
static bool initialized;
@@ -101,7 +92,6 @@ namespace System.Web.Security
static int timeout;
static FormsProtectionEnum protection;
static object locker = new object ();
static byte [] init_vector; // initialization vector used for 3DES
#endif
#if NET_1_1
#if TARGET_J2EE
@@ -230,25 +220,13 @@ namespace System.Web.Security
password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5);
break;
case FormsAuthPasswordFormat.SHA1:
password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5);
password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.SHA1);
break;
}
return String.Compare (password, stored, caseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0;
}
#if NET_2_0
static byte [] GetDecryptionKey (MachineKeySection config)
{
return MachineKeySectionUtils.DecryptionKey192Bits (config);
}
#else
static byte [] GetDecryptionKey (MachineKeyConfig config)
{
return config.DecryptionKey192Bits;
}
#endif
static FormsAuthenticationTicket Decrypt2 (byte [] bytes)
{
if (protection == FormsProtectionEnum.None)
@@ -259,59 +237,14 @@ namespace System.Web.Security
#else
MachineKeyConfig config = HttpContext.GetAppConfig (machineKeyConfigPath) as MachineKeyConfig;
#endif
bool all = (protection == FormsProtectionEnum.All);
byte [] result = bytes;
if (all || protection == FormsProtectionEnum.Encryption) {
ICryptoTransform decryptor;
decryptor = TripleDES.Create ().CreateDecryptor (GetDecryptionKey (config), init_vector);
result = decryptor.TransformFinalBlock (bytes, 0, bytes.Length);
bytes = null;
}
if (all || protection == FormsProtectionEnum.Validation) {
int count;
MachineKeyValidation validationType;
#if NET_2_0
validationType = config.Validation;
#else
validationType = config.ValidationType;
#endif
if (validationType == MachineKeyValidation.MD5)
count = MD5_hash_size;
else
count = SHA1_hash_size; // 3DES and SHA1
#if NET_2_0
byte [] vk = MachineKeySectionUtils.ValidationKeyBytes (config);
#else
byte [] vk = config.ValidationKey;
#endif
byte [] mix = new byte [result.Length - count + vk.Length];
Buffer.BlockCopy (result, 0, mix, 0, result.Length - count);
Buffer.BlockCopy (vk, 0, mix, result.Length - count, vk.Length);
byte [] hash = null;
switch (validationType) {
case MachineKeyValidation.MD5:
hash = MD5.Create ().ComputeHash (mix);
break;
// From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
case MachineKeyValidation.TripleDES:
case MachineKeyValidation.SHA1:
hash = SHA1.Create ().ComputeHash (mix);
break;
}
if (result.Length < count)
throw new ArgumentException ("Error validating ticket (length).", "encryptedTicket");
int i, k;
for (i = result.Length - count, k = 0; k < count; i++, k++) {
if (result [i] != hash [k])
throw new ArgumentException ("Error validating ticket.", "encryptedTicket");
}
byte [] result = null;
if (protection == FormsProtectionEnum.All) {
result = MachineKeySectionUtils.VerifyDecrypt (config, bytes);
} else if (protection == FormsProtectionEnum.Encryption) {
result = MachineKeySectionUtils.Decrypt (config, bytes);
} else if (protection == FormsProtectionEnum.Validation) {
result = MachineKeySectionUtils.Verify (config, bytes);
}
return FormsAuthenticationTicket.FromByteArray (result);
@@ -325,11 +258,8 @@ namespace System.Web.Security
Initialize ();
FormsAuthenticationTicket ticket;
#if NET_2_0
byte [] bytes = MachineKeySectionUtils.GetBytes (encryptedTicket, encryptedTicket.Length);
#else
byte [] bytes = MachineKeyConfig.GetBytes (encryptedTicket, encryptedTicket.Length);
#endif
byte [] bytes = Convert.FromBase64String (encryptedTicket);
try {
ticket = Decrypt2 (bytes);
} catch (Exception) {
@@ -347,57 +277,23 @@ namespace System.Web.Security
Initialize ();
byte [] ticket_bytes = ticket.ToByteArray ();
if (protection == FormsProtectionEnum.None)
return GetHexString (ticket_bytes);
return Convert.ToBase64String (ticket_bytes);
byte [] result = ticket_bytes;
byte [] result = null;
#if NET_2_0
MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection (machineKeyConfigPath);
#else
MachineKeyConfig config = HttpContext.GetAppConfig (machineKeyConfigPath) as MachineKeyConfig;
#endif
bool all = (protection == FormsProtectionEnum.All);
if (all || protection == FormsProtectionEnum.Validation) {
byte [] valid_bytes = null;
#if NET_2_0
byte [] vk = MachineKeySectionUtils.ValidationKeyBytes (config);
#else
byte [] vk = config.ValidationKey;
#endif
byte [] mix = new byte [ticket_bytes.Length + vk.Length];
Buffer.BlockCopy (ticket_bytes, 0, mix, 0, ticket_bytes.Length);
Buffer.BlockCopy (vk, 0, mix, result.Length, vk.Length);
switch (
#if NET_2_0
config.Validation
#else
config.ValidationType
#endif
) {
case MachineKeyValidation.MD5:
valid_bytes = MD5.Create ().ComputeHash (mix);
break;
// From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
case MachineKeyValidation.TripleDES:
case MachineKeyValidation.SHA1:
valid_bytes = SHA1.Create ().ComputeHash (mix);
break;
}
int tlen = ticket_bytes.Length;
int vlen = valid_bytes.Length;
result = new byte [tlen + vlen];
Buffer.BlockCopy (ticket_bytes, 0, result, 0, tlen);
Buffer.BlockCopy (valid_bytes, 0, result, tlen, vlen);
if (protection == FormsProtectionEnum.All) {
result = MachineKeySectionUtils.EncryptSign (config, ticket_bytes);
} else if (protection == FormsProtectionEnum.Encryption) {
result = MachineKeySectionUtils.Encrypt (config, ticket_bytes);
} else if (protection == FormsProtectionEnum.Validation) {
result = MachineKeySectionUtils.Sign (config, ticket_bytes);
}
if (all || protection == FormsProtectionEnum.Encryption) {
ICryptoTransform encryptor;
encryptor = TripleDES.Create ().CreateEncryptor (GetDecryptionKey (config), init_vector);
result = encryptor.TransformFinalBlock (result, 0, result.Length);
}
return GetHexString (result);
return Convert.ToBase64String (result);
}
public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie)
@@ -478,21 +374,6 @@ namespace System.Web.Security
return returnUrl;
}
static string GetHexString (byte [] bytes)
{
const int letterPart = 55;
const int numberPart = 48;
char [] result = new char [bytes.Length * 2];
for (int i = 0; i < bytes.Length; i++) {
int tmp = (int) bytes [i];
int second = tmp & 15;
int first = (tmp >> 4) & 15;
result [(i * 2)] = (char) (first > 9 ? letterPart + first : numberPart + first);
result [(i * 2) + 1] = (char) (second > 9 ? letterPart + second : numberPart + second);
}
return new string (result);
}
static string HashPasswordForStoringInConfigFile (string password, FormsAuthPasswordFormat passwordFormat)
{
if (password == null)
@@ -512,7 +393,7 @@ namespace System.Web.Security
throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
}
return GetHexString (bytes);
return MachineKeySectionUtils.GetHexString (bytes);
}
public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat)
@@ -580,16 +461,6 @@ namespace System.Web.Security
}
#endif
// IV is 8 bytes long for 3DES
init_vector = new byte [8];
int len = cookieName.Length;
for (int i = 0; i < 8; i++) {
if (i >= len)
break;
init_vector [i] = (byte) cookieName [i];
}
initialized = true;
}
}
@@ -1,5 +1,5 @@
//
// System.Web.Security.MembershipEncryptionHelper
// System.Web.Security.MembershipHelper
//
// Authors:
// Ben Maurer ([email protected])
@@ -27,10 +27,11 @@
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Configuration.Provider;
using System.Security.Cryptography;
using System.Web.Configuration;
using System.Web.Util;
namespace System.Web.Security
{
@@ -49,56 +50,32 @@ namespace System.Web.Security
get { return Membership.Providers; }
}
static SymmetricAlgorithm GetAlg ()
static SymmetricAlgorithm GetAlgorithm ()
{
MachineKeySection section = (MachineKeySection) WebConfigurationManager.GetSection ("system.web/machineKey");
MachineKeySection section = MachineKeySection.Config;
if (section.DecryptionKey.StartsWith ("AutoGenerate"))
throw new ProviderException ("You must explicitly specify a decryption key in the <machineKey> section when using encrypted passwords.");
string alg_type = section.Decryption;
if (alg_type == "Auto")
alg_type = "AES";
SymmetricAlgorithm sa = section.GetDecryptionAlgorithm ();
if (sa == null)
throw new ProviderException (String.Format ("Unsupported decryption attribute '{0}' in <machineKey> configuration section", section.Decryption));
SymmetricAlgorithm alg = null;
if (alg_type == "AES")
alg = Rijndael.Create ();
else if (alg_type == "3DES")
alg = TripleDES.Create ();
else
throw new ProviderException (String.Format ("Unsupported decryption attribute '{0}' in <machineKey> configuration section", alg_type));
alg.Key = MachineKeySectionUtils.DecryptionKey192Bits (section);
return alg;
sa.Key = section.GetDecryptionKey ();
return sa;
}
public byte [] DecryptPassword (byte [] encodedPassword)
{
using (SymmetricAlgorithm alg = GetAlg ()) {
// alg.Key is set in GetAlg based on web.config
// iv is the first part of the encodedPassword
byte [] iv = new byte [alg.IV.Length];
Array.Copy (encodedPassword, 0, iv, 0, iv.Length);
using (ICryptoTransform decryptor = alg.CreateDecryptor (alg.Key, iv)) {
return decryptor.TransformFinalBlock (encodedPassword, iv.Length, encodedPassword.Length - iv.Length);
}
using (SymmetricAlgorithm sa = GetAlgorithm ()) {
return MachineKeySectionUtils.Decrypt (sa, encodedPassword, 0, encodedPassword.Length);
}
}
public byte[] EncryptPassword (byte[] password)
{
using (SymmetricAlgorithm alg = GetAlg ()) {
// alg.Key is set in GetAlg based on web.config
// alg.IV is randomly set (default behavior) and perfect for our needs
byte [] iv = alg.IV;
using (ICryptoTransform encryptor = alg.CreateEncryptor (alg.Key, iv)) {
byte [] encrypted = encryptor.TransformFinalBlock (password, 0, password.Length);
byte [] output = new byte [iv.Length + encrypted.Length];
// note: the IV can be public, however it should not be based on the password
Array.Copy (iv, 0, output, 0, iv.Length);
Array.Copy (encrypted, 0, output, iv.Length, encrypted.Length);
return output;
}
using (SymmetricAlgorithm sa = GetAlgorithm ()) {
return MachineKeySectionUtils.Encrypt (sa, password);
}
}
}
@@ -29,10 +29,10 @@
//
using System.Collections.Specialized;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Security.Principal;
using System.Web.Configuration;
using System.Web.Util;
using System.IO;
using System.Text;
@@ -146,42 +146,16 @@ namespace System.Web.Security {
CookieProtection cookieProtection = RoleManagerConfig.CookieProtection;
if (cookieProtection == CookieProtection.None)
return GetBase64FromBytes (ticket.GetBuffer (), 0, (int) ticket.Position);
if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Validation) {
byte [] hashBytes = null;
byte [] validationBytes = MachineKeySectionUtils.ValidationKeyBytes (MachineConfig);
writer.Write (validationBytes);
switch (MachineConfig.Validation) {
case MachineKeyValidation.MD5:
hashBytes = MD5.Create ().ComputeHash (ticket.GetBuffer (), 0, (int) ticket.Position);
break;
case MachineKeyValidation.TripleDES:
case MachineKeyValidation.SHA1:
hashBytes = SHA1.Create ().ComputeHash (ticket.GetBuffer (), 0, (int) ticket.Position);
break;
}
writer.Seek (-validationBytes.Length, SeekOrigin.Current);
writer.Write (hashBytes);
byte[] ticket_data = ticket.GetBuffer ();
if (cookieProtection == CookieProtection.All) {
ticket_data = MachineKeySectionUtils.EncryptSign (MachineConfig, ticket_data);
} else if (cookieProtection == CookieProtection.Encryption) {
ticket_data = MachineKeySectionUtils.Encrypt (MachineConfig, ticket_data);
} else if (cookieProtection == CookieProtection.Validation) {
ticket_data = MachineKeySectionUtils.Sign (MachineConfig, ticket_data);
}
byte [] ticketBytes = null;
if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Encryption) {
ICryptoTransform enc;
enc = TripleDES.Create ().CreateEncryptor (MachineKeySectionUtils.DecryptionKey192Bits (MachineConfig),
InitVector);
ticketBytes = enc.TransformFinalBlock (ticket.GetBuffer (), 0, (int) ticket.Position);
}
if (ticketBytes == null)
return GetBase64FromBytes (ticket.GetBuffer (), 0, (int) ticket.Position);
else
return GetBase64FromBytes (ticketBytes, 0, ticketBytes.Length);
return GetBase64FromBytes (ticket_data, 0, ticket_data.Length);
}
void DecryptTicket (string encryptedTicket)
@@ -193,44 +167,17 @@ namespace System.Web.Security {
byte [] decryptedTicketBytes = null;
CookieProtection cookieProtection = RoleManagerConfig.CookieProtection;
if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Encryption) {
ICryptoTransform decryptor;
decryptor = TripleDES.Create ().CreateDecryptor (
MachineKeySectionUtils.DecryptionKey192Bits (MachineConfig),
InitVector);
decryptedTicketBytes = decryptor.TransformFinalBlock (ticketBytes, 0, ticketBytes.Length);
if (cookieProtection == CookieProtection.All) {
decryptedTicketBytes = MachineKeySectionUtils.VerifyDecrypt (MachineConfig, ticketBytes);
} else if (cookieProtection == CookieProtection.Encryption) {
decryptedTicketBytes = MachineKeySectionUtils.Decrypt (MachineConfig, ticketBytes);
} else if (cookieProtection == CookieProtection.Validation) {
decryptedTicketBytes = MachineKeySectionUtils.Verify (MachineConfig, ticketBytes);
}
else
decryptedTicketBytes = ticketBytes;
if (cookieProtection == CookieProtection.All || cookieProtection == CookieProtection.Validation) {
byte [] validationBytes = MachineKeySectionUtils.ValidationKeyBytes (MachineConfig);
byte [] rolesWithValidationBytes = null;
byte [] tmpValidation = null;
int hashSize = (MachineConfig.Validation == MachineKeyValidation.MD5) ? 16 : 20; //md5 is 16 bytes, sha1 is 20 bytes
rolesWithValidationBytes = new byte [decryptedTicketBytes.Length - hashSize + validationBytes.Length];
Buffer.BlockCopy (decryptedTicketBytes, 0, rolesWithValidationBytes, 0, decryptedTicketBytes.Length - hashSize);
Buffer.BlockCopy (validationBytes, 0, rolesWithValidationBytes, decryptedTicketBytes.Length - hashSize, validationBytes.Length);
switch (MachineConfig.Validation) {
case MachineKeyValidation.MD5:
tmpValidation = MD5.Create ().ComputeHash (rolesWithValidationBytes);
break;
case MachineKeyValidation.TripleDES:
case MachineKeyValidation.SHA1:
tmpValidation = SHA1.Create ().ComputeHash (rolesWithValidationBytes);
break;
}
for (int i = 0; i < tmpValidation.Length; i++) {
if (i >= decryptedTicketBytes.Length ||
tmpValidation [i] != decryptedTicketBytes [i + decryptedTicketBytes.Length - hashSize])
throw new HttpException ("ticket validation failed");
}
}
if (decryptedTicketBytes == null)
throw new HttpException ("ticket validation failed");
MemoryStream ticket = new MemoryStream (decryptedTicketBytes);
BinaryReader reader = new BinaryReader (ticket);
@@ -276,11 +223,6 @@ namespace System.Web.Security {
_cachedRoles.Add (r, r);
}
byte [] InitVector
{
get { return new byte [] { 1, 2, 3, 4, 5, 6, 7, 8 }; }
}
public bool CachedListChanged {
get { return _listChanged; }
}
@@ -1048,11 +1048,22 @@ namespace System.Web.Security {
MembershipSection section = (MembershipSection) WebConfigurationManager.GetSection ("system.web/membership");
string alg_type = section.HashAlgorithmType;
if (alg_type == "") {
MachineKeySection keysection = (MachineKeySection) WebConfigurationManager.GetSection ("system.web/machineKey");
alg_type = keysection.Validation.ToString ();
if (alg_type.Length == 0) {
alg_type = MachineKeySection.Config.Validation.ToString ();
#if NET_4_0
// support new (4.0) custom algorithms
if (alg_type.StartsWith ("alg:"))
alg_type = alg_type.Substring (4);
#endif
}
using (HashAlgorithm hash = HashAlgorithm.Create (alg_type)) {
#if NET_4_0
// for compatibility (with 2.0) we'll allow MD5 and SHA1 not to map to HMACMD5 and HMACSHA1
// but that won't work with new (4.0) algorithms, like HMACSHA256|384|512 or custom, won't work without using the key
KeyedHashAlgorithm kha = (hash as KeyedHashAlgorithm);
if (kha != null)
kha.Key = MachineKeySection.Config.GetValidationKey ();
#endif
hash.TransformFinalBlock (hashBytes, 0, hashBytes.Length);
return Convert.ToBase64String (hash.Hash);
}
@@ -1432,7 +1432,7 @@ namespace System.Web.Security
case MembershipPasswordFormat.Hashed:
HMACSHA1 hash = new HMACSHA1();
if (machineKeyIsAutoGenerated)
hash.Key = MachineKeySectionUtils.ValidationKeyBytes ();
hash.Key = MachineKeySection.Config.GetValidationKey ();
else
hash.Key = HexToByte(m_MachineKey.ValidationKey);
encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
@@ -28,15 +28,12 @@
using System.Text;
using System.Security.Cryptography;
using System.Web.Util;
namespace System.Web.SessionState {
internal class SessionId {
static char [] allowed = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'A', 'B',
'C', 'D', 'E', 'F' };
internal const int IdLength = 24;
const int half_len = IdLength / 2;
static RandomNumberGenerator rng = RandomNumberGenerator.Create ();
@@ -48,25 +45,9 @@ namespace System.Web.SessionState {
lock (rng) {
rng.GetBytes (key);
}
return Encode (key);
return MachineKeySectionUtils.GetHexString (key);
}
internal static string Encode (byte[] key)
{
if (key == null)
throw new ArgumentNullException ("key");
if (key.Length != half_len)
throw new ArgumentException (String.Concat ("key must be ", half_len.ToString (), " bytes long."));
// Just a standard hex conversion
char[] res = new char [IdLength];
for (int i=0; i < half_len; i++) {
int b = key [i];
res [i * 2] = allowed [b >> 4];
res [(i * 2) + 1] = allowed [b & 0xF];
}
return new String (res);
}
#if !NET_2_0
internal static string Lookup (HttpRequest request, bool cookieless)
{
+12 -2
View File
@@ -1100,8 +1100,18 @@ namespace System.Web.UI
return null;
int separatorIdx = id.IndexOf (IdSeparator, pathOffset);
if (separatorIdx == -1)
return LookForControlByName (id.Substring (pathOffset));
if (separatorIdx == -1) {
if (pathOffset == 0) {
namingContainer = NamingContainer;
if (namingContainer != null) {
Control ctl = namingContainer.FindControl (id);
if (ctl != null)
return ctl;
}
}
return LookForControlByName (pathOffset > 0 ? id.Substring (pathOffset) : id);
}
string idfound = id.Substring (pathOffset, separatorIdx - pathOffset);
namingContainer = LookForControlByName (idfound);
@@ -28,10 +28,11 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Configuration;
using System.IO;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Web.Util;
namespace System.Web.UI {
@@ -46,42 +47,58 @@ namespace System.Web.UI {
osf = new ObjectStateFormatter ();
}
public LosFormatter (bool enableMac, string macKeyModifier) : this (enableMac, Convert.FromBase64String (macKeyModifier))
public LosFormatter (bool enableMac, string macKeyModifier) : this (enableMac, String.IsNullOrEmpty (macKeyModifier) ? null : Encoding.ASCII.GetBytes (macKeyModifier))
{
}
[MonoTODO]
public LosFormatter (bool enableMac, byte[] macKeyModifier)
{
if (enableMac)
osf = new ObjectStateFormatter (macKeyModifier);
else
osf = new ObjectStateFormatter ();
osf = new ObjectStateFormatter ();
if (enableMac && (macKeyModifier != null)) {
SetMacKey (macKeyModifier);
}
}
private void SetMacKey (byte[] macKeyModifier)
{
try {
osf.Section.ValidationKey = MachineKeySectionUtils.GetHexString (macKeyModifier);
}
catch (ArgumentException) {
}
catch (ConfigurationErrorsException) {
// bad key (e.g. size), default key will be used
}
}
public object Deserialize (Stream stream)
{
if (stream == null)
throw new ArgumentNullException ("stream");
#if NET_4_0
using (StreamReader sr = new StreamReader (stream)) {
return Deserialize (sr.ReadToEnd ());
}
#else
long streamLength = -1;
if (stream.CanSeek)
streamLength = stream.Length;
byte [] bytes = new byte [streamLength >= 0 ? streamLength : 2048];
MemoryStream ms = null;
if (streamLength != -1 && (stream is MemoryStream) && stream.Position == 0) {
// We save allocating a new stream and reading in this case.
ms = (MemoryStream) stream;
} else {
byte [] bytes = new byte [streamLength >= 0 ? streamLength : 2048];
ms = new MemoryStream ();
int n;
while ((n = stream.Read (bytes, 0, bytes.Length)) > 0)
ms.Write (bytes, 0, n);
streamLength = ms.Length;
}
string b64 = Encoding.ASCII.GetString (ms.GetBuffer (),
0, (int) streamLength);
return Deserialize (b64);
#endif
}
public object Deserialize (TextReader input)
@@ -109,7 +126,10 @@ namespace System.Web.UI {
{
if (stream == null)
throw new ArgumentNullException ("stream");
#if NET_4_0
if (!stream.CanSeek)
throw new NotSupportedException ();
#endif
string b64 = SerializeToBase64 (value);
byte [] bytes = Encoding.ASCII.GetBytes (b64);
stream.Write (bytes, 0, bytes.Length);
@@ -44,16 +44,16 @@ using System.Text;
using System.Web.UI.WebControls;
using System.Web.Util;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Web.Configuration;
namespace System.Web.UI
{
public sealed class ObjectStateFormatter : IFormatter, IStateFormatter
{
const ushort SERIALIZED_STREAM_MAGIC = 0x01FF;
Page page;
HashAlgorithm algo;
byte [] vkey;
MachineKeySection section;
public ObjectStateFormatter ()
{
@@ -64,65 +64,40 @@ namespace System.Web.UI
this.page = page;
}
internal ObjectStateFormatter (byte [] vkey)
{
this.vkey = vkey;
}
internal bool EnableMac {
bool EnableMac {
get {
if (page == null) {
if (vkey == null)
return false;
return true;
} else
return page.EnableViewStateMac;
return (page == null) ? (section != null) : page.EnableViewStateMac;
}
}
internal HashAlgorithm GetAlgo ()
{
if (algo != null)
return algo;
if (!EnableMac)
return null;
byte [] algoKey;
if (page != null) {
MachineKeySection mconfig = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection ("system.web/machineKey");
algoKey = MachineKeySectionUtils.ValidationKeyBytes (mconfig);
} else
algoKey = vkey;
algo = new HMACSHA1 (algoKey);
return algo;
}
static int ValidateInput (HashAlgorithm algo, byte [] data, int offset, int size)
{
if (algo == null)
throw new HttpException ("Unable to validate data.");
int hash_size = algo.HashSize / 8;
if (size != 0 && size < hash_size)
throw new HttpException ("Unable to validate data.");
int data_length = size - hash_size;
MemoryStream data_stream = new MemoryStream (data, offset, data_length, false, false);
byte [] hash = algo.ComputeHash (data_stream);
for (int i = 0; i < hash_size; i++) {
if (hash [i] != data [data_length + i])
throw new HttpException ("Unable to validate data.");
bool NeedViewStateEncryption {
get {
return (page == null) ? false : page.NeedViewStateEncryption;
}
return data_length;
}
internal MachineKeySection Section {
get {
if (section == null)
section = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection ("system.web/machineKey");
return section;
}
set {
section = value;
}
}
public object Deserialize (Stream inputStream)
{
if (inputStream == null)
throw new ArgumentNullException ("inputStream");
return DeserializeObject (new BinaryReader (inputStream));
BinaryReader reader = new BinaryReader (inputStream);
short magic = reader.ReadInt16 ();
if (magic != SERIALIZED_STREAM_MAGIC)
throw new ArgumentException ("The serialized data is invalid");
return DeserializeObject (reader);
}
public object Deserialize (string inputString)
@@ -132,45 +107,50 @@ namespace System.Web.UI
if (inputString.Length == 0)
throw new ArgumentNullException ("inputString");
byte [] buffer = Convert.FromBase64String (inputString);
int length;
if (buffer == null || (length = buffer.Length) == 0)
byte [] data = Convert.FromBase64String (inputString);
if (data == null || (data.Length) == 0)
throw new ArgumentNullException ("inputString");
if (page != null && EnableMac)
length = ValidateInput (GetAlgo (), buffer, 0, length);
bool isEncrypted = ((int)buffer [--length] == 1)? true : false;
Stream ms = new MemoryStream (buffer, 0, length, false, false);
if (isEncrypted)
ms = new CryptoStream (ms, page.GetCryptoTransform (CryptoStreamMode.Read), CryptoStreamMode.Read);
return Deserialize (ms);
if (NeedViewStateEncryption) {
if (EnableMac) {
data = MachineKeySectionUtils.VerifyDecrypt (Section, data);
} else {
data = MachineKeySectionUtils.Decrypt (Section, data);
}
} else if (EnableMac) {
data = MachineKeySectionUtils.Verify (Section, data);
}
if (data == null)
throw new HttpException ("Unable to validate data.");
using (MemoryStream ms = new MemoryStream (data)) {
return Deserialize (ms);
}
}
public string Serialize (object stateGraph)
{
if (stateGraph == null)
return String.Empty;
MemoryStream ms = new MemoryStream ();
Stream output = ms;
bool needEncryption = page == null ? false : page.NeedViewStateEncryption;
if (needEncryption){
output = new CryptoStream (output, page.GetCryptoTransform (CryptoStreamMode.Write), CryptoStreamMode.Write);
byte[] data = null;
using (MemoryStream ms = new MemoryStream ()) {
Serialize (ms, stateGraph);
data = ms.GetBuffer ();
}
Serialize (output, stateGraph);
ms.WriteByte((byte)(needEncryption? 1 : 0));
#if TRACE
ms.WriteTo (File.OpenWrite (Path.GetTempFileName ()));
#endif
if (EnableMac && ms.Length > 0) {
HashAlgorithm algo = GetAlgo ();
if (algo != null) {
byte [] hash = algo.ComputeHash (ms.GetBuffer (), 0, (int) ms.Length);
ms.Write (hash, 0, hash.Length);
if (NeedViewStateEncryption) {
if (EnableMac) {
data = MachineKeySectionUtils.EncryptSign (Section, data);
} else {
data = MachineKeySectionUtils.Encrypt (Section, data);
}
} else if (EnableMac) {
data = MachineKeySectionUtils.Sign (Section, data);
}
return Convert.ToBase64String (ms.GetBuffer (), 0, (int) ms.Length);
return Convert.ToBase64String (data, 0, data.Length);
}
public void Serialize (Stream outputStream, object stateGraph)
@@ -181,7 +161,10 @@ namespace System.Web.UI
if (stateGraph == null)
throw new ArgumentNullException ("stateGraph");
SerializeValue (new BinaryWriter (outputStream), stateGraph);
BinaryWriter writer = new BinaryWriter (outputStream);
writer.Write (SERIALIZED_STREAM_MAGIC);
SerializeValue (writer, stateGraph);
}
void SerializeValue (BinaryWriter w, object o)
@@ -39,7 +39,6 @@ using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.IO;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
@@ -2375,74 +2374,6 @@ public partial class Page : TemplateControl, IHttpHandler
controlRegisteredForViewStateEncryption = true;
}
static byte [] AES_IV = null;
static byte [] TripleDES_IV = null;
static object locker = new object ();
static bool isEncryptionInitialized = false;
static void InitializeEncryption ()
{
if (isEncryptionInitialized)
return;
lock (locker) {
if (isEncryptionInitialized)
return;
string iv_string = "0BA48A9E-736D-40f8-954B-B2F62241F282";
AES_IV = new byte [16];
TripleDES_IV = new byte [8];
int i;
for (i = 0; i < AES_IV.Length; i++) {
AES_IV [i] = (byte) iv_string [i];
}
for (i = 0; i < TripleDES_IV.Length; i++) {
TripleDES_IV [i] = (byte) iv_string [i];
}
isEncryptionInitialized = true;
}
}
internal ICryptoTransform GetCryptoTransform (CryptoStreamMode cryptoStreamMode)
{
ICryptoTransform transform = null;
MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetSection (machineKeyConfigPath);
byte [] vk = MachineKeySectionUtils.ValidationKeyBytes (config);
switch (config.Validation) {
case MachineKeyValidation.SHA1:
transform = SHA1.Create ();
break;
case MachineKeyValidation.MD5:
transform = MD5.Create ();
break;
case MachineKeyValidation.AES:
InitializeEncryption ();
if (cryptoStreamMode == CryptoStreamMode.Read){
transform = Rijndael.Create().CreateDecryptor(vk, AES_IV);
} else {
transform = Rijndael.Create().CreateEncryptor(vk, AES_IV);
}
break;
case MachineKeyValidation.TripleDES:
InitializeEncryption ();
if (cryptoStreamMode == CryptoStreamMode.Read){
transform = TripleDES.Create().CreateDecryptor(vk, TripleDES_IV);
} else {
transform = TripleDES.Create().CreateEncryptor(vk, TripleDES_IV);
}
break;
}
return transform;
}
internal bool NeedViewStateEncryption {
get {
return (ViewStateEncryptionMode == ViewStateEncryptionMode.Always ||
@@ -404,6 +404,7 @@ namespace System.Web.UI
value = GetString (atts, "MasterPageFile", masterPage != null ? masterPage.Value : null);
if (!String.IsNullOrEmpty (value)) {
if (!BaseParser.IsExpression (value)) {
value = System.Web.VirtualPathUtility.Combine(BaseVirtualDir, value);
if (!HostingEnvironment.VirtualPathProvider.FileExists (value))
ThrowParseFileNotFound (value);
AddDependency (value);
@@ -0,0 +1,315 @@
//
// System.Web.Util.MachineKeySectionUtils
//
// Authors:
// Chris Toshok ([email protected])
// Sebastien Pouliot <[email protected]>
//
// (c) Copyright 2005, 2010 Novell, Inc (http://www.novell.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.ComponentModel;
using System.Configuration;
using System.Configuration.Provider;
using System.Security.Cryptography;
using System.Text;
using System.Web.Configuration;
#if NET_2_0
namespace System.Web.Util {
static class MachineKeySectionUtils {
static byte ToHexValue (char c, bool high)
{
byte v;
if (c >= '0' && c <= '9')
v = (byte) (c - '0');
else if (c >= 'a' && c <= 'f')
v = (byte) (c - 'a' + 10);
else if (c >= 'A' && c <= 'F')
v = (byte) (c - 'A' + 10);
else
throw new ArgumentException ("Invalid hex character");
if (high)
v <<= 4;
return v;
}
internal static byte [] GetBytes (string key, int len)
{
byte [] result = new byte [len / 2];
for (int i = 0; i < len; i += 2)
result [i / 2] = (byte) (ToHexValue (key [i], true) + ToHexValue (key [i + 1], false));
return result;
}
static public string GetHexString (byte [] bytes)
{
StringBuilder sb = new StringBuilder (bytes.Length * 2);
int letterPart = 55;
const int numberPart = 48;
for (int i = 0; i < bytes.Length; i++) {
int tmp = (int) bytes [i];
int second = tmp & 15;
int first = (tmp >> 4) & 15;
sb.Append ((char) (first > 9 ? letterPart + first : numberPart + first));
sb.Append ((char) (second > 9 ? letterPart + second : numberPart + second));
}
return sb.ToString ();
}
// decryption="Auto" [Auto | DES | 3DES | AES | alg:algorithm_name]
// http://msdn.microsoft.com/en-us/library/w8h3skw9.aspx
public static SymmetricAlgorithm GetDecryptionAlgorithm (string name)
{
SymmetricAlgorithm sa = null;
switch (name) {
case "AES":
case "Auto":
sa = Rijndael.Create ();
break;
case "DES":
sa = DES.Create ();
break;
case "3DES":
sa = TripleDES.Create ();
break;
default:
#if NET_4_0
if (name.StartsWith ("alg:"))
sa = SymmetricAlgorithm.Create (name.Substring (4));
else
#endif
throw new ConfigurationErrorsException ();
break;
}
return sa;
}
// validation="HMACSHA256" [SHA1 | MD5 | 3DES | AES | HMACSHA256 | HMACSHA384 | HMACSHA512 | alg:algorithm_name]
// [1] http://msdn.microsoft.com/en-us/library/system.web.configuration.machinekeyvalidation.aspx
// [2] http://msdn.microsoft.com/en-us/library/w8h3skw9.aspx
public static KeyedHashAlgorithm GetValidationAlgorithm (MachineKeySection section)
{
KeyedHashAlgorithm kha = null;
switch (section.Validation) {
case MachineKeyValidation.MD5:
kha = new HMACMD5 ();
break;
case MachineKeyValidation.AES: // see link [1] or [2]
case MachineKeyValidation.TripleDES: // see link [2]
case MachineKeyValidation.SHA1:
kha = new HMACSHA1 ();
break;
#if NET_4_0
case MachineKeyValidation.HMACSHA256:
kha = new HMACSHA256 ();
break;
case MachineKeyValidation.HMACSHA384:
kha = new HMACSHA384 ();
break;
case MachineKeyValidation.HMACSHA512:
kha = new HMACSHA512 ();
break;
case MachineKeyValidation.Custom:
// remove the "alg:" from the start of the string
string algo = section.ValidationAlgorithm;
if (algo.StartsWith ("alg:"))
kha = KeyedHashAlgorithm.Create (algo.Substring (4));
break;
#endif
}
return kha;
}
// helpers to ease unit testing of the cryptographic code
#if TEST
static byte [] decryption_key;
static byte [] validation_key;
static SymmetricAlgorithm GetDecryptionAlgorithm (MachineKeySection section)
{
return GetDecryptionAlgorithm (section.Decryption);
}
static byte [] GetDecryptionKey (MachineKeySection section)
{
if (decryption_key == null)
decryption_key = GetDecryptionAlgorithm (section).Key;
return decryption_key;
}
static byte [] GetValidationKey (MachineKeySection section)
{
if (validation_key == null)
validation_key = GetValidationAlgorithm (section).Key;
return validation_key;
}
#else
static SymmetricAlgorithm GetDecryptionAlgorithm (MachineKeySection section)
{
return section.GetDecryptionAlgorithm ();
}
static byte[] GetDecryptionKey (MachineKeySection section)
{
return section.GetDecryptionKey ();
}
static byte [] GetValidationKey (MachineKeySection section)
{
return section.GetValidationKey ();
}
#endif
static public byte [] Decrypt (MachineKeySection section, byte [] encodedData)
{
return Decrypt (section, encodedData, 0, encodedData.Length);
}
static byte [] Decrypt (MachineKeySection section, byte [] encodedData, int offset, int length)
{
using (SymmetricAlgorithm sa = GetDecryptionAlgorithm (section)) {
sa.Key = GetDecryptionKey (section);
return Decrypt (sa, encodedData, offset, length);
}
}
static public byte [] Decrypt (SymmetricAlgorithm alg, byte [] encodedData, int offset, int length)
{
// alg.IV is randomly set (default behavior) and perfect for our needs
// iv is the first part of the encodedPassword
byte [] iv = new byte [alg.IV.Length];
Array.Copy (encodedData, 0, iv, 0, iv.Length);
using (ICryptoTransform decryptor = alg.CreateDecryptor (alg.Key, iv)) {
try {
return decryptor.TransformFinalBlock (encodedData, iv.Length + offset, length - iv.Length);
}
catch (CryptographicException) {
return null;
}
}
}
static public byte [] Encrypt (MachineKeySection section, byte [] data)
{
using (SymmetricAlgorithm sa = GetDecryptionAlgorithm (section)) {
sa.Key = GetDecryptionKey (section);
return Encrypt (sa, data);
}
}
static public byte [] Encrypt (SymmetricAlgorithm alg, byte [] data)
{
// alg.IV is randomly set (default behavior) and perfect for our needs
byte [] iv = alg.IV;
using (ICryptoTransform encryptor = alg.CreateEncryptor (alg.Key, iv)) {
byte [] encrypted = encryptor.TransformFinalBlock (data, 0, data.Length);
byte [] output = new byte [iv.Length + encrypted.Length];
// note: the IV can be public, however it should not be based on the password
Array.Copy (iv, 0, output, 0, iv.Length);
Array.Copy (encrypted, 0, output, iv.Length, encrypted.Length);
return output;
}
}
// in [data]
// return [data][signature]
public static byte [] Sign (MachineKeySection section, byte [] data)
{
return Sign (section, data, 0, data.Length);
}
static byte [] Sign (MachineKeySection section, byte [] data, int offset, int length)
{
using (KeyedHashAlgorithm kha = GetValidationAlgorithm (section)) {
kha.Key = GetValidationKey (section);
byte [] signature = kha.ComputeHash (data, offset, length);
byte [] block = new byte [length + signature.Length];
Array.Copy (data, block, length);
Array.Copy (signature, 0, block, length, signature.Length);
return block;
}
}
public static byte [] Verify (MachineKeySection section, byte [] data)
{
byte [] unsigned_data = null;
bool valid = true;
using (KeyedHashAlgorithm kha = GetValidationAlgorithm (section)) {
kha.Key = GetValidationKey (section);
int signlen = kha.HashSize >> 3; // bits to bytes
byte [] signature = Sign (section, data, 0, data.Length - signlen);
for (int i = 0; i < signature.Length; i++) {
if (signature [i] != data [data.Length - signature.Length + i])
valid = false; // do not return (timing attack)
}
unsigned_data = new byte [data.Length - signlen];
Array.Copy (data, 0, unsigned_data, 0, unsigned_data.Length);
}
return valid ? unsigned_data : null;
}
// do NOT sign then encrypt
public static byte [] EncryptSign (MachineKeySection section, byte [] data)
{
byte [] encdata = Encrypt (section, data);
return Sign (section, encdata);
}
// note: take no shortcut (timing attack) while verifying or decrypting
public static byte [] VerifyDecrypt (MachineKeySection section, byte [] block)
{
bool valid = true;
int signlen;
using (KeyedHashAlgorithm kha = GetValidationAlgorithm (section)) {
kha.Key = GetValidationKey (section);
signlen = kha.HashSize >> 3; // bits to bytes
byte [] signature = Sign (section, block, 0, block.Length - signlen);
for (int i = 0; i < signature.Length; i++) {
if (signature [i] != block [block.Length - signature.Length + i])
valid = false; // do not return (timing attack)
}
}
// whatever the signature continue with decryption
try {
byte [] decdata = Decrypt (section, block, 0, block.Length - signlen);
return valid ? decdata : null;
}
catch {
return null;
}
}
}
}
#endif
+1 -1
View File
@@ -182,7 +182,6 @@ System.Web.Configuration_2.0/IRemoteWebConfigurationHostServer.cs
System.Web.Configuration_2.0/LowerCaseStringConverter.cs
System.Web.Configuration_2.0/MachineKeyRegistryStorage.cs
System.Web.Configuration_2.0/MachineKeySection.cs
System.Web.Configuration_2.0/MachineKeySectionUtils.cs
System.Web.Configuration_2.0/MachineKeyValidation.cs
System.Web.Configuration_2.0/MachineKeyValidationConverter.cs
System.Web.Configuration_2.0/MembershipSection.cs
@@ -1165,6 +1164,7 @@ System.Web.Util/HttpEncoder.cs
System.Web.Util/ICalls.cs
System.Web.Util/IWebObjectFactory.cs
System.Web.Util/IWebPropertyAccessor.cs
System.Web.Util/MachineKeySectionUtils.cs
System.Web.Util/RuntimeHelpers.cs
System.Web.Util/SearchPattern.cs
System.Web.Util/SerializationHelper.cs
@@ -712,6 +712,8 @@ namespace System.Web
static void OnFileChanged(object sender, FileSystemEventArgs args)
{
if (HttpRuntime.DomainUnloading)
return;
string name = args.Name;
bool isConfig = false;
@@ -441,6 +441,11 @@ namespace System.Web
static void RealProcessRequest (object o)
{
if (domainUnloading) {
Console.Error.WriteLine ("Domain is unloading, not processing the request.");
return;
}
HttpWorkerRequest req = (HttpWorkerRequest) o;
bool started_internally = req.StartedInternally;
do {
@@ -584,6 +589,7 @@ namespace System.Web
// TODO: call ReleaseResources
//
domainUnloading = true;
HttpApplicationFactory.DisableWatchers ();
ThreadPool.QueueUserWorkItem (delegate {
try {
ShutdownAppDomain ();
+11 -1
View File
@@ -35,6 +35,7 @@ using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Resources;
using System.Security.Principal;
namespace System.Web {
public class SiteMapNode : IHierarchyData, INavigateUIData, ICloneable {
@@ -177,12 +178,20 @@ namespace System.Web {
public virtual SiteMapNodeCollection ChildNodes {
get {
if (childNodes == null)
if (provider.SecurityTrimmingEnabled) {
IPrincipal p = HttpContext.Current.User;
if ((user == null && user != p) || user != null && user != p) {
user = p;
childNodes = provider.GetChildNodes (this);
}
} else if (childNodes == null) {
childNodes = provider.GetChildNodes (this);
}
return childNodes;
}
set {
CheckWritable ();
user = null;
childNodes = value;
}
}
@@ -439,6 +448,7 @@ namespace System.Web {
string resourceKey;
SiteMapNode parent;
SiteMapNodeCollection childNodes;
IPrincipal user;
#endregion
}
@@ -88,6 +88,7 @@ System.Web.Configuration/CustomErrorCollectionTest.cs
System.Web.Configuration/DeploymentSectionTest.cs
System.Web.Configuration/GlobalizationSectionTest.cs
System.Web.Configuration/HostingEnvironmentSectionTest.cs
System.Web.Configuration/MachineKeySectionTest.cs
System.Web.Configuration/MachineKeyValidationConverterTest.cs
System.Web.Configuration/NullableStringValidatorTest.cs
System.Web.Configuration/ProfilePropertySettingsTest.cs
@@ -549,6 +550,7 @@ System.Web.UI.WebControls/WebControlCas.cs
System.Web.UI.WebControls/XmlCas.cs
System.Web.UI.WebControls/XmlDataSourceCas.cs
System.Web.Util/HttpEncoderTest.cs
System.Web.Util/MachineKeySectionUtilsTest.cs
System.Web.Util/RequestValidatorTest.cs
System.Web.Util/TransactionsCas.cs
System.Web.Util/UrlUtilsTest.cs
@@ -0,0 +1,178 @@
//
// Unit tests for MachineKeySection
//
// Author:
// Sebastien Pouliot <[email protected]>
//
// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Configuration;
using System.Web.Configuration;
using NUnit.Framework;
namespace MonoTests.System.Web.Configuration {
[TestFixture]
public class MachineKeySectionTest {
[Test]
public void DefaultValues ()
{
MachineKeySection section = new MachineKeySection ();
#if NET_4_0
Assert.AreEqual (MachineKeyCompatibilityMode.Framework20SP1, section.CompatibilityMode, "CompatibilityMode");
#endif
Assert.AreEqual ("Auto", section.Decryption, "Decryption");
Assert.AreEqual ("AutoGenerate,IsolateApps", section.DecryptionKey, "DecryptionKey");
#if NET_4_0
Assert.AreEqual (MachineKeyValidation.HMACSHA256, section.Validation, "Validation");
Assert.AreEqual ("HMACSHA256", section.ValidationAlgorithm, "ValidationAlgorithm");
#else
Assert.AreEqual (MachineKeyValidation.SHA1, section.Validation, "Validation");
#endif
Assert.AreEqual ("AutoGenerate,IsolateApps", section.ValidationKey, "ValidationKey");
}
[Test]
#if NET_4_0
[ExpectedException (typeof (NullReferenceException))]
#else
[ExpectedException (typeof (ConfigurationErrorsException))]
#endif
public void Decryption_Null ()
{
MachineKeySection section = new MachineKeySection ();
section.Decryption = null;
}
[Test]
[ExpectedException (typeof (ConfigurationErrorsException))]
public void Decryption_Empty ()
{
MachineKeySection section = new MachineKeySection ();
section.Decryption = String.Empty;
}
#if NET_4_0
[Test]
public void Decryption_RC2 ()
{
MachineKeySection section = new MachineKeySection ();
Assert.AreEqual ("Auto", section.Decryption, "before");
section.Decryption = "alg:RC2";
Assert.AreEqual ("alg:RC2", section.Decryption, "after");
}
[Test]
public void Decryption_InvalidName ()
{
MachineKeySection section = new MachineKeySection ();
Assert.AreEqual ("Auto", section.Decryption, "before");
section.Decryption = "alg:UnexistingType";
// looks like the problem is found (much) later
Assert.AreEqual ("alg:UnexistingType", section.Decryption, "Decryption");
}
[Test]
public void ValidationAlgorithm_Null ()
{
MachineKeySection section = new MachineKeySection ();
section.ValidationAlgorithm = null;
Assert.AreEqual ("HMACSHA256", section.ValidationAlgorithm, "ValidationAlgorithm");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void ValidationAlgorithm_Empty ()
{
MachineKeySection section = new MachineKeySection ();
section.ValidationAlgorithm = String.Empty;
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Validation_Custom ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.Custom;
// cannot be set directly
}
[Test]
public void Validation ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.AES;
Assert.AreEqual ("AES", section.ValidationAlgorithm, "AES");
section.Validation = MachineKeyValidation.HMACSHA256;
Assert.AreEqual ("HMACSHA256", section.ValidationAlgorithm, "HMACSHA256");
section.Validation = MachineKeyValidation.HMACSHA384;
Assert.AreEqual ("HMACSHA384", section.ValidationAlgorithm, "HMACSHA384");
section.Validation = MachineKeyValidation.HMACSHA512;
Assert.AreEqual ("HMACSHA512", section.ValidationAlgorithm, "HMACSHA512");
section.Validation = MachineKeyValidation.MD5;
Assert.AreEqual ("MD5", section.ValidationAlgorithm, "MD5");
section.Validation = MachineKeyValidation.SHA1;
Assert.AreEqual ("SHA1", section.ValidationAlgorithm, "SHA1");
// special case, enum value and algorithm names differs
section.Validation = MachineKeyValidation.TripleDES;
Assert.AreEqual ("3DES", section.ValidationAlgorithm, "3DES");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void ValidationAlgorithm ()
{
MachineKeySection section = new MachineKeySection ();
section.ValidationAlgorithm = "HMACRIPEMD160";
// syntax is: alg:something-deriving-from-KeyedHashAlgorithm
}
[Test]
public void ValidationAlgorithm_RIPEMD160 ()
{
MachineKeySection section = new MachineKeySection ();
Assert.AreEqual (MachineKeyValidation.HMACSHA256, section.Validation, "before");
section.ValidationAlgorithm = "alg:HMACRIPEMD160";
Assert.AreEqual (MachineKeyValidation.Custom, section.Validation, "after");
Assert.AreEqual ("alg:HMACRIPEMD160", section.ValidationAlgorithm, "ValidationAlgorithm");
}
[Test]
public void ValidationAlgorithm_InvalidName ()
{
MachineKeySection section = new MachineKeySection ();
Assert.AreEqual (MachineKeyValidation.HMACSHA256, section.Validation, "before");
section.ValidationAlgorithm = "alg:UnexistingType";
// looks like the problem is found (much) later
Assert.AreEqual (MachineKeyValidation.Custom, section.Validation, "after");
Assert.AreEqual ("alg:UnexistingType", section.ValidationAlgorithm, "ValidationAlgorithm");
}
#endif
}
}
@@ -2,10 +2,11 @@
// System.Web.Configuration.MachineKeyValidationConverterTest.cs - Unit tests
// for System.Web.Configuration.MachineKeyValidationConverter.
//
// Author:
// Authors:
// Chris Toshok <[email protected]>
// Sebastien Pouliot <[email protected]>
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
// Copyright (C) 2005, 2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -35,8 +36,7 @@ using NUnit.Framework;
namespace MonoTests.System.Web.Configuration {
[TestFixture]
public class MachineKeyValidationConverterTest
{
public class MachineKeyValidationConverterTest {
[Test]
public void CanConvertFrom ()
{
@@ -66,10 +66,46 @@ namespace MonoTests.System.Web.Configuration {
object o;
o = cv.ConvertFrom (null, null, "MD5");
Assert.AreEqual (typeof (MachineKeyValidation), o.GetType(), "A1");
Assert.AreEqual ("MD5", o.ToString(), "A2");
Assert.AreEqual (typeof (MachineKeyValidation), o.GetType (), "typeof");
Assert.AreEqual ("MD5", o.ToString (), "MD5");
o = cv.ConvertFrom (null, null, "SHA1");
Assert.AreEqual ("SHA1", o.ToString (), "SHA1");
// 3DES in, TripleDES out
o = cv.ConvertFrom (null, null, "3DES");
Assert.AreEqual ("TripleDES", o.ToString (), "3DES");
o = cv.ConvertFrom (null, null, "AES");
Assert.AreEqual ("AES", o.ToString(), "A3");
Assert.AreEqual ("AES", o.ToString (), "AES");
#if NET_4_0
o = cv.ConvertFrom (null, null, "HMACSHA256");
Assert.AreEqual ("HMACSHA256", o.ToString (), "HMACSHA256");
o = cv.ConvertFrom (null, null, "HMACSHA384");
Assert.AreEqual ("HMACSHA384", o.ToString (), "HMACSHA384");
o = cv.ConvertFrom (null, null, "HMACSHA512");
Assert.AreEqual ("HMACSHA512", o.ToString (), "HMACSHA512");
#endif
}
#if NET_4_0
[Test]
[ExpectedException (typeof (ArgumentException))]
public void ConvertFrom_Custom ()
{
MachineKeyValidationConverter cv = new MachineKeyValidationConverter ();
cv.ConvertFrom (null, null, "Custom");
}
#endif
[Test]
[ExpectedException (typeof (ArgumentException))]
public void ConvertFrom_CaseSensitive ()
{
MachineKeyValidationConverter cv = new MachineKeyValidationConverter ();
cv.ConvertFrom (null, null, "sha1");
}
[Test]
@@ -91,10 +127,29 @@ namespace MonoTests.System.Web.Configuration {
Assert.AreEqual ("MD5", cv.ConvertTo (null, null, MachineKeyValidation.MD5, typeof (string)), "A1");
Assert.AreEqual ("SHA1", cv.ConvertTo (null, null, MachineKeyValidation.SHA1, typeof (string)), "A2");
Assert.AreEqual ("3DES", cv.ConvertTo (null, null, MachineKeyValidation.TripleDES, typeof (string)), "A3");
#if NET_4_0
Assert.AreEqual ("HMACSHA256", cv.ConvertTo (null, null, MachineKeyValidation.HMACSHA256, typeof (string)), "HMACSHA256");
Assert.AreEqual ("HMACSHA384", cv.ConvertTo (null, null, MachineKeyValidation.HMACSHA384, typeof (string)), "HMACSHA384");
Assert.AreEqual ("HMACSHA512", cv.ConvertTo (null, null, MachineKeyValidation.HMACSHA512, typeof (string)), "HMACSHA512");
#endif
}
#if NET_4_0
[Test]
[ExpectedException (typeof (ArgumentException))]
public void ConvertTo_Custom ()
{
MachineKeyValidationConverter cv = new MachineKeyValidationConverter ();
cv.ConvertTo (null, null, MachineKeyValidation.Custom, typeof (string));
}
#endif
[Test]
#if NET_4_0
[ExpectedException (typeof (ArgumentException))]
#else
[ExpectedException (typeof (NullReferenceException))]
#endif
public void ConvertTo_NullError ()
{
MachineKeyValidationConverter cv = new MachineKeyValidationConverter ();
@@ -103,7 +158,11 @@ namespace MonoTests.System.Web.Configuration {
}
[Test]
#if NET_4_0
[ExpectedException (typeof (ArgumentException))]
#else
[ExpectedException (typeof (FormatException))]
#endif
public void ConvertTo_TypeError1 ()
{
MachineKeyValidationConverter cv = new MachineKeyValidationConverter ();
@@ -120,6 +179,17 @@ namespace MonoTests.System.Web.Configuration {
Assert.AreEqual ("MD5", cv.ConvertTo (null, null, MachineKeyValidation.MD5, null), "A2");
}
[Test]
#if NET_4_0
[ExpectedException (typeof (ArgumentException))]
#else
[ExpectedException (typeof (FormatException))]
#endif
public void ConvertTo_TypeError3 ()
{
MachineKeyValidationConverter cv = new MachineKeyValidationConverter ();
cv.ConvertTo (null, null, (MachineKeyValidation)Int32.MinValue, typeof (string));
}
}
}
@@ -87,7 +87,7 @@ namespace MonoTests.System.Web.Security
// ä (C3-A4)
s = Encoding.UTF8.GetString (new byte [2] { 0xC3, 0xA4 });
Assert.AreEqual ("8419B71C87A225A2C70B50486FBEE545", FormsAuthentication.HashPasswordForStoringInConfigFile (s, "MD5"));
Assert.AreEqual ("8419B71C87A225A2C70B50486FBEE545", FormsAuthentication.HashPasswordForStoringInConfigFile (s, "md5"));
}
[Test]
@@ -99,7 +99,7 @@ namespace MonoTests.System.Web.Security
// ä (C3-A4)
s = Encoding.UTF8.GetString (new byte [2] { 0xC3, 0xA4 });
Assert.AreEqual ("961FA22F61A56E19F3F5F8867901AC8CF5E6D11F", FormsAuthentication.HashPasswordForStoringInConfigFile (s, "SHA1"));
Assert.AreEqual ("961FA22F61A56E19F3F5F8867901AC8CF5E6D11F", FormsAuthentication.HashPasswordForStoringInConfigFile (s, "sha1"));
}
[Test]
@@ -129,6 +129,16 @@ namespace MonoTests.System.Web.Security
{
FormsAuthentication.RedirectToLoginPage (String.Empty);
}
[Test]
[Category ("NotWorking")] // works on .net
public void Authenticate ()
{
Assert.IsFalse (FormsAuthentication.Authenticate (null, "password"), "null,string");
Assert.IsFalse (FormsAuthentication.Authenticate ("user", null), "string,null");
// not throwing
Assert.IsFalse (FormsAuthentication.Authenticate ("user", "password"), "string,string");
}
#endif
[TestFixtureTearDown]
@@ -1,6 +1,6 @@
//
// MembershipUserCollectionTest.cs
// - Unit tests for System.Web.Security.MembershipUserCollection
// RolePrincipalTest.cs
// - Unit tests for System.Web.Security.RolePrincipal
//
// Author:
// Sebastien Pouliot <[email protected]>
@@ -1,10 +1,12 @@
//
// LosFormatterTest.cs - Unit tests for System.Web.UI.LosFormatter
//
// Author:
// Authors:
// Gert Driesen <[email protected]>
// Sebastien Pouliot <[email protected]>
//
// Copyright (C) 2007 Gert Driesen
// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
@@ -38,6 +40,145 @@ namespace MonoTests.System.Web.UI
[TestFixture]
public class LosFormatterTest
{
static byte [] Empty = new byte [0];
string Serialize (LosFormatter lf, object value)
{
StringWriter sw = new StringWriter ();
lf.Serialize (sw, value);
return sw.ToString ();
}
object Deserialize (LosFormatter lf, string serializedData)
{
return lf.Deserialize (serializedData);
}
string NoKeyRoundTrip (LosFormatter lf, string assertionMessage)
{
string serializedData = Serialize (lf, "Mono");
Assert.AreEqual ("Mono", (string) Deserialize (lf, serializedData), assertionMessage);
return serializedData;
}
[Test]
public void Ctor_BoolByteArray ()
{
LosFormatter lf1 = new LosFormatter (false, (byte []) null);
string expected = NoKeyRoundTrip (lf1, "false, null");
LosFormatter lf2 = new LosFormatter (true, (byte []) null);
Assert.AreEqual (expected, NoKeyRoundTrip (lf2, "true, null"), "2");
LosFormatter lf3 = new LosFormatter (false, Empty);
Assert.AreEqual (expected, NoKeyRoundTrip (lf3, "false, empty"), "3");
// an empty key is still a key - a signature is appended
LosFormatter lf4 = new LosFormatter (true, Empty);
string signed = NoKeyRoundTrip (lf4, "true, empty");
Assert.AreNotEqual (expected, signed, "4");
byte [] data = Convert.FromBase64String (expected);
byte [] signed_data = Convert.FromBase64String (signed);
Assert.IsTrue (BitConverter.ToString (signed_data).StartsWith (BitConverter.ToString (data)), "4 / same data");
#if NET_4_0
// 32 bytes == 256 bits -> match HMACSHA256 as default
Assert.AreEqual (32, signed_data.Length - data.Length, "signature length");
#else
// 20 bytes == 160 bits -> match HMACSHA1 as default
Assert.AreEqual (20, signed_data.Length - data.Length, "signature length");
#endif
}
[Test]
public void Ctor_BoolString ()
{
LosFormatter lf1 = new LosFormatter (false, (string) null);
string expected = NoKeyRoundTrip (lf1, "false, null");
LosFormatter lf2 = new LosFormatter (true, (string) null);
Assert.AreEqual (expected, NoKeyRoundTrip (lf2, "true, null"), "2");
LosFormatter lf3 = new LosFormatter (false, String.Empty);
Assert.AreEqual (expected, NoKeyRoundTrip (lf3, "false, empty"), "3");
// an empty string is not an empty key!
LosFormatter lf4 = new LosFormatter (true, String.Empty);
Assert.AreEqual (expected, NoKeyRoundTrip (lf4, "true, empty"), "4");
byte [] key = new byte [32];
LosFormatter lf5 = new LosFormatter (true, Convert.ToBase64String (key));
string signed = NoKeyRoundTrip (lf5, "true, b64");
Assert.AreNotEqual (expected, signed, "5");
byte [] data = Convert.FromBase64String (expected);
byte [] signed_data = Convert.FromBase64String (signed);
Assert.IsTrue (BitConverter.ToString (signed_data).StartsWith (BitConverter.ToString (data)), "5 / same data");
#if NET_4_0
// 32 bytes == 256 bits -> match HMACSHA256 as default
Assert.AreEqual (32, signed_data.Length - data.Length, "signature length");
#else
// 20 bytes == 160 bits -> match HMACSHA1 as default
Assert.AreEqual (20, signed_data.Length - data.Length, "signature length");
#endif
}
string SerializeOverloads (LosFormatter lf, string message)
{
string stream_ser;
using (MemoryStream ms = new MemoryStream ()) {
lf.Serialize (ms, String.Empty);
stream_ser = Convert.ToBase64String (ms.ToArray ());
}
string tw_ser;
using (MemoryStream ms = new MemoryStream ()) {
using (TextWriter tw = new StreamWriter (ms)) {
lf.Serialize (tw, String.Empty);
}
tw_ser = Convert.ToBase64String (ms.ToArray ());
}
Assert.AreEqual (stream_ser, tw_ser, message);
return stream_ser;
}
[Test]
public void SerializeOverloads ()
{
LosFormatter lf1 = new LosFormatter (false, (string) null);
string r1 = SerializeOverloads (lf1, "false, null");
LosFormatter lf2 = new LosFormatter (true, (string) null);
string r2 = SerializeOverloads (lf2, "true, null");
Assert.AreEqual (r1, r2, "r1-r2");
LosFormatter lf3 = new LosFormatter (false, String.Empty);
string r3 = SerializeOverloads (lf3, "false, empty");
Assert.AreEqual (r2, r3, "r2-r3");
// an empty string is not an empty key!
LosFormatter lf4 = new LosFormatter (true, String.Empty);
string r4 = SerializeOverloads (lf4, "true, empty");
Assert.AreEqual (r3, r4, "r3-r4");
byte [] key = new byte [32];
LosFormatter lf5 = new LosFormatter (true, Convert.ToBase64String (key));
string r5 = SerializeOverloads (lf5, "false, b64");
Assert.AreNotEqual (r4, r5, "r4-r5");
}
#if NET_4_0
[Test]
[ExpectedException (typeof (NotSupportedException))]
public void Deserialize_Stream_NonSeekable ()
{
string s1 = "Hello world";
NonSeekableStream ns = new NonSeekableStream ();
LosFormatter lf = new LosFormatter ();
lf.Serialize (ns, s1);
}
#else
[Test] // bug #411115
public void Deserialize_Stream_NonSeekable ()
{
@@ -49,7 +190,7 @@ namespace MonoTests.System.Web.UI
string s2 = lf.Deserialize (ns) as string;
Assert.AreEqual (s1, s2);
}
#endif
[Test] // bug #324526
public void Serialize ()
{
@@ -30,6 +30,7 @@
#if NET_2_0
using System;
using System.IO;
using System.Reflection;
using System.Web;
using System.Web.UI;
@@ -115,6 +116,20 @@ namespace MonoTests.System.Web.UI
HtmlDiff.AssertAreEqual (originalHtml, renderedHtml, "#A1");
}
#if false
[Test]
public void SerializeOverloads ()
{
ObjectStateFormatter osf = new ObjectStateFormatter ();
string s1 = osf.Serialize (String.Empty);
string s2;
using (MemoryStream ms = new MemoryStream ()) {
osf.Serialize (ms, String.Empty);
s2 = Convert.ToBase64String (ms.ToArray ());
}
Assert.AreEqual (s1, s2, "identical");
}
#endif
}
}
#endif
#endif
@@ -0,0 +1,310 @@
//
// Unit tests for MachineKeySectionUtils (internals)
//
// Author:
// Sebastien Pouliot <[email protected]>
//
// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Web.Configuration;
using System.Web.Util;
using NUnit.Framework;
namespace MonoTests.System.Web.Util {
[TestFixture]
public class MachineKeySectionUtilsTest {
public void Encrypt_RoundTrip (MachineKeySection section)
{
byte [] data = new byte [14];
byte [] encdata = MachineKeySectionUtils.Encrypt (section, data);
byte [] decdata = MachineKeySectionUtils.Decrypt (section, encdata);
Assert.AreEqual (data, decdata, "roundtrip");
// changing length (missing first byte)
byte [] cut = new byte [encdata.Length - 1];
Array.Copy (encdata, 1, cut, 0, cut.Length);
Assert.IsNull (MachineKeySectionUtils.Decrypt (section, cut), "bad length");
// changing last byte (padding)
byte be = encdata [encdata.Length - 1];
encdata [encdata.Length - 1] ^= (byte) (be + 1);
Assert.IsNull (MachineKeySectionUtils.Decrypt (section, encdata), "bad padding");
}
[Test]
public void Encrypt_RoundTrip_Default ()
{
Encrypt_RoundTrip (new MachineKeySection ());
}
[Test]
public void Encrypt_RoundTrip_AES ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.AES;
Encrypt_RoundTrip (section);
}
[Test]
public void Encrypt_RoundTrip_TripleDES ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.TripleDES;
Encrypt_RoundTrip (section);
}
[Test]
public void Encrypt_RoundTrip_MD5 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.MD5;
Encrypt_RoundTrip (section);
}
[Test]
public void Encrypt_RoundTrip_SHA1 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.SHA1;
Encrypt_RoundTrip (section);
}
#if NET_4_0
[Test]
public void Encrypt_RoundTrip_HMACSHA256 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.HMACSHA256;
EncryptSign_RoundTrip (section);
}
[Test]
public void Encrypt_RoundTrip_HMACSHA384 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.HMACSHA384;
EncryptSign_RoundTrip (section);
}
[Test]
public void Encrypt_RoundTrip_HMACSHA512 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.HMACSHA512;
EncryptSign_RoundTrip (section);
}
[Test]
public void Encrypt_RoundTrip_Custom_RIPEMD160 ()
{
MachineKeySection section = new MachineKeySection ();
section.ValidationAlgorithm = "alg:HMACRIPEMD160";
EncryptSign_RoundTrip (section);
}
#endif
public void EncryptSign_RoundTrip (MachineKeySection section)
{
byte [] data = new byte [14];
byte [] block = MachineKeySectionUtils.EncryptSign (section, data);
byte [] decdata = MachineKeySectionUtils.VerifyDecrypt (section, block);
Assert.AreEqual (data, decdata, "roundtrip");
// changing a byte of the data
byte b0 = block [0];
block [0] ^= b0;
Assert.IsNull (MachineKeySectionUtils.VerifyDecrypt (section, block), "bad data");
block [0] = b0;
// changing a byte of the signature
byte be = block [block.Length - 1];
block [block.Length - 1] ^= (byte) (be + 1);
Assert.IsNull (MachineKeySectionUtils.VerifyDecrypt (section, block), "bad signature");
}
[Test]
public void EncryptSign_RoundTrip_Default ()
{
EncryptSign_RoundTrip (new MachineKeySection ());
}
[Test]
public void EncryptSign_RoundTrip_AES ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.AES;
EncryptSign_RoundTrip (section);
}
[Test]
public void EncryptSign_RoundTrip_TripleDES ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.TripleDES;
EncryptSign_RoundTrip (section);
}
[Test]
public void EncryptSign_RoundTrip_MD5 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.MD5;
EncryptSign_RoundTrip (section);
}
[Test]
public void EncryptSign_RoundTrip_SHA1 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.SHA1;
EncryptSign_RoundTrip (section);
}
#if NET_4_0
[Test]
public void EncryptSign_RoundTrip_HMACSHA256 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.HMACSHA256;
EncryptSign_RoundTrip (section);
}
[Test]
public void EncryptSign_RoundTrip_HMACSHA384 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.HMACSHA384;
EncryptSign_RoundTrip (section);
}
[Test]
public void EncryptSign_RoundTrip_HMACSHA512 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.HMACSHA512;
EncryptSign_RoundTrip (section);
}
[Test]
public void EncryptSign_RoundTrip_Custom_RIPEMD160 ()
{
MachineKeySection section = new MachineKeySection ();
section.ValidationAlgorithm = "alg:HMACRIPEMD160";
EncryptSign_RoundTrip (section);
}
#endif
public void Validation_RoundTrip (MachineKeySection section)
{
byte [] data = new byte [] { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0 };
byte [] block = MachineKeySectionUtils.Sign (section, data);
Assert.AreEqual (data, MachineKeySectionUtils.Verify (section, block), "OK");
// changing last byte
for (int i = 0; i < data.Length; i++) {
byte b = block [i];
block [i] ^= 0xFF;
Assert.IsNull (MachineKeySectionUtils.Verify (section, block), "bad-" + i.ToString ());
block [i] = b;
}
}
[Test]
public void Validation_RoundTrip_Default ()
{
Validation_RoundTrip (new MachineKeySection ());
}
[Test]
public void Validation_RoundTrip_AES ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.AES;
Validation_RoundTrip (section);
}
[Test]
public void Validation_RoundTrip_TripleDES ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.TripleDES;
Validation_RoundTrip (section);
}
[Test]
public void Validation_RoundTrip_MD5 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.MD5;
Validation_RoundTrip (section);
}
[Test]
public void Validation_RoundTrip_SHA1 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.SHA1;
Validation_RoundTrip (section);
}
#if NET_4_0
[Test]
public void Validation_RoundTrip_HMACSHA256 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.HMACSHA256;
Validation_RoundTrip (section);
}
[Test]
public void Validation_RoundTrip_HMACSHA384 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.HMACSHA384;
Validation_RoundTrip (section);
}
[Test]
public void Validation_RoundTrip_HMACSHA512 ()
{
MachineKeySection section = new MachineKeySection ();
section.Validation = MachineKeyValidation.HMACSHA512;
Validation_RoundTrip (section);
}
[Test]
public void Validation_RoundTrip_Custom_RIPEMD160 ()
{
MachineKeySection section = new MachineKeySection ();
section.ValidationAlgorithm = "alg:HMACRIPEMD160";
Validation_RoundTrip (section);
}
#endif
[Test]
public void GetHexString ()
{
Assert.AreEqual ("DEADC0DE", MachineKeySectionUtils.GetHexString (new byte [] { 0xde, 0xad, 0xc0, 0xde }), "deadcode");
}
}
}
@@ -13,6 +13,7 @@ System.Web.Caching/OutputCacheProviderCollection.cs
System.Web.Caching/ResponseElement.cs
System.Web.Caching/SubstitutionResponseElement.cs
System.Web.Configuration_2.0/VersionConverter.cs
System.Web.Configuration_2.0/MachineKeyCompatibilityMode.cs
System.Web.Compilation/FolderLevelBuildProviderAppliesTo.cs
System.Web.Compilation/FolderLevelBuildProviderAppliesToAttribute.cs
System.Web.Compilation/RouteUrlExpressionBuilder.cs
@@ -72,7 +72,13 @@ namespace System.Net.Configuration {
get { return (string) base ["targetName"]; }
set { base ["targetName"] = value; }
}
#if NET_4_0
[ConfigurationPropertyAttribute("enableSsl", DefaultValue = false)]
public bool EnableSsl {
get { return (bool) base ["enableSsl"]; }
set { base ["enableSsl"] = value; }
}
#endif
protected override ConfigurationPropertyCollection Properties {
// what to do here?
get { return base.Properties; }
@@ -118,6 +118,9 @@ namespace System.Net.Mail {
if (cfg != null) {
this.host = cfg.Network.Host;
this.port = cfg.Network.Port;
#if NET_4_0
this.enableSsl = cfg.Network.EnableSsl;
#endif
TargetName = cfg.Network.TargetName;
if (this.TargetName == null)
TargetName = "SMTPSVC/" + (host != null ? host : "");
@@ -184,7 +184,11 @@ namespace System.Net.Sockets
SocketAsyncCall sac = null;
SocketAsyncResult req = null;
lock (queue) {
queue.Dequeue (); // remove ourselves
// queue.Count will only be 0 if the socket is closed while receive/send
// operation(s) are pending and at least one call to this method is
// waiting on the lock while another one calls CompleteAllOnDispose()
if (queue.Count > 0)
queue.Dequeue (); // remove ourselves
if (queue.Count > 0) {
req = (SocketAsyncResult) queue.Peek ();
if (!Sock.disposed) {
@@ -485,7 +485,7 @@ namespace System.Net.Sockets {
throw new ArgumentNullException ("remoteEP");
IPEndPoint ep = remoteEP as IPEndPoint;
if (ep != null)
if (ep != null && socket_type != SocketType.Dgram) /* Dgram uses Any to 'disconnect' */
if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any))
throw new SocketException ((int) SocketError.AddressNotAvailable);
@@ -516,7 +516,8 @@ namespace System.Net.Sockets {
if (error != 0)
throw new SocketException (error);
connected=true;
if (socket_type != SocketType.Dgram)
connected=true;
#if NET_2_0
isbound = true;
+20 -5
View File
@@ -119,7 +119,7 @@ namespace System.Net {
try {
stream.BeginRead (buffer, 0, BufferSize, OnRead, this);
} catch {
sock.Close (); // stream disposed
CloseSocket ();
}
}
@@ -167,14 +167,14 @@ namespace System.Net {
if (ms != null && ms.Length > 0)
SendError ();
if (sock != null)
sock.Close ();
CloseSocket ();
return;
}
if (nread == 0) {
//if (ms.Length > 0)
// SendError (); // Why bother?
sock.Close ();
CloseSocket ();
return;
}
@@ -343,6 +343,19 @@ namespace System.Net {
Close (false);
}
void CloseSocket ()
{
if (sock == null)
return;
try {
sock.Close ();
} catch {
} finally {
sock = null;
}
}
internal void Close (bool force_close)
{
if (sock != null) {
@@ -381,10 +394,12 @@ namespace System.Net {
Socket s = sock;
sock = null;
try {
s.Shutdown (SocketShutdown.Both);
if (s != null)
s.Shutdown (SocketShutdown.Both);
} catch {
} finally {
s.Close ();
if (s != null)
s.Close ();
}
Unbind ();
return;
@@ -1240,6 +1240,7 @@ namespace System.Net
if (r != null) {
if (wexc != null) {
haveResponse = true;
r.SetCompleted (false, wexc);
r.DoCallback ();
return;
@@ -205,14 +205,24 @@ namespace System.Security.Cryptography.X509Certificates {
status = null;
if (elements.Count > 0)
elements.Clear ();
if (roots != null) {
roots.Close ();
roots = null;
if (user_root_store != null) {
user_root_store.Close ();
user_root_store = null;
}
if (cas != null) {
cas.Close ();
cas = null;
if (root_store != null) {
root_store.Close ();
root_store = null;
}
if (user_ca_store != null) {
user_ca_store.Close ();
user_ca_store = null;
}
if (ca_store != null) {
ca_store.Close ();
ca_store = null;
}
roots = null;
cas = null;
collection = null;
bce_restriction = null;
working_public_key = null;
@@ -227,29 +237,92 @@ namespace System.Security.Cryptography.X509Certificates {
// private stuff
private X509Store roots;
private X509Store cas;
private X509Certificate2Collection roots;
private X509Certificate2Collection cas;
private X509Store root_store;
private X509Store ca_store;
private X509Store user_root_store;
private X509Store user_ca_store;
private X509Store Roots {
private X509Certificate2Collection Roots {
get {
if (roots == null) {
roots = new X509Store (StoreName.Root, location);
roots.Open (OpenFlags.ReadOnly);
X509Certificate2Collection c = new X509Certificate2Collection ();
X509Store store = LMRootStore;
if (location == StoreLocation.CurrentUser)
c.AddRange (UserRootStore.Certificates);
c.AddRange (store.Certificates);
roots = c;
}
return roots;
}
}
private X509Store CertificateAuthorities {
private X509Certificate2Collection CertificateAuthorities {
get {
if (cas == null) {
cas = new X509Store (StoreName.CertificateAuthority, location);
cas.Open (OpenFlags.ReadOnly);
X509Certificate2Collection c = new X509Certificate2Collection ();
X509Store store = LMCAStore;
if (location == StoreLocation.CurrentUser)
c.AddRange (UserCAStore.Certificates);
c.AddRange (store.Certificates);
cas = c;
}
return cas;
}
}
private X509Store LMRootStore {
get {
if (root_store == null) {
root_store = new X509Store (StoreName.Root, StoreLocation.LocalMachine);
try {
root_store.Open (OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
} catch {
}
}
return root_store;
}
}
private X509Store UserRootStore {
get {
if (user_root_store == null) {
user_root_store = new X509Store (StoreName.Root, StoreLocation.CurrentUser);
try {
user_root_store.Open (OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
} catch {
}
}
return user_root_store;
}
}
private X509Store LMCAStore {
get {
if (ca_store == null) {
ca_store = new X509Store (StoreName.CertificateAuthority, StoreLocation.LocalMachine);
try {
ca_store.Open (OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
} catch {
}
}
return ca_store;
}
}
private X509Store UserCAStore {
get {
if (user_ca_store == null) {
user_ca_store = new X509Store (StoreName.CertificateAuthority, StoreLocation.CurrentUser);
try {
user_ca_store.Open (OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
} catch {
}
}
return user_ca_store;
}
}
// *** certificate chain/path building stuff ***
private X509Certificate2Collection collection;
@@ -260,10 +333,8 @@ namespace System.Security.Cryptography.X509Certificates {
get {
if (collection == null) {
collection = new X509Certificate2Collection (ChainPolicy.ExtraStore);
if (Roots.Certificates.Count > 0)
collection.AddRange (Roots.Certificates);
if (CertificateAuthorities.Certificates.Count > 0)
collection.AddRange (CertificateAuthorities.Certificates);
collection.AddRange (Roots);
collection.AddRange (CertificateAuthorities);
}
return collection;
}
@@ -295,7 +366,7 @@ namespace System.Security.Cryptography.X509Certificates {
// roots may be supplied (e.g. in the ExtraStore) so we need to confirm their
// trustiness (what a cute word) in the trusted root collection
if (!Roots.Certificates.Contains (certificate))
if (!Roots.Contains (certificate))
elements [elements.Count - 1].StatusFlags |= X509ChainStatusFlags.UntrustedRoot;
return X509ChainStatusFlags.NoError;
@@ -637,18 +708,18 @@ namespace System.Security.Cryptography.X509Certificates {
}
// System.dll v2 doesn't have a class to deal with the AuthorityKeyIdentifier extension
private string GetAuthorityKeyIdentifier (X509Certificate2 certificate)
static string GetAuthorityKeyIdentifier (X509Certificate2 certificate)
{
return GetAuthorityKeyIdentifier (certificate.MonoCertificate.Extensions ["2.5.29.35"]);
}
// but anyway System.dll v2 doesn't expose CRL in any way so...
private string GetAuthorityKeyIdentifier (MX.X509Crl crl)
static string GetAuthorityKeyIdentifier (MX.X509Crl crl)
{
return GetAuthorityKeyIdentifier (crl.Extensions ["2.5.29.35"]);
}
private string GetAuthorityKeyIdentifier (MX.X509Extension ext)
static string GetAuthorityKeyIdentifier (MX.X509Extension ext)
{
if (ext == null)
return String.Empty;
@@ -804,21 +875,34 @@ namespace System.Security.Cryptography.X509Certificates {
return X509ChainStatusFlags.NoError;
}
static MX.X509Crl CheckCrls (string subject, string ski, ArrayList crls)
{
foreach (MX.X509Crl crl in crls) {
if (crl.IssuerName == subject && (ski.Length == 0 || ski == GetAuthorityKeyIdentifier (crl)))
return crl;
}
return null; // No CRL found
}
private MX.X509Crl FindCrl (X509Certificate2 caCertificate)
{
string subject = caCertificate.SubjectName.Decode (X500DistinguishedNameFlags.None);
string ski = GetSubjectKeyIdentifier (caCertificate);
foreach (MX.X509Crl crl in CertificateAuthorities.Store.Crls) {
if (crl.IssuerName == subject) {
if ((ski.Length == 0) || (ski == GetAuthorityKeyIdentifier (crl)))
return crl;
}
MX.X509Crl result = CheckCrls (subject, ski, LMCAStore.Store.Crls);
if (result != null)
return result;
if (location == StoreLocation.CurrentUser) {
result = CheckCrls (subject, ski, UserCAStore.Store.Crls);
if (result != null)
return result;
}
foreach (MX.X509Crl crl in Roots.Store.Crls) {
if (crl.IssuerName == subject) {
if ((ski.Length == 0) || (ski == GetAuthorityKeyIdentifier (crl)))
return crl;
}
result = CheckCrls (subject, ski, LMRootStore.Store.Crls);
if (result != null)
return result;
if (location == StoreLocation.CurrentUser) {
result = CheckCrls (subject, ski, UserRootStore.Store.Crls);
if (result != null)
return result;
}
return null;
}
@@ -57,6 +57,7 @@ namespace Microsoft.Win32
// FIXME must be a way to determin this dynamically?
const int Int32ByteSize = 4;
const int Int64ByteSize = 8;
// FIXME this is hard coded on Mono, can it be determined dynamically?
readonly int NativeBytesPerCharacter = Marshal.SystemDefaultCharSize;
@@ -119,6 +120,11 @@ namespace Microsoft.Win32
string valueName, IntPtr reserved, RegistryValueKind type,
ref int data, int rawDataLength);
[DllImport ("advapi32.dll", CharSet=CharSet.Unicode, EntryPoint="RegSetValueEx")]
private static extern int RegSetValueEx (IntPtr keyBase,
string valueName, IntPtr reserved, RegistryValueKind type,
ref long data, int rawDataLength);
[DllImport ("advapi32.dll", CharSet=CharSet.Unicode, EntryPoint="RegQueryValueEx")]
private static extern int RegQueryValueEx (IntPtr keyBase,
string valueName, IntPtr reserved, ref RegistryValueKind type,
@@ -134,6 +140,11 @@ namespace Microsoft.Win32
string valueName, IntPtr reserved, ref RegistryValueKind type,
ref int data, ref int dataSize);
[DllImport ("advapi32.dll", CharSet=CharSet.Unicode, EntryPoint="RegQueryValueEx")]
private static extern int RegQueryValueEx (IntPtr keyBase,
string valueName, IntPtr reserved, ref RegistryValueKind type,
ref long data, ref int dataSize);
// Returns our handle from the RegistryKey
public IntPtr GetHandle (RegistryKey key)
{
@@ -192,6 +203,10 @@ namespace Microsoft.Win32
int data = 0;
result = RegQueryValueEx (handle, name, IntPtr.Zero, ref type, ref data, ref size);
obj = data;
} else if (type == RegistryValueKind.QWord) {
long data = 0;
result = RegQueryValueEx (handle, name, IntPtr.Zero, ref type, ref data, ref size);
obj = data;
} else if (type == RegistryValueKind.Binary) {
byte[] data;
result = GetBinaryValue (rkey, name, type, out data, size);
@@ -228,7 +243,10 @@ namespace Microsoft.Win32
int result;
IntPtr handle = GetHandle (rkey);
if (valueKind == RegistryValueKind.DWord && type == typeof (int)) {
if (valueKind == RegistryValueKind.QWord && type == typeof (long)) {
long rawValue = (long)value;
result = RegSetValueEx (handle, name, IntPtr.Zero, RegistryValueKind.QWord, ref rawValue, Int64ByteSize);
} else if (valueKind == RegistryValueKind.DWord && type == typeof (int)) {
int rawValue = (int)value;
result = RegSetValueEx (handle, name, IntPtr.Zero, RegistryValueKind.DWord, ref rawValue, Int32ByteSize);
} else if (valueKind == RegistryValueKind.Binary && type == typeof (byte[])) {
+31 -15
View File
@@ -155,10 +155,11 @@ namespace System.IO {
static StreamReader TryOpen (string name)
{
if (File.Exists (name))
return new StreamReader (name, Encoding.ASCII);
return new StreamReader (name);
return null;
}
static char [] space = { ' ' };
static DriveInfo [] LinuxGetDrives ()
{
using (StreamReader mounts = TryOpen ("/proc/mounts")){
@@ -168,27 +169,42 @@ namespace System.IO {
while ((line = mounts.ReadLine ()) != null){
if (line.StartsWith ("rootfs"))
continue;
int p;
p = line.IndexOf (' ');
if (p == -1)
string [] parts = line.Split (space, 4);
if (parts.Length < 3)
continue;
string rest = line.Substring (p+1);
p = rest.IndexOf (' ');
if (p == -1)
continue;
string path = rest.Substring (0, p);
rest = rest.Substring (p+1);
p = rest.IndexOf (' ');
if (p == -1)
continue;
string fstype = rest.Substring (0, p);
string path = Unescape (parts [1]);
string fstype = parts [2];
drives.Add (new DriveInfo (_DriveType.Linux, path, fstype));
}
return (DriveInfo []) drives.ToArray (typeof (DriveInfo));
}
}
static string Unescape (string path)
{
StringBuilder sb = null;
int start = 0;
do {
int slash = path.IndexOf ('\\', start);
if (slash >= 0) {
if (sb == null)
sb = new StringBuilder ();
string str = path.Substring (start, slash - start);
sb.Append (path.Substring (start, slash - start));
char c = (char) ((path [slash + 1] - '0') << 6);
c += (char) ((path [slash + 2] - '0') << 3);
c += (char) (path [slash + 3] - '0');
sb.Append (c);
start = slash + 4;
continue;
}
if (start == 0)
return path;
sb.Append (path.Substring (start));
return sb.ToString ();
} while (true);
}
static DriveInfo [] UnixGetDrives ()
{
@@ -709,6 +709,22 @@ namespace System.Runtime.Serialization.Formatters.Binary
return metadata;
}
// Called for primitive types
static bool IsGeneric (MemberInfo minfo)
{
if (minfo == null)
return false;
Type mtype = null;
switch (minfo.MemberType) {
case MemberTypes.Field:
mtype = ((FieldInfo) minfo).FieldType;
break;
default:
throw new NotSupportedException ("Not supported: " + minfo.MemberType);
}
return (mtype != null && mtype.IsGenericType);
}
private void ReadValue (BinaryReader reader, object parentObject, long parentObjectId, SerializationInfo info, Type valueType, string fieldName, MemberInfo memberInfo, int[] indices)
{
@@ -716,7 +732,7 @@ namespace System.Runtime.Serialization.Formatters.Binary
object val;
if (BinaryCommon.IsPrimitive (valueType))
if (BinaryCommon.IsPrimitive (valueType) && !IsGeneric (memberInfo))
{
val = ReadPrimitiveTypeValue (reader, valueType);
SetObjectValue (parentObject, fieldName, memberInfo, info, val, valueType, indices);
+36 -1
View File
@@ -237,11 +237,46 @@ namespace System.Threading
}
}
// lock held by caller
int FindByDueTime (long nr)
{
int min = 0;
int max = list.Count - 1;
if (max < 0)
return -1;
if (max < 20) {
while (min <= max) {
Timer t = (Timer) list.GetByIndex (min);
if (t.next_run == nr)
return min;
if (t.next_run > nr)
return -1;
min++;
}
return -1;
}
while (min <= max) {
int half = min + ((max - min) >> 1);
Timer t = (Timer) list.GetByIndex (half);
if (nr == t.next_run)
return half;
if (nr > t.next_run)
min = half + 1;
else
max = half - 1;
}
return -1;
}
// This should be the only caller to list.Add!
void Add (Timer timer)
{
// Make sure there are no collisions (10000 ticks == 1ms, so we should be safe here)
int idx = list.IndexOfKey (timer);
// Do not use list.IndexOfKey here. See bug #648130
int idx = FindByDueTime (timer.next_run);
if (idx != -1) {
bool up = (Int64.MaxValue - timer.next_run) > 20000 ? true : false;
while (true) {
+2 -2
View File
@@ -1316,7 +1316,7 @@ namespace System
throw new ArgumentOutOfRangeException ("length", Locale.GetText (
"Value has to be >= 0."));
if (keys.Length != items.Length || keys.Length - (index + keys.GetLowerBound (0)) < length)
if (items.Length - (index + items.GetLowerBound (0)) < length || keys.Length - (index + keys.GetLowerBound (0)) < length)
throw new ArgumentException ();
SortImpl (keys, items, index, length, comparer);
@@ -1565,7 +1565,7 @@ namespace System
if (length < 0)
throw new ArgumentOutOfRangeException ("length");
if (keys.Length != items.Length || keys.Length - index < length)
if (items.Length - index < length || keys.Length - index < length)
throw new ArgumentException ();
SortImpl<TKey, TValue> (keys, items, index, length, comparer);
+1 -1
View File
@@ -649,7 +649,7 @@ namespace System
public static DateTime FromBinary (long dateData)
{
switch ((ulong)dateData >> 62) {
switch ((ulong)dateData >> KindShift) {
case 1: // Utc
return new DateTime (dateData & TicksMask, DateTimeKind.Utc);
case 0: // Unspecified
@@ -2311,6 +2311,13 @@ public class ArrayTest
Assert.AreEqual (3, i1[4], "#N91");
Assert.AreEqual (6, i1[5], "#N92");
}
{
// #648828
double[] a = new double[115];
int[] b = new int[256];
Array.Sort<double, int> (a, b, 0, 115);
}
}
[Test] // #616416
+1 -1
View File
@@ -169,7 +169,7 @@ namespace Mono.CSharp {
case Binary.Operator.Subtraction:
result = BinaryFold (ec, oper, ((EnumConstant)left).Child, ((EnumConstant)right).Child, loc);
if (result != null)
result = result.Resolve (ec).TryReduce (ec, ((EnumConstant)left).Child.Type, loc);
result = result.Resolve (ec).TryReduce (ec, EnumSpec.GetUnderlyingType (lt), loc);
return result;
///
+3 -3
View File
@@ -184,15 +184,15 @@ namespace Mono.CSharp {
switch (RootContext.Platform) {
case Platform.X86:
pekind = PortableExecutableKinds.Required32Bit;
pekind = PortableExecutableKinds.Required32Bit | PortableExecutableKinds.ILOnly;
machine = ImageFileMachine.I386;
break;
case Platform.X64:
pekind = PortableExecutableKinds.PE32Plus;
pekind = PortableExecutableKinds.ILOnly;
machine = ImageFileMachine.AMD64;
break;
case Platform.IA64:
pekind = PortableExecutableKinds.PE32Plus;
pekind = PortableExecutableKinds.ILOnly;
machine = ImageFileMachine.IA64;
break;
case Platform.AnyCPU:
+2 -1
View File
@@ -5833,7 +5833,6 @@ namespace Mono.CSharp {
if (initializers == null)
return true;
only_constant_initializers = true;
for (int i = 0; i < probe.Count; ++i) {
var o = probe [i];
if (o is ArrayInitializer) {
@@ -5941,6 +5940,8 @@ namespace Mono.CSharp {
protected bool ResolveInitializers (ResolveContext ec)
{
only_constant_initializers = true;
if (arguments != null) {
bool res = true;
for (int i = 0; i < arguments.Count; ++i) {
+6 -1
View File
@@ -1001,14 +1001,19 @@ namespace Mono.CSharp
public override bool Define()
{
var mod_flags_src = ModFlags;
if (!base.Define ())
return false;
if (declarators != null) {
if ((mod_flags_src & Modifiers.DEFAULT_ACCESS_MODIFER) != 0)
mod_flags_src &= ~(Modifiers.AccessibilityMask | Modifiers.DEFAULT_ACCESS_MODIFER);
var t = new TypeExpression (MemberType, TypeExpression.Location);
int index = Parent.PartialContainer.Events.IndexOf (this);
foreach (var d in declarators) {
var ef = new EventField (Parent, t, ModFlags, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
var ef = new EventField (Parent, t, mod_flags_src, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
if (d.Initializer != null)
ef.initializer = d.Initializer;
+1 -1
View File
@@ -12,7 +12,7 @@ class Program {
typeof (Program).Module.GetPEKind (out pekind, out machine);
if ((pekind & PortableExecutableKinds.ILOnly) != 0)
if ((pekind & PortableExecutableKinds.ILOnly) == 0)
return 1;
if ((pekind & PortableExecutableKinds.Required32Bit) == 0)
+24
View File
@@ -0,0 +1,24 @@
// Compiler options: -optimize
using System;
class Test
{
static int Main ()
{
//switching to a constant fixes the problem
double thisIsCausingTheProblem = 5.0;
double[,] m1 = new double[4, 4] {
{ 1.0, 0.0, 0.0, thisIsCausingTheProblem },
{ 0.0, 1.0, 0.0, thisIsCausingTheProblem },
{ 0.0, 0.0, 1.0, thisIsCausingTheProblem },
{ 0.0, 0.0, 0.0, 1.0 }
};
var r = m1[0, 3];
if (r != 5)
return 1;
return 0;
}
}
+2
View File
@@ -32,6 +32,8 @@ class X {
// Now try the implicit conversions for underlying types in enum operators
byte b = 1;
short s = (short) (Test.A + b);
const int e = A.b + 1 - A.a;
//
// Make sure that other operators still work
+1 -1
View File
@@ -93,7 +93,7 @@ namespace Mono.XBuild.CommandLine {
static string guidExpression = "{[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}}";
static Regex slnVersionRegex = new Regex (@"Microsoft Visual Studio Solution File, Format Version (\d?\d.\d\d)");
static Regex projectRegex = new Regex ("Project\\(\"(" + guidExpression + ")\"\\) = \"(.*?)\", \"(.*?)\", \"(" + guidExpression + ")\"(\\s*?)((\\s*?)ProjectSection\\((.*?)\\) = (.*?)EndProjectSection(\\s*?))*(\\s*?)EndProject?", RegexOptions.Singleline);
static Regex projectRegex = new Regex ("Project\\(\"(" + guidExpression + ")\"\\) = \"(.*?)\", \"(.*?)\", \"(" + guidExpression + ")\"(\\s*?)((\\s*?)ProjectSection\\((.*?)\\) = (.*?)EndProjectSection(\\s*?))*(\\s*?)(EndProject)?", RegexOptions.Singleline);
static Regex projectDependenciesRegex = new Regex ("ProjectSection\\((.*?)\\) = \\w*(.*?)EndProjectSection", RegexOptions.Singleline);
static Regex projectDependencyRegex = new Regex ("\\s*(" + guidExpression + ") = (" + guidExpression + ")");
static Regex projectSectionPropertiesRegex = new Regex ("\\s*(?<name>.*) = \"(?<value>.*)\"");
@@ -139,6 +139,11 @@
ResolveAssemblyReferences;
AfterResolveReferences
</ResolveReferencesDependsOn>
<ResolveAssemblyReferencesDependsOn>
GetFrameworkPaths;
PrepareForBuild
</ResolveAssemblyReferencesDependsOn>
</PropertyGroup>
<Target Name="ResolveReferences" DependsOnTargets="$(ResolveReferencesDependsOn)"/>
@@ -146,7 +151,7 @@
<Target Name="BeforeResolveReferences" />
<Target Name="AfterResolveReferences" />
<Target Name="ResolveAssemblyReferences">
<Target Name="ResolveAssemblyReferences" DependsOnTargets="$(ResolveAssemblyReferencesDependsOn)">
<ResolveAssemblyReference
Assemblies="@(Reference)"
AssemblyFiles="@(ChildProjectReferences)"
@@ -139,6 +139,11 @@
ResolveAssemblyReferences;
AfterResolveReferences
</ResolveReferencesDependsOn>
<ResolveAssemblyReferencesDependsOn>
GetFrameworkPaths;
PrepareForBuild
</ResolveAssemblyReferencesDependsOn>
</PropertyGroup>
<Target Name="ResolveReferences" DependsOnTargets="$(ResolveReferencesDependsOn)"/>
@@ -146,7 +151,7 @@
<Target Name="BeforeResolveReferences" />
<Target Name="AfterResolveReferences" />
<Target Name="ResolveAssemblyReferences">
<Target Name="ResolveAssemblyReferences" DependsOnTargets="$(ResolveAssemblyReferencesDependsOn)">
<ResolveAssemblyReference
Assemblies="@(Reference)"
AssemblyFiles="@(ChildProjectReferences)"
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff. Show more