mirror of
https://github.com/BepInEx/mono.git
synced 2026-11-16 11:21:08 -10:00
Compare commits
241
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5077205a44 | ||
|
|
0d6f6f8f40 | ||
|
|
d6c24517f4 | ||
|
|
0f5c24054c | ||
|
|
3511ffcb2d | ||
|
|
188c235ca4 | ||
|
|
25ac18a9b7 | ||
|
|
d95d7d30fe | ||
|
|
82d42e61b1 | ||
|
|
4c98dc2006 | ||
|
|
4dc09dc922 | ||
|
|
d27287c77b | ||
|
|
1298269b88 | ||
|
|
2ce82742e8 | ||
|
|
81da99eb76 | ||
|
|
9667aa6485 | ||
|
|
1e856f02ff | ||
|
|
6ab979c9df | ||
|
|
02b6c24e5d | ||
|
|
87ad2c3690 | ||
|
|
3cde98344e | ||
|
|
1d0445bfc7 | ||
|
|
1d389ea02c | ||
|
|
ad60bf18b7 | ||
|
|
c20c0b3b81 | ||
|
|
d33f7f6de9 | ||
|
|
c8c005f137 | ||
|
|
1aa58e9a46 | ||
|
|
5673411799 | ||
|
|
1434f9c879 | ||
|
|
3598a4ab55 | ||
|
|
72cdd51acb | ||
|
|
ea3996571a | ||
|
|
bdf17346a6 | ||
|
|
37f8c76e38 | ||
|
|
cda97d6fc1 | ||
|
|
198ff835e9 | ||
|
|
ba317ed4e6 | ||
|
|
450d4d7a9e | ||
|
|
5da5fa26fb | ||
|
|
bee954cff2 | ||
|
|
762430b83e | ||
|
|
d717e1b1ea | ||
|
|
5a3893de5c | ||
|
|
6dc5ddd3d9 | ||
|
|
6f6232707c | ||
|
|
64a055b079 | ||
|
|
34a69b5e81 | ||
|
|
b8c96604c5 | ||
|
|
440fff5aee | ||
|
|
502a6a5e1b | ||
|
|
02f0d6ee9d | ||
|
|
4242008df5 | ||
|
|
12f8ebafed | ||
|
|
e6a3b54b37 | ||
|
|
b6255d35cd | ||
|
|
ff7a2e46e7 | ||
|
|
b83bdfd396 | ||
|
|
c686827dba | ||
|
|
b9b2d23f1a | ||
|
|
d845201db4 | ||
|
|
10fe0e89c0 | ||
|
|
83ca242114 | ||
|
|
5309190d7d | ||
|
|
98e0d8c486 | ||
|
|
a9d142eeb2 | ||
|
|
6149b5d569 | ||
|
|
851b6c7654 | ||
|
|
6462e3fc8e | ||
|
|
2eced64a82 | ||
|
|
e6c0a86e70 | ||
|
|
ad88c52d8e | ||
|
|
7e2f9aa7e8 | ||
|
|
dda961cf9a | ||
|
|
55a698e07d | ||
|
|
67489264b7 | ||
|
|
f23dca66a7 | ||
|
|
590080c39e | ||
|
|
452f94286b | ||
|
|
f342dae059 | ||
|
|
8fafb67859 | ||
|
|
71cc0a16c9 | ||
|
|
78c2486dcb | ||
|
|
f47f6a1dab | ||
|
|
052d1c2867 | ||
|
|
bdc6fd7f03 | ||
|
|
90faddac77 | ||
|
|
809fa3a3a8 | ||
|
|
7ce4e861df | ||
|
|
4e11ba5c8b | ||
|
|
9dafa35db6 | ||
|
|
51f9a82ecd | ||
|
|
5a3b524b60 | ||
|
|
d4df2e7aa9 | ||
|
|
4d40922fde | ||
|
|
082289cc15 | ||
|
|
ef4352cde5 | ||
|
|
9ed0907eea | ||
|
|
339c5249a7 | ||
|
|
df9df437ae | ||
|
|
d15985c4af | ||
|
|
98a9c23d70 | ||
|
|
4b82d60bbc | ||
|
|
c3452996bd | ||
|
|
65d1d7cdae | ||
|
|
d424096c05 | ||
|
|
6d11ff42da | ||
|
|
1c7614193f | ||
|
|
be6441b30d | ||
|
|
66f8f1aa53 | ||
|
|
a5c496fd46 | ||
|
|
b92bdff265 | ||
|
|
d27cc030bb | ||
|
|
5f5f25f58a | ||
|
|
0d0be3e704 | ||
|
|
414feeffc7 | ||
|
|
06060e290d | ||
|
|
37a593df33 | ||
|
|
c34e267b4c | ||
|
|
582b140f7d | ||
|
|
16c75ce329 | ||
|
|
72eabfe658 | ||
|
|
c8e14aa2ea | ||
|
|
ffcc54965d | ||
|
|
2d56aa09df | ||
|
|
ac26b00ca4 | ||
|
|
f77c835faf | ||
|
|
e319507866 | ||
|
|
cd5d8a9d1b | ||
|
|
5eae4df2ee | ||
|
|
9ecfd9f23a | ||
|
|
37de1b5b0d | ||
|
|
68392d0c90 | ||
|
|
715991f427 | ||
|
|
503f379a22 | ||
|
|
a36202bfea | ||
|
|
bbf84b172e | ||
|
|
62a0e75dd8 | ||
|
|
80e1e3a964 | ||
|
|
303981e264 | ||
|
|
05ff99fc73 | ||
|
|
24e82a5385 | ||
|
|
cd2579f7ce | ||
|
|
760ac86dd9 | ||
|
|
2b14612b1c | ||
|
|
94ced23f9a | ||
|
|
66905636c1 | ||
|
|
2fb26892dc | ||
|
|
4b62516d17 | ||
|
|
d78c35091b | ||
|
|
836896684c | ||
|
|
9528721b39 | ||
|
|
eff6063589 | ||
|
|
b600314281 | ||
|
|
a5808f9c71 | ||
|
|
785c82b5d1 | ||
|
|
dcc3c6090b | ||
|
|
08f150b1d9 | ||
|
|
a417e02c2d | ||
|
|
1a1d71d808 | ||
|
|
152e22549b | ||
|
|
ae2e60c61c | ||
|
|
9f78eca1af | ||
|
|
8cbef676c3 | ||
|
|
724c7df79c | ||
|
|
15e53eba9b | ||
|
|
7323343a64 | ||
|
|
c69dae3bcb | ||
|
|
661495317c | ||
|
|
2415374524 | ||
|
|
fa1030da6f | ||
|
|
a17a84caee | ||
|
|
44560f1e67 | ||
|
|
c52c4bd713 | ||
|
|
c8ca5929c7 | ||
|
|
d60a36ee80 | ||
|
|
cee57b3c78 | ||
|
|
fe75a6ee2f | ||
|
|
65956a952d | ||
|
|
b6b7ce3eff | ||
|
|
e6409c5953 | ||
|
|
2cc99a1681 | ||
|
|
d8b4f5d2ab | ||
|
|
0c315e92b0 | ||
|
|
5d7e4c9cf6 | ||
|
|
23fb3fe800 | ||
|
|
679777b17b | ||
|
|
f0c0314e4d | ||
|
|
10ee1bafc9 | ||
|
|
bceca5b359 | ||
|
|
4560d3c57f | ||
|
|
1c41089315 | ||
|
|
cb922c0fa6 | ||
|
|
fe9c5ebe97 | ||
|
|
51403d818e | ||
|
|
459d47bb9b | ||
|
|
63dde6cce0 | ||
|
|
640d5a03e4 | ||
|
|
19b866517a | ||
|
|
8953abc7d3 | ||
|
|
b78f4f6e5f | ||
|
|
9bd54596bb | ||
|
|
74d31d88ef | ||
|
|
d66823b37b | ||
|
|
f01f6476b5 | ||
|
|
bcf75c0b8c | ||
|
|
84b7173fcb | ||
|
|
2b673c3022 | ||
|
|
ff9ce3b7ff | ||
|
|
97056ba86a | ||
|
|
ceaa04d0b8 | ||
|
|
87a92c89c2 | ||
|
|
de1a4a0229 | ||
|
|
2f1bfa9788 | ||
|
|
6caddcd9d1 | ||
|
|
8a3e2b11e1 | ||
|
|
e2fa30543b | ||
|
|
8a113e88b3 | ||
|
|
d8e522c16c | ||
|
|
e476b1ac33 | ||
|
|
6fbe05fe9a | ||
|
|
440cd5475c | ||
|
|
dc34ec682c | ||
|
|
9deeb95816 | ||
|
|
171ba52158 | ||
|
|
4393b68452 | ||
|
|
76da2e9ed8 | ||
|
|
5006bcc901 | ||
|
|
50c26943d4 | ||
|
|
5596255efe | ||
|
|
a41069ad76 | ||
|
|
f70bda0c06 | ||
|
|
3ed19e6630 | ||
|
|
f404e04d6d | ||
|
|
6019eeb483 | ||
|
|
e37d7a2ce9 | ||
|
|
2440b14865 | ||
|
|
4f4cb919cf | ||
|
|
42a5eeb95a | ||
|
|
b65e5ee577 | ||
|
|
672282c892 |
No files matched your search
+3
-4
@@ -4,6 +4,9 @@ config.rpath crlf=input
|
||||
configure.host crlf=input
|
||||
mkinstalldirs crlf=input
|
||||
*.sh crlf=input
|
||||
*.sources crlf=input
|
||||
.gitattributes crlf=input
|
||||
*akefile* crlf=input
|
||||
|
||||
# ensure native line endings on checkout
|
||||
*.c crlf
|
||||
@@ -11,10 +14,6 @@ mkinstalldirs crlf=input
|
||||
*.cs crlf
|
||||
*.il crlf
|
||||
|
||||
.gitattributes crlf
|
||||
*akefile* crlf
|
||||
*.sources crlf
|
||||
|
||||
# don't do anything to line-endings. Let CRLFs go into the repo, and CRLF on checkout
|
||||
*.bat -crlf
|
||||
*.sln -crlf
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
[submodule "external/cecil"]
|
||||
path = external/cecil
|
||||
url = git://github.com/mono/cecil.git
|
||||
branch = mono-2017-02
|
||||
[submodule "external/rx"]
|
||||
path = external/rx
|
||||
url = git://github.com/mono/rx.git
|
||||
|
||||
+5
-13
@@ -44,10 +44,6 @@ dist-hook:
|
||||
rm -rf `find $(top_distdir)/external -path '*\.git'`
|
||||
rm -f `find $(top_distdir)/external -path '*\.exe' -not -path '*/roslyn-binaries/*'`
|
||||
rm -f `find $(top_distdir)/external -path '*\.dll' -not -path '*/binary-reference-assemblies/*' -not -path '*/roslyn-binaries/*'`
|
||||
cp mcs/class/lib/basic/System.Configuration.dll mcs/class/lib/monolite/
|
||||
cp mcs/class/lib/basic/System.Security.dll mcs/class/lib/monolite/
|
||||
# Disable this for now because it is very slow and causes wrench to timeout:
|
||||
# test ! -d $(GIT_DIR) || ./scripts/commits-to-changelog.py --root=$(distdir) last-commit-with-compulsory-changelog-entry
|
||||
|
||||
mac-sdk-package:
|
||||
external/bockbuild/bb MacSDK --package
|
||||
@@ -58,17 +54,13 @@ DISTCLEANFILES= mono-uninstalled.pc
|
||||
|
||||
# building with monolite
|
||||
mcslib = $(mcs_topdir)/class/lib
|
||||
monolite = $(mcslib)/monolite
|
||||
mono_corlib_version = $(shell sed -n "s/\#define MONO_CORLIB_VERSION //p" $(srcdir)/mono/metadata/appdomain.c)
|
||||
monolite_url = http://download.mono-project.com/monolite/monolite-$(mono_corlib_version)-latest.tar.gz
|
||||
monolite_url = https://download.mono-project.com/monolite/monolite-$(MONO_CORLIB_VERSION)-latest.tar.gz
|
||||
.PHONY: get-monolite-latest
|
||||
get-monolite-latest:
|
||||
-rm -fr $(mcslib)/monolite-*
|
||||
-mkdir -p $(mcslib)
|
||||
test ! -d $(monolite) || test ! -d $(monolite).old || rm -fr $(monolite).old
|
||||
test ! -d $(monolite) || mv -f $(monolite) $(monolite).old
|
||||
cd $(mcslib) && { (wget -O- $(monolite_url) || curl $(monolite_url)) | gzip -d | tar xf - ; }
|
||||
cd $(mcslib) && mv -f monolite-* monolite
|
||||
-rm -fr $(mcslib)/monolite/$(MONO_CORLIB_VERSION)
|
||||
-mkdir -p $(mcslib)/monolite
|
||||
cd $(mcslib) && { (wget -O- $(monolite_url) || curl -L $(monolite_url)) | gzip -d | tar xf - ; }
|
||||
cd $(mcslib) && mv -f monolite-* monolite/$(MONO_CORLIB_VERSION)
|
||||
|
||||
if BITCODE
|
||||
BITCODE_CHECK=yes
|
||||
|
||||
+20
-2
@@ -1,8 +1,7 @@
|
||||
# Process this file with autoconf to produce a configure script.
|
||||
#AC_PREREQ([2.62])
|
||||
|
||||
# when bumping version number below, keep it in sync with man/mono.1 too
|
||||
AC_INIT(mono, [4.9.0],
|
||||
AC_INIT(mono, [5.0.1],
|
||||
[http://bugzilla.xamarin.com/enter_bug.cgi?classification=Mono])
|
||||
|
||||
AC_CONFIG_SRCDIR([README.md])
|
||||
@@ -29,6 +28,24 @@ AC_PROG_LN_S
|
||||
|
||||
m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([yes])])
|
||||
|
||||
MONO_VERSION_MAJOR=`echo $VERSION | cut -d . -f 1`
|
||||
MONO_VERSION_MINOR=`echo $VERSION | cut -d . -f 2`
|
||||
MONO_VERSION_BUILD=`echo $VERSION | cut -d . -f 3`
|
||||
|
||||
# This is the version number of the corlib-runtime interface. When
|
||||
# making changes to this interface (by changing the layout
|
||||
# of classes the runtime knows about, changing icall signature or
|
||||
# semantics etc), increment this variable.
|
||||
#
|
||||
# This can be reset to 0 when Mono's version number is bumped
|
||||
# since it's part of the corlib version (the prefix '1' in the full
|
||||
# version number is to ensure the number isn't treated as octal in C)
|
||||
MONO_CORLIB_COUNTER=0
|
||||
MONO_CORLIB_VERSION=`printf "1%02d%02d%02d%03d" $MONO_VERSION_MAJOR $MONO_VERSION_MINOR $MONO_VERSION_BUILD $MONO_CORLIB_COUNTER`
|
||||
|
||||
AC_DEFINE_UNQUOTED(MONO_CORLIB_VERSION,$MONO_CORLIB_VERSION,[Version of the corlib-runtime interface])
|
||||
AC_SUBST(MONO_CORLIB_VERSION)
|
||||
|
||||
case $host_os in
|
||||
*cygwin* )
|
||||
echo "Run configure using ./configure --host=i686-pc-mingw32"
|
||||
@@ -4504,6 +4521,7 @@ fi
|
||||
}')]
|
||||
|
||||
echo "MONO_VERSION = $myver" >> $mcs_topdir/build/config.make
|
||||
echo "MONO_CORLIB_VERSION = $MONO_CORLIB_VERSION" >> $mcs_topdir/build/config.make
|
||||
|
||||
if test x$host_darwin = xyes; then
|
||||
echo "PLATFORM = darwin" >> $mcs_topdir/build/config.make
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
check-coverage crlf=input
|
||||
check-exports crlf=input
|
||||
produce-lists crlf=input
|
||||
+2
-1
@@ -160,7 +160,8 @@ typedef struct _GMemChunk GMemChunk;
|
||||
* Misc.
|
||||
*/
|
||||
|
||||
const gchar * g_getenv(const gchar *variable);
|
||||
gboolean g_hasenv(const gchar *variable);
|
||||
gchar * g_getenv(const gchar *variable);
|
||||
gboolean g_setenv(const gchar *variable, const gchar *value, gboolean overwrite);
|
||||
void g_unsetenv(const gchar *variable);
|
||||
|
||||
|
||||
+50
-4
@@ -39,23 +39,69 @@
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
static pthread_mutex_t env_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
|
||||
const gchar *
|
||||
g_getenv(const gchar *variable)
|
||||
/* MONO Comment
|
||||
*
|
||||
* As per the UNIX spec,
|
||||
* "The return value from getenv() may point to static data which may be overwritten by subsequent calls to getenv(), setenv(), or unsetenv()."
|
||||
* Source: Unix Manual Pages for getenv, IEEE Std 1003.1
|
||||
*
|
||||
* This means that using pointers returned from getenv may (and does) lead to many
|
||||
* pointers which refer to the same piece of memory. When one is freed, all will be freed.
|
||||
*
|
||||
* This is unsafe and an ergonomics risk to fix in the callers. While the caller could lock,
|
||||
* this introduces the risk for looping or exiting while inside of a lock. For this reason,
|
||||
* g_getenv does not mimic the behavior of POSIX getenv anymore.
|
||||
*
|
||||
* The memory address returned will be unique to the invocaton, and must be freed.
|
||||
* */
|
||||
gchar *
|
||||
g_getenv (const gchar *variable)
|
||||
{
|
||||
return getenv(variable);
|
||||
gchar *ret = NULL;
|
||||
pthread_mutex_lock (&env_lock);
|
||||
gchar *res = getenv(variable);
|
||||
if (res)
|
||||
ret = g_strdup(res);
|
||||
pthread_mutex_unlock (&env_lock);
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
/*
|
||||
* This function checks if the given variable is non-NULL
|
||||
* in the environment. It's useful because it removes memory
|
||||
* freeing requirements.
|
||||
*
|
||||
*/
|
||||
gboolean
|
||||
g_hasenv (const gchar *variable)
|
||||
{
|
||||
pthread_mutex_lock (&env_lock);
|
||||
gchar *res = getenv(variable);
|
||||
gboolean not_null = (res != NULL);
|
||||
pthread_mutex_unlock (&env_lock);
|
||||
|
||||
return not_null;
|
||||
}
|
||||
|
||||
gboolean
|
||||
g_setenv(const gchar *variable, const gchar *value, gboolean overwrite)
|
||||
{
|
||||
return setenv(variable, value, overwrite) == 0;
|
||||
gboolean res;
|
||||
pthread_mutex_lock (&env_lock);
|
||||
res = (setenv(variable, value, overwrite) == 0);
|
||||
pthread_mutex_unlock (&env_lock);
|
||||
return res;
|
||||
}
|
||||
|
||||
void
|
||||
g_unsetenv(const gchar *variable)
|
||||
{
|
||||
pthread_mutex_lock (&env_lock);
|
||||
unsetenv(variable);
|
||||
pthread_mutex_unlock (&env_lock);
|
||||
}
|
||||
|
||||
gchar*
|
||||
|
||||
@@ -39,7 +39,13 @@
|
||||
#include <io.h>
|
||||
#include <assert.h>
|
||||
|
||||
const gchar *
|
||||
gboolean
|
||||
g_hasenv (const gchar *variable)
|
||||
{
|
||||
return g_getenv (variable) != NULL;
|
||||
}
|
||||
|
||||
gchar *
|
||||
g_getenv(const gchar *variable)
|
||||
{
|
||||
gunichar2 *var, *buffer;
|
||||
|
||||
Vendored
+1
-1
Submodule external/binary-reference-assemblies updated: 6c77197318...febc100f03.
Vendored
+1
-1
Submodule external/cecil updated: f7733aca62...7801534de1.
Vendored
+1
-1
Submodule external/corefx updated: f7ed7c88fe...bd96ae5f14.
Vendored
+1
-1
Submodule external/nuget-buildtasks updated: 04bdab55d8...8d307472ea.
Vendored
+1
-1
Submodule external/roslyn-binaries updated: 69ce5c6b08...0d4198b129.
+57
-18
@@ -2,31 +2,22 @@
|
||||
.if t .sp .5v
|
||||
.if n .sp
|
||||
..
|
||||
.TH csharp 1 "4 September 2008"
|
||||
.TH csharp 1 "22 March 2017"
|
||||
.SH NAME
|
||||
csharp, gsharp \- Interactive C# Shell
|
||||
csharp \- Interactive C# Shell and Scripting
|
||||
.SH SYNOPSIS
|
||||
.B csharp [--attach PID] [-e EXPRESSION] [file1 [file2]]
|
||||
[options]
|
||||
.P
|
||||
.B gsharp [file1 [file2]]
|
||||
[compiler-options] [--|-s script-options]
|
||||
.SH DESCRIPTION
|
||||
The
|
||||
.I csharp
|
||||
is an interactive C# shell that allows the user to enter and evaluate
|
||||
C# statements and expressions from the command line. The regular
|
||||
command is an interactive C# shell and scripting host that allows
|
||||
the user to enter and evaluate C# statements and expressions from
|
||||
the command line or execute C# scripts.
|
||||
The regular
|
||||
.I mcs
|
||||
command line options can be used in this version of the compiler.
|
||||
.PP
|
||||
The
|
||||
.I gsharp
|
||||
command is a GUI version of the C# interpreter that uses Gtk# and
|
||||
provides an area to attach widgets as well. This version can be
|
||||
attached to other Gtk# applications in a safe way as it injects itself
|
||||
into the main loop of a Gtk# application, avoiding any problems
|
||||
arising from the multi-threaded nature of injecting itself into a
|
||||
target process.
|
||||
.PP
|
||||
Files specified in the command line will be loaded and executed as
|
||||
scripts.
|
||||
.PP
|
||||
@@ -35,9 +26,31 @@ Starting with Mono 2.10, the
|
||||
command can be used as an interpreter executed by executables flagged
|
||||
with the Unix execute attribute. To do this, make the first line of
|
||||
your C# source code look like this:
|
||||
.PP
|
||||
.nf
|
||||
"#!/usr/bin/csharp"
|
||||
Console.WriteLine ("Hello, World");
|
||||
#!/usr/bin/csharp
|
||||
Console.WriteLine ("Hello, World");
|
||||
.fi
|
||||
.PP
|
||||
Starting with Mono 5.0, command line arguments may now be passed
|
||||
to the
|
||||
.I csharp
|
||||
command by specifying either the
|
||||
.I -s
|
||||
or
|
||||
.I --
|
||||
(script) options.
|
||||
.PP
|
||||
The
|
||||
.I -s
|
||||
option is ideal for interpreting executable scripts that utilize
|
||||
shebang syntax (introduced in Mono 2.10). This allows command line
|
||||
arguments to be passed to and consumed cleanly by the script:
|
||||
.PP
|
||||
.nf
|
||||
#!/usr/bin/csharp -s
|
||||
foreach (var arg in Args)
|
||||
Console.WriteLine ($"script argument: {arg}");
|
||||
.fi
|
||||
.SH OPTIONS
|
||||
The commands accept all of the commands that are available to the
|
||||
@@ -45,6 +58,23 @@ The commands accept all of the commands that are available to the
|
||||
command, so you can reference assemblies, specify paths, language
|
||||
level and so on from the command line. In addition, the following
|
||||
command line options are supported:
|
||||
.TP
|
||||
.I "\-s" SCRIPT_FILE
|
||||
This option is ideal for authoring executable scripts that utilize
|
||||
the Unix shebang feature. Unix will implicitly append as an argument
|
||||
the path of the script to execute. When the executable is invoked,
|
||||
any arguments then passed to it will be available in the
|
||||
.I Args
|
||||
global. Example:
|
||||
.I "#!/usr/bin/env csharp -s"
|
||||
.TP
|
||||
.I "\-\-"
|
||||
Any arguments that follow will not be passed to the compiler driver,
|
||||
and instead will be made available in the
|
||||
.I Args
|
||||
global. Example:
|
||||
.I csharp -- a b c
|
||||
will result in Args = { "a", "b", "c" } in the interactive shell.
|
||||
.TP
|
||||
.I "\-\-attach"
|
||||
This is an advanced option and should only be used if you have a deep
|
||||
@@ -290,6 +320,15 @@ statements and expressions are executed are static, they can be
|
||||
invoked directly from the shell. These are the available properties
|
||||
and methods:
|
||||
.TP
|
||||
.I Args
|
||||
An easy to consume array of any arguments specified after either
|
||||
.I -s
|
||||
or
|
||||
.I --
|
||||
on the command line. Ideal for self-executing scripts utilizing the
|
||||
.I -s
|
||||
option.
|
||||
.TP
|
||||
.I void LoadAssembly(string assembly)
|
||||
Loads the given assembly. This is equivalent to passing the compiler
|
||||
the -r: flag with the specified string.
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@
|
||||
.if t .sp .5v
|
||||
.if n .sp
|
||||
..
|
||||
.TH gacutil "Mono 1.0"
|
||||
.TH Mono "gacutil"
|
||||
.SH NAME
|
||||
gacutil \- Global Assembly Cache management utility.
|
||||
.SH SYNOPSIS
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
.if t .sp .5v
|
||||
.if n .sp
|
||||
..
|
||||
.TH lc "Mono 2.6"
|
||||
.TH Mono "lc"
|
||||
.SH NAME
|
||||
lc \- Mono License Compiler
|
||||
.SH SYNOPSIS
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@
|
||||
.if t .sp .5v
|
||||
.if n .sp
|
||||
..
|
||||
.TH macpack "Mono 1.0"
|
||||
.TH Mono "macpack"
|
||||
.SH NAME
|
||||
macpack \- Macintosh OS X Packager for managed gui assemblies
|
||||
.SH SYNOPSIS
|
||||
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
.\"
|
||||
.\" mono manual page.
|
||||
.\" mdb2ppdb manual page.
|
||||
.\" Copyright 2017 Microsoft
|
||||
.\"
|
||||
.TH Mono "Mono 4.8.0"
|
||||
.TH Mono "mdb2ppdb"
|
||||
.SH NAME
|
||||
mdb2ppdb \- Convert Mono's debug file format (MDB) to Portable Program
|
||||
Database (PPDB) file formatn
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@
|
||||
.if t .sp .5v
|
||||
.if n .sp
|
||||
..
|
||||
.TH mkbundle "mkbundle 1.0"
|
||||
.TH Mono "mkbundle"
|
||||
.SH NAME
|
||||
mkbundle, mkbundle2 \- Creates a bundled executable.
|
||||
.SH SYNOPSIS
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
.\" Miguel de Icaza ([email protected])
|
||||
.\" Paolo Molaro ([email protected])
|
||||
.\"
|
||||
.TH Mono "Mono 1.0"
|
||||
.TH Mono "mono-config"
|
||||
.SH NAME
|
||||
mono-config \- Mono runtime file format configuration
|
||||
.SH DESCRIPTION
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@
|
||||
.if t .sp .5v
|
||||
.if n .sp
|
||||
..
|
||||
.TH Mono "Mono 1.0"
|
||||
.TH Mono "mono-service"
|
||||
.SH NAME
|
||||
mono-service, mono-service2 \- Mono ServiceProcess host
|
||||
.SH SYNOPSIS
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@
|
||||
.if t .sp .5v
|
||||
.if n .sp
|
||||
..
|
||||
.TH mono-xmltool "Mono 1.0"
|
||||
.TH Mono "mono-xmltool"
|
||||
.SH NAME
|
||||
mono-xmltool \- Mono XML validation and transformation tool.
|
||||
.SH SYNOPSIS
|
||||
|
||||
+95
-27
@@ -7,7 +7,7 @@
|
||||
.\" Author:
|
||||
.\" Miguel de Icaza ([email protected])
|
||||
.\"
|
||||
.TH Mono "Mono 4.7.0"
|
||||
.TH Mono "mono"
|
||||
.SH NAME
|
||||
mono \- Mono's ECMA-CLI native code generator (Just-in-Time and Ahead-of-Time)
|
||||
.SH SYNOPSIS
|
||||
@@ -104,11 +104,6 @@ than one can be specified:
|
||||
.RS
|
||||
.ne 8
|
||||
.TP
|
||||
.I autoreg
|
||||
The AOT compiler will emit a (ELF only) library initializer to automatically
|
||||
register the aot compiled module with the runtime. This is only useful in static
|
||||
mode
|
||||
.TP
|
||||
.I asmonly
|
||||
Instructs the AOT compiler to output assembly code instead of an
|
||||
object file.
|
||||
@@ -118,11 +113,6 @@ object file.
|
||||
If specified, forces the generated AOT files to be bound to the
|
||||
runtime version of the compiling Mono. This will prevent the AOT
|
||||
files from being consumed by a different Mono runtime.
|
||||
.I full
|
||||
.Sp
|
||||
This is currently an experimental feature as it is not complete.
|
||||
This instructs Mono to precompile code that has historically not been
|
||||
precompiled with AOT.
|
||||
.TP
|
||||
.I data-outfile=FILE.dll.aotdata
|
||||
.Sp
|
||||
@@ -134,10 +124,59 @@ on demand by using the
|
||||
.I mono_install_load_aot_data_hook
|
||||
method.
|
||||
.TP
|
||||
.I direct-icalls
|
||||
.Sp
|
||||
When this option is specified, icalls (internal calls made from the
|
||||
standard library into the mono runtime code) are invoked directly
|
||||
instead of going through the operating system symbol lookup operation.
|
||||
This requires use of the
|
||||
.I static
|
||||
option.
|
||||
.TP
|
||||
.I direct-pinvoke
|
||||
.Sp
|
||||
When this option is specified, P/Invoke methods are invoked directly
|
||||
instead of going through the operating system symbol lookup operation.
|
||||
This requires use of the
|
||||
.I static
|
||||
option.
|
||||
.TP
|
||||
.I dwarfdebug
|
||||
Instructs the AOT compiler to emit DWARF debugging information. When
|
||||
used together with the nodebug option, only DWARF debugging
|
||||
information is emitted, but not the information that can be used at
|
||||
runtime.
|
||||
.TP
|
||||
.I full
|
||||
.Sp
|
||||
This creates binaries which can be used with the --full-aot option.
|
||||
.TP
|
||||
.I hybrid
|
||||
.Sp
|
||||
This creates binaries which can be used with the --hybrid-aot option.
|
||||
.TP
|
||||
.I llvm
|
||||
AOT will be performed with the LLVM backend instead of the Mono backend where possible. This will be slower to compile but most likely result in a performance improvement.
|
||||
.TP
|
||||
.I llvmonly
|
||||
AOT will be performed with the LLVM backend exclusively and the Mono backend will not be used. The only output in this mode will be the bitcode file normally specified with the
|
||||
.I llvm-outfile
|
||||
option. Use of
|
||||
.I llvmonly
|
||||
automatically enables the
|
||||
.I full
|
||||
and
|
||||
.I llvm
|
||||
options. This feature is experimental.
|
||||
.TP
|
||||
.I llvm-outfile=[filename]
|
||||
Gives the path for the temporary LLVM bitcode file created during AOT.
|
||||
.TP
|
||||
.I info
|
||||
Print the architecture the AOT in this copy of Mono targets and quit.
|
||||
.TP
|
||||
.I ld-flags
|
||||
Additional flags to pass to the C linker (if the current AOT mode calls for invoking it).
|
||||
.TP
|
||||
.I llvm-path=<PREFIX>
|
||||
Same for the llvm tools 'opt' and 'llc'.
|
||||
@@ -156,7 +195,12 @@ llc compiler.
|
||||
.I nimt-trampolines=[number]
|
||||
When compiling in full aot mode, the IMT trampolines must be precreated
|
||||
in the AOT image. You can add additional method trampolines with this argument.
|
||||
Defaults to 128.
|
||||
Defaults to 512.
|
||||
.TP
|
||||
.I ngsharedvt-trampolines=[number]
|
||||
When compiling in full aot mode, the value type generic sharing trampolines must be precreated
|
||||
in the AOT image. You can add additional method trampolines with this argument.
|
||||
Defaults to 512.
|
||||
.TP
|
||||
.I nodebug
|
||||
Instructs the AOT compiler to not output any debugging information.
|
||||
@@ -166,23 +210,22 @@ This prevents the AOT compiler from generating a direct calls to a
|
||||
method. The AOT compiler usually generates direct calls for certain
|
||||
methods that do not require going through the PLT (for example,
|
||||
methods that are known to not require a hook like a static
|
||||
constructor) or call into simple internal calls.
|
||||
.TP
|
||||
.I dwarfdebug
|
||||
Instructs the AOT compiler to emit DWARF debugging information. When
|
||||
used together with the nodebug option, only DWARF debugging
|
||||
information is emitted, but not the information that can be used at
|
||||
runtime.
|
||||
constructor) or call into simple internal calls.
|
||||
.TP
|
||||
.I nrgctx-trampolines=[number]
|
||||
When compiling in full aot mode, the generic sharing trampolines must be precreated
|
||||
in the AOT image. You can add additional method trampolines with this argument.
|
||||
Defaults to 1024.
|
||||
Defaults to 4096.
|
||||
.TP
|
||||
.I nrgctx-fetch-trampolines=[number]
|
||||
When compiling in full aot mode, the generic sharing fetch trampolines must be precreated
|
||||
in the AOT image. You can add additional method trampolines with this argument.
|
||||
Defaults to 128.
|
||||
.TP
|
||||
.I ntrampolines=[number]
|
||||
When compiling in full aot mode, the method trampolines must be precreated
|
||||
in the AOT image. You can add additional method trampolines with this argument.
|
||||
Defaults to 1024.
|
||||
Defaults to 4096.
|
||||
.TP
|
||||
.I outfile=[filename]
|
||||
Instructs the AOT compiler to save the output to the specified file.
|
||||
@@ -191,6 +234,16 @@ Instructs the AOT compiler to save the output to the specified file.
|
||||
If the AOT compiler cannot compile a method for any reason, enabling this flag
|
||||
will output the skipped methods to the console.
|
||||
.TP
|
||||
.I profile=[file]
|
||||
Specify a file to use for profile-guided optimization. See the "AOT PROFILING" section. To specify multiple files, include the
|
||||
.I profile
|
||||
option multiple times.
|
||||
.TP
|
||||
.I profile-only
|
||||
AOT *only* the methods described in the files specified with the
|
||||
.I profile
|
||||
option. See the "AOT PROFILING" section.
|
||||
.TP
|
||||
.I readonly-value=namespace.typename.fieldname=type/value
|
||||
Override the value of a static readonly field. Usually, during JIT
|
||||
compilation, the static constructor is ran eagerly, so the value of
|
||||
@@ -203,7 +256,6 @@ Note that signed/unsigned numbers do not matter here, just the storage size.
|
||||
This option can be specified multiple times and it doesn't prevent the static
|
||||
constructor for the type defining the field to execute with the usual rules
|
||||
at runtime (hence possibly computing a different value for the field).
|
||||
|
||||
.TP
|
||||
.I save-temps,keep-temps
|
||||
Instructs the AOT compiler to keep temporary files.
|
||||
@@ -232,6 +284,9 @@ mono_aot_register_module (mono_aot_module_hello_info);
|
||||
.I stats
|
||||
Print various stats collected during AOT compilation.
|
||||
.TP
|
||||
.I temp_path=[path]
|
||||
Explicitly specify path to store temporary files created during AOT compilation.
|
||||
.TP
|
||||
.I threads=[number]
|
||||
This is an experimental option for the AOT compiler to use multiple threads
|
||||
when compiling the methods.
|
||||
@@ -241,8 +296,11 @@ Prepends <PREFIX> to the name of tools ran by the AOT compiler, i.e. 'as'/'ld'.
|
||||
example, --tool=prefix=arm-linux-gnueabi- will make the AOT compiler run
|
||||
'arm-linux-gnueabi-as' instead of 'as'.
|
||||
.TP
|
||||
.I write-symbols
|
||||
Instructs the AOT compiler to emit debug symbol information.
|
||||
.I verbose
|
||||
Prints additional information about type loading failures.
|
||||
.TP
|
||||
.I write-symbols,no-write-symbols
|
||||
Instructs the AOT compiler to emit (or not emit) debug symbol information.
|
||||
.PP
|
||||
For more information about AOT, see: http://www.mono-project.com/docs/advanced/aot/
|
||||
.RE
|
||||
@@ -318,10 +376,12 @@ the heap as much as possible at the expense of slowing down garbage
|
||||
collection a bit.
|
||||
.TP
|
||||
\fB--full-aot\fR
|
||||
This is an experimental flag that instructs the Mono runtime to not
|
||||
This flag instructs the Mono runtime to not
|
||||
generate any code at runtime and depend exclusively on the code
|
||||
generated from using mono --aot=full previously. This is useful for
|
||||
platforms that do not permit dynamic code generation.
|
||||
generated from using mono --aot=full previously. This is useful for
|
||||
platforms that do not permit dynamic code generation, or if you need
|
||||
to run assemblies that have been stripped of IL (for example using
|
||||
mono-cil-strip).
|
||||
.Sp
|
||||
Notice that this feature will abort execution at runtime if a codepath
|
||||
in your program, or Mono's class libraries attempts to generate code
|
||||
@@ -351,6 +411,14 @@ will switch to '/bin/mono64' iff '/bin/mono' is a 32-bit build).
|
||||
\fB--help\fR, \fB-h\fR
|
||||
Displays usage instructions.
|
||||
.TP
|
||||
\fB--hybrid-aot\fR
|
||||
This flag allows the Mono runtime to run assemblies
|
||||
that have been stripped of IL, for example using mono-cil-strip. For this to
|
||||
work, the assembly must have been AOT compiled with --aot=hybrid.
|
||||
|
||||
This flag is similar to --full-aot, but it does not disable the JIT. This means
|
||||
you can use dynamic features such as System.Reflection.Emit.
|
||||
.TP
|
||||
\fB--llvm\fR
|
||||
If the Mono runtime has been compiled with LLVM support (not available
|
||||
in all configurations), Mono will use the LLVM optimization and code
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@
|
||||
.if t .sp .5v
|
||||
.if n .sp
|
||||
..
|
||||
.TH resgen "resgen 1.0"
|
||||
.TH Mono "resgen"
|
||||
.SH NAME
|
||||
resgen, resgen2 \- Mono/CLI Resource Generator
|
||||
.SH SYNOPSIS
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
/LICENSE.MSPL -crlf
|
||||
/ScalableMonoIcon.svg -crlf
|
||||
/winexe.in crlf=input
|
||||
+2
-1
@@ -12,7 +12,8 @@ clean-local:
|
||||
|
||||
common/Consts.cs: common/Consts.cs.in $(wildcard config.make)
|
||||
test -n '$(MONO_VERSION)'
|
||||
sed -e 's,@''MONO_VERSION@,$(MONO_VERSION),' $< > $@
|
||||
test -n '$(MONO_CORLIB_VERSION)'
|
||||
sed -e 's,@''MONO_VERSION@,$(MONO_VERSION),' -e 's,@''MONO_CORLIB_VERSION@,$(MONO_CORLIB_VERSION),' $< > $@
|
||||
|
||||
PLATFORMS = darwin linux win32
|
||||
PROFILES = \
|
||||
|
||||
@@ -38,6 +38,7 @@ static class Consts
|
||||
public const string MonoCompany = "Mono development team";
|
||||
public const string MonoProduct = "Mono Common Language Infrastructure";
|
||||
public const string MonoCopyright = "(c) Various Mono authors";
|
||||
public const int MonoCorlibVersion = @MONO_CORLIB_VERSION@;
|
||||
|
||||
#if MOBILE
|
||||
// Versions of .NET Framework for Silverlight 4.0
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
# -*- makefile -*-
|
||||
#
|
||||
# Platform-specific makefile rules. This one's for linux.
|
||||
# Platform-specific makefile rules. This one's for macOS.
|
||||
#
|
||||
|
||||
PLATFORM_MCS_FLAGS =
|
||||
PLATFORM_RUNTIME = $(RUNTIME)
|
||||
PLATFORM_CORLIB = mscorlib.dll
|
||||
PLATFORM_TEST_HARNESS_EXCLUDES = NotOnMac,
|
||||
PLATFORM_TEST_HARNESS_EXCLUDES = NotOnMac,MacNotWorking,
|
||||
|
||||
EXTERNAL_MCS = mcs
|
||||
EXTERNAL_MBAS = mbas
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
# -*- makefile -*-
|
||||
|
||||
with_mono_path_monolite = MONO_PATH="$(topdir)/class/lib/monolite$(PLATFORM_PATH_SEPARATOR)$(topdir)/class/lib/monolite/Facades$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH"
|
||||
monolite_path := $(topdir)/class/lib/monolite/$(MONO_CORLIB_VERSION)
|
||||
|
||||
with_mono_path_monolite = MONO_PATH="$(monolite_path)$(PLATFORM_PATH_SEPARATOR)$(monolite_path)/Facades$(PLATFORM_PATH_SEPARATOR)$$MONO_PATH"
|
||||
|
||||
monolite_flag := $(depsdir)/use-monolite
|
||||
use_monolite := $(wildcard $(monolite_flag))
|
||||
|
||||
MONOLITE_MSCORLIB = $(topdir)/class/lib/monolite/mscorlib.dll
|
||||
MONOLITE_MSCORLIB = $(monolite_path)/mscorlib.dll
|
||||
|
||||
ifdef use_monolite
|
||||
ifdef MCS_MODE
|
||||
CSC_LOCATION = $(topdir)/class/lib/monolite/mcs.exe
|
||||
CSC_LOCATION = $(monolite_path)/mcs.exe
|
||||
endif
|
||||
|
||||
PROFILE_RUNTIME = $(with_mono_path_monolite) $(RUNTIME)
|
||||
@@ -79,8 +81,7 @@ do-profile-check: $(depsdir)/.stamp
|
||||
$(MAKE) $(MAKE_Q) do-profile-check-monolite ; \
|
||||
else \
|
||||
echo "*** The runtime '$(PROFILE_RUNTIME)' doesn't appear to be usable." 1>&2; \
|
||||
echo "*** You need Mono version 4.8 or better installed to build MCS" 1>&2 ; \
|
||||
echo "*** Check mono README for information on how to bootstrap a Mono installation." 1>&2 ; \
|
||||
echo "*** Check README for information on how to bootstrap a Mono installation." 1>&2 ; \
|
||||
exit 1; fi; fi
|
||||
|
||||
|
||||
@@ -89,7 +90,7 @@ ifdef use_monolite
|
||||
do-get-monolite:
|
||||
|
||||
do-profile-check-monolite:
|
||||
@echo "*** The contents of your 'monolite' directory may be out-of-date" 1>&2
|
||||
@echo "*** The contents of your 'monolite/$(MONO_CORLIB_VERSION)' directory may be out-of-date" 1>&2
|
||||
@echo "*** You may want to try 'make get-monolite-latest'" 1>&2
|
||||
rm -f $(monolite_flag)
|
||||
exit 1
|
||||
@@ -97,12 +98,12 @@ do-profile-check-monolite:
|
||||
else
|
||||
|
||||
do-get-monolite:
|
||||
@echo "*** Downloading bootstrap required 'monolite'" 1>&2
|
||||
@echo "*** Downloading bootstrap required 'monolite/$(MONO_CORLIB_VERSION)'" 1>&2
|
||||
$(MAKE) $(MAKE_Q) -C $(mono_build_root) get-monolite-latest
|
||||
|
||||
do-profile-check-monolite: $(depsdir)/.stamp
|
||||
@echo "*** The runtime '$(PROFILE_RUNTIME)' doesn't appear to be usable." 1>&2
|
||||
@echo "*** Trying the 'monolite' directory." 1>&2
|
||||
@echo "*** Trying the 'monolite/$(MONO_CORLIB_VERSION)' directory." 1>&2
|
||||
@echo dummy > $(monolite_flag)
|
||||
$(MAKE) do-profile-check
|
||||
|
||||
|
||||
@@ -43,3 +43,5 @@ MOBILE_PROFILE = yes
|
||||
NO_CONSOLE = yes
|
||||
|
||||
PROFILE_DISABLE_BTLS=1
|
||||
MONO_FEATURE_APPLETLS=1
|
||||
ONLY_APPLETLS=1
|
||||
@@ -9,3 +9,6 @@ NO_THREAD_SUSPEND_RESUME=1
|
||||
NO_MULTIPLE_APPDOMAINS=1
|
||||
NO_PROCESS_START=1
|
||||
NO_MONO_SECURITY=1
|
||||
MONO_FEATURE_APPLETLS=
|
||||
ONLY_APPLETLS=
|
||||
MONO_FEATURE_APPLE_X509=1
|
||||
@@ -10,3 +10,6 @@ NO_THREAD_SUSPEND_RESUME=1
|
||||
# so we need a System.dll that can do that.
|
||||
#NO_PROCESS_START=1
|
||||
NO_MONO_SECURITY=1
|
||||
MONO_FEATURE_APPLETLS=
|
||||
ONLY_APPLETLS=
|
||||
MONO_FEATURE_APPLE_X509=1
|
||||
@@ -15,3 +15,4 @@ PROFILE_MCS_FLAGS = -d:NET_4_0 -d:NET_4_5 -d:NET_4_6 -d:MONO -d:WIN_PLATFORM -no
|
||||
|
||||
FRAMEWORK_VERSION = 4.5
|
||||
XBUILD_VERSION = 4.0
|
||||
MONO_FEATURE_APPLETLS=1
|
||||
@@ -39,3 +39,5 @@ MOBILE_PROFILE = yes
|
||||
NO_CONSOLE = yes
|
||||
|
||||
PROFILE_DISABLE_BTLS=1
|
||||
MONO_FEATURE_APPLETLS=1
|
||||
ONLY_APPLETLS=1
|
||||
@@ -18,5 +18,6 @@ NO_SYSTEM_DRAWING_DEPENDENCY=1
|
||||
NO_SYSTEM_SERVICEMODEL_ACTIVATION_DEPENDENCY=1
|
||||
NO_SYSTEM_DESIGN_DEPENDENCY=1
|
||||
NO_SYSTEM_DIRECTORY_SERVICES_DEPENDENCY=1
|
||||
|
||||
PROFILE_DISABLE_BTLS=1
|
||||
MONO_FEATURE_APPLETLS=1
|
||||
ONLY_APPLETLS=1
|
||||
@@ -33,7 +33,7 @@ USE_MCS_FLAGS = /codepage:$(CODEPAGE) /nologo /noconfig /deterministic $(LOCAL_M
|
||||
USE_MBAS_FLAGS = /codepage:$(CODEPAGE) $(LOCAL_MBAS_FLAGS) $(PLATFORM_MBAS_FLAGS) $(PROFILE_MBAS_FLAGS) $(MBAS_FLAGS)
|
||||
USE_CFLAGS = $(LOCAL_CFLAGS) $(CFLAGS) $(CPPFLAGS)
|
||||
CSCOMPILE = $(Q_MCS) $(MCS) $(USE_MCS_FLAGS)
|
||||
CSC_RUNTIME_FLAGS = --aot-path=$(topdir)/class/lib/$(BUILD_TOOLS_PROFILE) --gc-params=nursery-size=64m
|
||||
CSC_RUNTIME_FLAGS = --aot-path=$(abspath $(topdir)/class/lib/$(BUILD_TOOLS_PROFILE)) --gc-params=nursery-size=64m
|
||||
BASCOMPILE = $(MBAS) $(USE_MBAS_FLAGS)
|
||||
CCOMPILE = $(CC) $(USE_CFLAGS)
|
||||
BOOT_COMPILE = $(Q_MCS) $(BOOTSTRAP_MCS) $(USE_MCS_FLAGS)
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
/lib
|
||||
/compat/
|
||||
monolite-*.tar.gz
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
TypeForwarders.cs
|
||||
AssemblyInfo.cs
|
||||
SR.cs
|
||||
../../../../external/corefx/src/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/IncrementalHash.net46.cs
|
||||
../../../../external/corefx/src/System.Security.Cryptography.Algorithms/src/System/Security/Cryptography/IncrementalHash.net46.cs
|
||||
@@ -9,7 +9,8 @@ LIBRARY_INSTALL_DIR = $(mono_libdir)/mono/$(FRAMEWORK_VERSION)/Facades
|
||||
|
||||
LIBRARY = netstandard.dll
|
||||
|
||||
KEY_FILE = ../../msfinal.pub
|
||||
KEY_FILE = ../../Open.snk
|
||||
LIBRARY_SNK = $(KEY_FILE)
|
||||
SIGN_FLAGS = /delaysign /keyfile:$(KEY_FILE) /nowarn:1616,1699 /nowarn:618
|
||||
LIB_REFS = System System.Xml System.Xml.Linq System.Runtime.Serialization System.Core System.Numerics System.Net.Http System.Transactions \
|
||||
System.IO.Compression System.Data System.ComponentModel.Composition System.IO.Compression.FileSystem \
|
||||
@@ -21,7 +22,7 @@ else
|
||||
LIB_REFS += System.Web System.Drawing
|
||||
endif
|
||||
|
||||
LIB_MCS_FLAGS = $(SIGN_FLAGS)
|
||||
LIB_MCS_FLAGS = $(SIGN_FLAGS) $(EXTRA_LIB_MCS_FLAGS)
|
||||
|
||||
PLATFORM_DEBUG_FLAGS =
|
||||
|
||||
|
||||
+14
-3
@@ -2,6 +2,12 @@ thisdir = class
|
||||
|
||||
pcl_facade_dirs := Facades
|
||||
|
||||
-include ../build/config.make
|
||||
|
||||
ifdef MCS_MODE
|
||||
MCS_MODE_dirs := Mono.Cecil.Mdb
|
||||
endif
|
||||
|
||||
# The minimal set of csc dependencies
|
||||
basic_SUBDIRS := \
|
||||
corlib \
|
||||
@@ -14,6 +20,7 @@ basic_SUBDIRS := \
|
||||
System.Xml.Linq \
|
||||
System.Runtime.InteropServices.RuntimeInformation \
|
||||
Mono.Cecil \
|
||||
$(MCS_MODE_dirs) \
|
||||
../tools/cil-stringreplacer
|
||||
|
||||
# resgen is corlib specific so we need to wait until corlib is build
|
||||
@@ -33,12 +40,11 @@ build_SUBDIRS := \
|
||||
System.Runtime.InteropServices.RuntimeInformation \
|
||||
System.IO.Compression \
|
||||
Mono.Cecil \
|
||||
$(MCS_MODE_dirs) \
|
||||
Mono.CompilerServices.SymbolWriter \
|
||||
PEAPI \
|
||||
../tools/cil-stringreplacer
|
||||
|
||||
-include ../build/config.make
|
||||
|
||||
ifdef MCS_MODE
|
||||
basic_PARALLEL_SUBDIRS := ../mcs
|
||||
build_PARALLEL_SUBDIRS := ../mcs
|
||||
@@ -384,7 +390,7 @@ all-local $(STD_TARGETS:=-local):
|
||||
|
||||
all-local-aot:
|
||||
|
||||
monolite_dir := monolite
|
||||
monolite_dir := monolite/$(MONO_CORLIB_VERSION)
|
||||
|
||||
# Files needed to bootstrap C# compiler
|
||||
build_files = mscorlib.dll System.dll System.Xml.dll Mono.Security.dll System.Core.dll System.Security.dll System.Configuration.dll \
|
||||
@@ -419,6 +425,11 @@ $(build_files:%=lib/build/%):
|
||||
|
||||
dist-monolite: $(monolite_files) lib/$(monolite_dir)/mcs.exe
|
||||
|
||||
package-monolite-latest:
|
||||
MONOLITE=monolite-$(MONO_CORLIB_VERSION)-latest; \
|
||||
$(MAKE) dist-monolite monolite_dir=$$MONOLITE; \
|
||||
tar zcvpf $$MONOLITE.tar.gz --directory=lib $$MONOLITE/
|
||||
|
||||
dist-default: dist-monolite
|
||||
|
||||
dist-local: dist-default
|
||||
|
||||
@@ -64,7 +64,7 @@ namespace Mono.CodeContracts.Rewrite {
|
||||
|
||||
var readerParameters = new ReaderParameters ();
|
||||
|
||||
if (options.Debug)
|
||||
if (options.Debug && options.WritePdbFile)
|
||||
readerParameters.ReadSymbols = true;
|
||||
|
||||
var assembly = this.options.Assembly.IsFilename ?
|
||||
|
||||
@@ -221,7 +221,7 @@ namespace Mono.Data.Sqlite
|
||||
case SQLiteDateFormats.UnixEpoch:
|
||||
return ((long)(dateValue.Subtract(UnixEpoch).Ticks / TimeSpan.TicksPerSecond)).ToString();
|
||||
default:
|
||||
return dateValue.ToString(_datetimeFormats[5], CultureInfo.InvariantCulture);
|
||||
return dateValue.ToString(_datetimeFormats[19], CultureInfo.InvariantCulture);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
../../test-helpers/NunitHelpers.cs
|
||||
Mono.Unix/ReadlinkTest.cs
|
||||
Mono.Unix/StdioFileStreamTest.cs
|
||||
Mono.Unix/UnixEncodingTest.cs
|
||||
|
||||
@@ -173,7 +173,7 @@ namespace MonoTests.Mono.Unix
|
||||
long r = Syscall.readlink (link, buf);
|
||||
if (r < 0)
|
||||
UnixMarshal.ThrowExceptionForLastError ();
|
||||
AssertHelper.GreaterOrEqual (buf.Length, r);
|
||||
Assert.That(buf.Length, Is.GreaterThanOrEqualTo(r));
|
||||
if (r == buf.Length)
|
||||
buf = new byte[checked (buf.Length * 2)];
|
||||
else
|
||||
@@ -199,7 +199,7 @@ namespace MonoTests.Mono.Unix
|
||||
long r = Syscall.readlinkat (TempFD, "link", buf);
|
||||
if (r < 0)
|
||||
UnixMarshal.ThrowExceptionForLastError ();
|
||||
AssertHelper.GreaterOrEqual (buf.Length, r);
|
||||
Assert.That(buf.Length, Is.GreaterThanOrEqualTo(r));
|
||||
if (r == buf.Length)
|
||||
buf = new byte[checked (buf.Length * 2)];
|
||||
else
|
||||
@@ -226,7 +226,7 @@ namespace MonoTests.Mono.Unix
|
||||
if (r < 0)
|
||||
UnixMarshal.ThrowExceptionForLastError ();
|
||||
Assert.AreEqual (r, sb.Length);
|
||||
AssertHelper.GreaterOrEqual (sb.Capacity, r);
|
||||
Assert.That(sb.Capacity, Is.GreaterThanOrEqualTo(r));
|
||||
if (r == sb.Capacity)
|
||||
checked { sb.Capacity *= 2; }
|
||||
else
|
||||
@@ -255,7 +255,7 @@ namespace MonoTests.Mono.Unix
|
||||
if (r < 0)
|
||||
UnixMarshal.ThrowExceptionForLastError ();
|
||||
Assert.AreEqual (r, sb.Length);
|
||||
AssertHelper.GreaterOrEqual (sb.Capacity, r);
|
||||
Assert.That(sb.Capacity, Is.GreaterThanOrEqualTo(r));
|
||||
if (r == sb.Capacity)
|
||||
checked { sb.Capacity *= 2; }
|
||||
else
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
namespace Mono.Security.Interface
|
||||
{
|
||||
delegate MonoTlsProvider MonoTlsProviderFactoryDelegate ();
|
||||
|
||||
static partial class MonoTlsProviderFactory
|
||||
{
|
||||
internal static MonoTlsProviderFactoryDelegate _PrivateFactoryDelegate;
|
||||
}
|
||||
}
|
||||
@@ -163,7 +163,7 @@ namespace Mono.Security.X509 {
|
||||
cspParams.KeyContainerName = CryptoConvert.ToHex (certificate.Hash);
|
||||
|
||||
// Right now this seems to be the best way to know if we should use LM store.. ;)
|
||||
if (_storePath.StartsWith (X509StoreManager.LocalMachinePath))
|
||||
if (_storePath.StartsWith (X509StoreManager.LocalMachinePath) || _storePath.StartsWith(X509StoreManager.NewLocalMachinePath))
|
||||
cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
|
||||
|
||||
ImportPrivateKey (certificate, cspParams);
|
||||
@@ -338,7 +338,7 @@ namespace Mono.Security.X509 {
|
||||
// If privateKey it's available, load it too..
|
||||
CspParameters cspParams = new CspParameters ();
|
||||
cspParams.KeyContainerName = CryptoConvert.ToHex (cert.Hash);
|
||||
if (_storePath.StartsWith (X509StoreManager.LocalMachinePath))
|
||||
if (_storePath.StartsWith (X509StoreManager.LocalMachinePath) || _storePath.StartsWith(X509StoreManager.NewLocalMachinePath))
|
||||
cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
|
||||
KeyPairPersistence kpp = new KeyPairPersistence (cspParams);
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
#include Mono.Security.dll.sources
|
||||
../corlib/CommonCrypto/CommonCrypto.cs
|
||||
../corlib/CommonCrypto/RC4CommonCrypto.cs
|
||||
Mono.Security.Interface/MonoTlsProviderFactory.Apple.cs
|
||||
@@ -1,5 +1,5 @@
|
||||
Novell.Directory.Ldap/AssemblyInfo.cs
|
||||
../../build/common/Consts.cs.in
|
||||
../../build/common/Consts.cs
|
||||
Novell.Directory.Ldap/SupportClass.cs
|
||||
Novell.Directory.Ldap.Utilclass/Base64.cs
|
||||
Novell.Directory.Ldap.Utilclass/DN.cs
|
||||
|
||||
@@ -31,6 +31,7 @@ using System.Runtime.InteropServices;
|
||||
using System.Security.AccessControl;
|
||||
using System.Security.Permissions;
|
||||
using System.Security.Principal;
|
||||
using System.IO.MemoryMappedFiles;
|
||||
|
||||
namespace Microsoft.Win32.SafeHandles
|
||||
{
|
||||
@@ -42,10 +43,11 @@ namespace Microsoft.Win32.SafeHandles
|
||||
handle = preexistingHandle;
|
||||
}
|
||||
|
||||
[MonoTODO]
|
||||
protected override bool ReleaseHandle ()
|
||||
{
|
||||
throw new NotImplementedException ();
|
||||
MemoryMapImpl.CloseMapping (handle);
|
||||
handle = IntPtr.Zero;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,7 +33,6 @@ using Microsoft.Win32.SafeHandles;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
|
||||
namespace System.IO.MemoryMappedFiles
|
||||
{
|
||||
internal static class MemoryMapImpl {
|
||||
@@ -113,7 +112,6 @@ namespace System.IO.MemoryMappedFiles
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class MemoryMappedFile : IDisposable {
|
||||
// MemoryMappedFileAccess fileAccess;
|
||||
// string name;
|
||||
@@ -127,7 +125,7 @@ namespace System.IO.MemoryMappedFiles
|
||||
//
|
||||
FileStream stream;
|
||||
bool keepOpen;
|
||||
IntPtr handle;
|
||||
SafeMemoryMappedFileHandle handle;
|
||||
|
||||
public static MemoryMappedFile CreateFromFile (string path)
|
||||
{
|
||||
@@ -147,7 +145,7 @@ namespace System.IO.MemoryMappedFiles
|
||||
IntPtr handle = MemoryMapImpl.OpenFile (path, mode, null, out capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None);
|
||||
|
||||
return new MemoryMappedFile () {
|
||||
handle = handle,
|
||||
handle = new SafeMemoryMappedFileHandle (handle, true),
|
||||
// fileAccess = MemoryMappedFileAccess.ReadWrite,
|
||||
// fileCapacity = capacity
|
||||
};
|
||||
@@ -179,7 +177,7 @@ namespace System.IO.MemoryMappedFiles
|
||||
IntPtr handle = MemoryMapImpl.OpenFile (path, mode, mapName, out capacity, access, MemoryMappedFileOptions.None);
|
||||
|
||||
return new MemoryMappedFile () {
|
||||
handle = handle,
|
||||
handle = new SafeMemoryMappedFileHandle (handle, true),
|
||||
// fileAccess = access,
|
||||
// name = mapName,
|
||||
// fileCapacity = capacity
|
||||
@@ -202,7 +200,7 @@ namespace System.IO.MemoryMappedFiles
|
||||
MemoryMapImpl.ConfigureHandleInheritability (handle, inheritability);
|
||||
|
||||
return new MemoryMappedFile () {
|
||||
handle = handle,
|
||||
handle = new SafeMemoryMappedFileHandle (handle, true),
|
||||
// fileAccess = access,
|
||||
// name = mapName,
|
||||
// fileCapacity = capacity,
|
||||
@@ -229,7 +227,7 @@ namespace System.IO.MemoryMappedFiles
|
||||
MemoryMapImpl.ConfigureHandleInheritability (handle, inheritability);
|
||||
|
||||
return new MemoryMappedFile () {
|
||||
handle = handle,
|
||||
handle = new SafeMemoryMappedFileHandle (handle, true),
|
||||
// fileAccess = access,
|
||||
// name = mapName,
|
||||
// fileCapacity = capacity,
|
||||
@@ -252,7 +250,7 @@ namespace System.IO.MemoryMappedFiles
|
||||
IntPtr handle = MemoryMapImpl.OpenFile (null, mode, mapName, out capacity, access, options);
|
||||
|
||||
return new MemoryMappedFile () {
|
||||
handle = handle,
|
||||
handle = new SafeMemoryMappedFileHandle (handle, true),
|
||||
// fileAccess = access,
|
||||
// name = mapName,
|
||||
// fileCapacity = capacity
|
||||
@@ -339,7 +337,7 @@ namespace System.IO.MemoryMappedFiles
|
||||
|
||||
public MemoryMappedViewStream CreateViewStream (long offset, long size, MemoryMappedFileAccess access)
|
||||
{
|
||||
var view = MemoryMappedView.Create (handle, offset, size, access);
|
||||
var view = MemoryMappedView.Create (handle.DangerousGetHandle (), offset, size, access);
|
||||
return new MemoryMappedViewStream (view);
|
||||
}
|
||||
|
||||
@@ -355,7 +353,7 @@ namespace System.IO.MemoryMappedFiles
|
||||
|
||||
public MemoryMappedViewAccessor CreateViewAccessor (long offset, long size, MemoryMappedFileAccess access)
|
||||
{
|
||||
var view = MemoryMappedView.Create (handle, offset, size, access);
|
||||
var view = MemoryMappedView.Create (handle.DangerousGetHandle (), offset, size, access);
|
||||
return new MemoryMappedViewAccessor (view);
|
||||
}
|
||||
|
||||
@@ -370,16 +368,16 @@ namespace System.IO.MemoryMappedFiles
|
||||
|
||||
protected virtual void Dispose (bool disposing)
|
||||
{
|
||||
if (disposing){
|
||||
if (stream != null){
|
||||
if (disposing) {
|
||||
if (stream != null) {
|
||||
if (keepOpen == false)
|
||||
stream.Close ();
|
||||
stream = null;
|
||||
}
|
||||
if (handle != IntPtr.Zero) {
|
||||
MemoryMapImpl.CloseMapping (handle);
|
||||
handle = IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
if (handle != null) {
|
||||
handle.Dispose ();
|
||||
handle = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -511,6 +511,11 @@ namespace MonoTests.System.Linq.Expressions {
|
||||
[Test]
|
||||
public void CallNullableGetValueOrDefault () // #568989
|
||||
{
|
||||
#if MOBILE
|
||||
// ensure that int?.GetValueOrDefault won't be removed by the linker
|
||||
Assert.AreEqual (0, ((int?)0).GetValueOrDefault (3));
|
||||
#endif
|
||||
|
||||
var value = Expression.Parameter (typeof (int?), "value");
|
||||
var default_parameter = Expression.Parameter (typeof (int), "default");
|
||||
|
||||
|
||||
@@ -36,46 +36,50 @@ using NUnit.Framework;
|
||||
namespace MonoTests.System.Linq.Expressions {
|
||||
|
||||
[TestFixture]
|
||||
public class ExpressionTest_Loop {
|
||||
public class ExpressionTest_Loop
|
||||
{
|
||||
public static void Print (int arg)
|
||||
{
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ComplexTest ()
|
||||
{
|
||||
var breakLabel = Expression.Label ("LoopBreak");
|
||||
var counter = Expression.Variable (typeof (int), "counter");
|
||||
var breakLabel = Expression.Label ("LoopBreak");
|
||||
var counter = Expression.Variable (typeof (int), "counter");
|
||||
|
||||
var l = Expression.Block (new[] { counter },
|
||||
Expression.Assign (counter, Expression.Constant (-1)),
|
||||
Expression.Loop (
|
||||
Expression.Block (Expression.IfThenElse (
|
||||
Expression.Equal (Expression.Assign (counter, Expression.Add (counter, Expression.Constant (1))), Expression.Constant (1000)),
|
||||
Expression.Block (Expression.Break (breakLabel)),
|
||||
Expression.Call (null, typeof (Console).GetMethod ("WriteLine", new Type[] { typeof (int) }), counter)
|
||||
)),
|
||||
breakLabel)
|
||||
);
|
||||
var l = Expression.Block (new[] { counter },
|
||||
Expression.Assign (counter, Expression.Constant (-1)),
|
||||
Expression.Loop (
|
||||
Expression.Block (Expression.IfThenElse (
|
||||
Expression.Equal (Expression.Assign (counter, Expression.Add (counter, Expression.Constant (1))), Expression.Constant (1000)),
|
||||
Expression.Block (Expression.Break (breakLabel)),
|
||||
Expression.Call (null, typeof (ExpressionTest_Loop).GetMethod ("Print", new Type[] { typeof (int) }), counter)
|
||||
)),
|
||||
breakLabel)
|
||||
);
|
||||
|
||||
var res = Expression.Lambda<Action> (l).Compile ();
|
||||
}
|
||||
var res = Expression.Lambda<Action> (l).Compile ();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ComplexTest_2 ()
|
||||
{
|
||||
var breakLabel = Expression.Label ("LoopBreak");
|
||||
var counter = Expression.Variable (typeof (int), "counter");
|
||||
var breakLabel = Expression.Label ("LoopBreak");
|
||||
var counter = Expression.Variable (typeof (int), "counter");
|
||||
|
||||
var l = Expression.Block (new[] { counter },
|
||||
Expression.Assign (counter, Expression.Constant(-1)),
|
||||
Expression.Loop (
|
||||
Expression.IfThenElse (
|
||||
Expression.Equal (Expression.Assign (counter, Expression.Add (counter, Expression.Constant (1))), Expression.Constant (1000)),
|
||||
Expression.Break (breakLabel),
|
||||
Expression.Call (null, typeof (Console).GetMethod ("WriteLine", new Type[] { typeof (int) }), counter)
|
||||
),
|
||||
breakLabel)
|
||||
);
|
||||
var l = Expression.Block (new[] { counter },
|
||||
Expression.Assign (counter, Expression.Constant(-1)),
|
||||
Expression.Loop (
|
||||
Expression.IfThenElse (
|
||||
Expression.Equal (Expression.Assign (counter, Expression.Add (counter, Expression.Constant (1))), Expression.Constant (1000)),
|
||||
Expression.Break (breakLabel),
|
||||
Expression.Call (null, typeof (ExpressionTest_Loop).GetMethod ("Print", new Type[] { typeof (int) }), counter)
|
||||
),
|
||||
breakLabel)
|
||||
);
|
||||
|
||||
var res = Expression.Lambda<Action> (l).Compile ();
|
||||
var res = Expression.Lambda<Action> (l).Compile ();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -289,4 +289,4 @@
|
||||
../referencesource/System.Data/System/Data/SqlClient/SqlUtil.cs
|
||||
../referencesource/System.Data/System/Data/SqlClient/TdsEnums.cs
|
||||
../referencesource/System.Data/System/Data/SqlClient/TdsParserStaticMethods.cs
|
||||
../referencesource/System.Data/System/Data/DataSet.cs
|
||||
../referencesource/System.Data/System/Data/DataSet.cs
|
||||
@@ -1,5 +1,5 @@
|
||||
Assembly/AssemblyInfo.cs
|
||||
../../build/common/Consts.cs.in
|
||||
../../build/common/Consts.cs
|
||||
../../build/common/Locale.cs
|
||||
../../build/common/SR.cs
|
||||
../../build/common/MonoTODOAttribute.cs
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
Assembly/AssemblyInfo.cs
|
||||
../../build/common/Consts.cs.in
|
||||
../../build/common/Consts.cs
|
||||
../../build/common/Locale.cs
|
||||
System.DirectoryServices/ActiveDirectoryAccessRule.cs
|
||||
System.DirectoryServices/ActiveDirectoryAuditRule.cs
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
Assembly/AssemblyInfo.cs
|
||||
../../build/common/Consts.cs
|
||||
#include netstandard.sources
|
||||
#include netstandard.sources
|
||||
+1
-1
@@ -11,4 +11,4 @@ corefx/SR.cs
|
||||
../../../external/corefx/src/System.Buffers/src/System/Buffers/ArrayPoolEventSource.cs
|
||||
../../../external/corefx/src/System.Buffers/src/System/Buffers/DefaultArrayPool.cs
|
||||
../../../external/corefx/src/System.Buffers/src/System/Buffers/DefaultArrayPoolBucket.cs
|
||||
../../../external/corefx/src/System.Buffers/src/System/Buffers/Utilities.cs
|
||||
../../../external/corefx/src/System.Buffers/src/System/Buffers/Utilities.cs
|
||||
@@ -37,6 +37,8 @@ namespace System.Net.Http
|
||||
readonly Stream content;
|
||||
readonly int bufferSize;
|
||||
readonly CancellationToken cancellationToken;
|
||||
readonly long startPosition;
|
||||
bool contentCopied;
|
||||
|
||||
public StreamContent (Stream content)
|
||||
: this (content, 16 * 1024)
|
||||
@@ -53,6 +55,10 @@ namespace System.Net.Http
|
||||
|
||||
this.content = content;
|
||||
this.bufferSize = bufferSize;
|
||||
|
||||
if (content.CanSeek) {
|
||||
startPosition = content.Position;
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
@@ -83,6 +89,16 @@ namespace System.Net.Http
|
||||
|
||||
protected internal override Task SerializeToStreamAsync (Stream stream, TransportContext context)
|
||||
{
|
||||
if (contentCopied) {
|
||||
if (!content.CanSeek) {
|
||||
throw new InvalidOperationException ("The stream was already consumed. It cannot be read again.");
|
||||
}
|
||||
|
||||
content.Seek (startPosition, SeekOrigin.Begin);
|
||||
} else {
|
||||
contentCopied = true;
|
||||
}
|
||||
|
||||
return content.CopyToAsync (stream, bufferSize, cancellationToken);
|
||||
}
|
||||
|
||||
@@ -92,7 +108,7 @@ namespace System.Net.Http
|
||||
length = 0;
|
||||
return false;
|
||||
}
|
||||
length = content.Length;
|
||||
length = content.Length - startPosition;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,8 +149,8 @@ namespace MonoTests.System.Net.Http
|
||||
/*
|
||||
sc = new StreamContent (new ExceptionStream ());
|
||||
try {
|
||||
sc.CopyToAsync (m).Wait ();
|
||||
Assert.Fail ("#2");
|
||||
sc.CopyToAsync (m).Wait ();
|
||||
Assert.Fail ("#2");
|
||||
} catch (AggregateException) {
|
||||
}
|
||||
*/
|
||||
@@ -190,6 +190,32 @@ namespace MonoTests.System.Net.Http
|
||||
Assert.IsTrue (hit, "#10");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CopyToAsync_Twice ()
|
||||
{
|
||||
var ms = new MemoryStream();
|
||||
ms.WriteByte(4);
|
||||
ms.WriteByte(12);
|
||||
ms.WriteByte(7);
|
||||
ms.Seek(1, SeekOrigin.Begin);
|
||||
|
||||
var sc = new StreamContent(ms);
|
||||
|
||||
var dest = new MemoryStream();
|
||||
var task = sc.CopyToAsync(dest);
|
||||
Assert.True(task.Wait(3000), "#0");
|
||||
Assert.AreEqual(2, dest.Length, "#1");
|
||||
dest.Seek(0, SeekOrigin.Begin);
|
||||
Assert.AreEqual(12, dest.ReadByte(), "#2");
|
||||
|
||||
dest = new MemoryStream();
|
||||
task = sc.CopyToAsync(dest);
|
||||
Assert.True(task.Wait(3000), "#10");
|
||||
Assert.AreEqual(2, dest.Length, "#11");
|
||||
dest.Seek(0, SeekOrigin.Begin);
|
||||
Assert.AreEqual(12, dest.ReadByte(), "#12");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CopyToAsync_ClosedInput ()
|
||||
{
|
||||
|
||||
+1
@@ -0,0 +1 @@
|
||||
#include mobile_System.ServiceModel.Internals.dll.sources
|
||||
+1
@@ -0,0 +1 @@
|
||||
#include mobile_System.ServiceModel.Internals.dll.sources
|
||||
@@ -31,9 +31,12 @@
|
||||
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Security.Permissions;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web.Configuration;
|
||||
using System.Web.Caching;
|
||||
using System.Web.Util;
|
||||
@@ -53,6 +56,8 @@ namespace System.Web.Hosting {
|
||||
static VirtualPathProvider vpath_provider = (HttpRuntime.AppDomainAppVirtualPath == null) ? null :
|
||||
new DefaultVirtualPathProvider ();
|
||||
static int busy_count;
|
||||
static BackgroundWorkScheduler _backgroundWorkScheduler = null; // created on demand
|
||||
static readonly Task<object> _completedTask = Task.FromResult<object>(null);
|
||||
|
||||
internal static bool HaveCustomVPP {
|
||||
get;
|
||||
@@ -212,6 +217,73 @@ namespace System.Web.Hosting {
|
||||
if (Host != null)
|
||||
Host.UnregisterObject (obj);
|
||||
}
|
||||
|
||||
// Schedules a task which can run in the background, independent of any request.
|
||||
// This differs from a normal ThreadPool work item in that ASP.NET can keep track
|
||||
// of how many work items registered through this API are currently running, and
|
||||
// the ASP.NET runtime will try not to delay AppDomain shutdown until these work
|
||||
// items have finished executing.
|
||||
//
|
||||
// Usage notes:
|
||||
// - This API cannot be called outside of an ASP.NET-managed AppDomain.
|
||||
// - The caller's ExecutionContext is not flowed to the work item.
|
||||
// - Scheduled work items are not guaranteed to ever execute, e.g., when AppDomain
|
||||
// shutdown has already started by the time this API was called.
|
||||
// - The provided CancellationToken will be signaled when the application is
|
||||
// shutting down. The work item should make every effort to honor this token.
|
||||
// If a work item does not honor this token and continues executing it will
|
||||
// eventually be considered rogue, and the ASP.NET runtime will rudely unload
|
||||
// the AppDomain without waiting for the work item to finish.
|
||||
//
|
||||
// This overload of QueueBackgroundWorkItem takes a void-returning callback; the
|
||||
// work item will be considered finished when the callback returns.
|
||||
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
|
||||
public static void QueueBackgroundWorkItem(Action<CancellationToken> workItem) {
|
||||
if (workItem == null) {
|
||||
throw new ArgumentNullException("workItem");
|
||||
}
|
||||
|
||||
QueueBackgroundWorkItem(ct => { workItem(ct); return _completedTask; });
|
||||
}
|
||||
|
||||
// See documentation on the other overload for a general API overview.
|
||||
//
|
||||
// This overload of QueueBackgroundWorkItem takes a Task-returning callback; the
|
||||
// work item will be considered finished when the returned Task transitions to a
|
||||
// terminal state.
|
||||
[SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)]
|
||||
public static void QueueBackgroundWorkItem(Func<CancellationToken, Task> workItem) {
|
||||
if (workItem == null) {
|
||||
throw new ArgumentNullException("workItem");
|
||||
}
|
||||
if (Host == null) {
|
||||
throw new InvalidOperationException(); // can only be called within an ASP.NET AppDomain
|
||||
}
|
||||
|
||||
QueueBackgroundWorkItemInternal(workItem);
|
||||
}
|
||||
|
||||
static void QueueBackgroundWorkItemInternal(Func<CancellationToken, Task> workItem) {
|
||||
Debug.Assert(workItem != null);
|
||||
|
||||
BackgroundWorkScheduler scheduler = Volatile.Read(ref _backgroundWorkScheduler);
|
||||
|
||||
// If the scheduler doesn't exist, lazily create it, but only allow one instance to ever be published to the backing field
|
||||
if (scheduler == null) {
|
||||
BackgroundWorkScheduler newlyCreatedScheduler = new BackgroundWorkScheduler(UnregisterObject, WriteUnhandledException);
|
||||
scheduler = Interlocked.CompareExchange(ref _backgroundWorkScheduler, newlyCreatedScheduler, null) ?? newlyCreatedScheduler;
|
||||
if (scheduler == newlyCreatedScheduler) {
|
||||
RegisterObject(scheduler); // Only call RegisterObject if we just created the "winning" one
|
||||
}
|
||||
}
|
||||
|
||||
scheduler.ScheduleWorkItem(workItem);
|
||||
}
|
||||
|
||||
static void WriteUnhandledException (AppDomain appDomain, Exception exception)
|
||||
{
|
||||
Console.Error.WriteLine ("Error in background work item: " + exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,6 +290,7 @@ System.Web.Hosting/AppManagerAppDomainFactory.cs
|
||||
System.Web.Hosting/ApplicationInfo.cs
|
||||
System.Web.Hosting/ApplicationHost.cs
|
||||
System.Web.Hosting/ApplicationManager.cs
|
||||
../referencesource/System.Web/Hosting/BackgroundWorkScheduler.cs
|
||||
System.Web.Hosting/BareApplicationHost.cs
|
||||
System.Web.Hosting/DefaultVirtualDirectory.cs
|
||||
System.Web.Hosting/DefaultVirtualFile.cs
|
||||
@@ -1199,6 +1200,7 @@ System.Web.UI/XhtmlMobileDocType.cs
|
||||
System.Web.UI/XhtmlTextWriter.cs
|
||||
System.Web.UI/XPathBinder.cs
|
||||
System.Web.Util/AltSerialization.cs
|
||||
../referencesource/System.Web/Util/CancellationTokenHelper.cs
|
||||
System.Web.Util/DataSourceHelper.cs
|
||||
System.Web.Util/DataSourceResolver.cs
|
||||
System.Web.Util/FileUtils.cs
|
||||
|
||||
@@ -68,6 +68,10 @@ namespace System.Resources {
|
||||
if (parts.Length == 1)
|
||||
throw new ArgumentException ("value");
|
||||
|
||||
string filename = parts [0];
|
||||
if (Path.DirectorySeparatorChar == '/')
|
||||
filename = filename.Replace ("\\", "/");
|
||||
|
||||
Type type = Type.GetType (parts [1]);
|
||||
if (type == typeof(string)) {
|
||||
Encoding encoding;
|
||||
@@ -77,12 +81,12 @@ namespace System.Resources {
|
||||
encoding = Encoding.Default;
|
||||
}
|
||||
|
||||
using (TextReader reader = new StreamReader(parts [0], encoding)) {
|
||||
using (TextReader reader = new StreamReader(filename, encoding)) {
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
}
|
||||
|
||||
using (FileStream file = new FileStream (parts [0], FileMode.Open, FileAccess.Read, FileShare.Read)) {
|
||||
using (FileStream file = new FileStream (filename, FileMode.Open, FileAccess.Read, FileShare.Read)) {
|
||||
buffer = new byte [file.Length];
|
||||
file.Read(buffer, 0, (int) file.Length);
|
||||
}
|
||||
@@ -90,7 +94,7 @@ namespace System.Resources {
|
||||
if (type == typeof(System.Byte[]))
|
||||
return buffer;
|
||||
|
||||
if (type == typeof (Bitmap) && Path.GetExtension (parts [0]) == ".ico") {
|
||||
if (type == typeof (Bitmap) && Path.GetExtension (filename) == ".ico") {
|
||||
MemoryStream ms = new MemoryStream (buffer);
|
||||
return new Icon (ms).ToBitmap ();
|
||||
}
|
||||
|
||||
@@ -229,6 +229,26 @@ namespace MonoTests.System.Resources
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ConvertFrom_Type_String_FilePathWithBackslashes ()
|
||||
{
|
||||
if (Path.DirectorySeparatorChar == '\\')
|
||||
// non-windows test
|
||||
return;
|
||||
|
||||
string fileContents = "foobar";
|
||||
string fileName = "foo.txt";
|
||||
string filePath = Path.Combine (_tempDirectory, fileName);
|
||||
File.WriteAllText (filePath, fileContents);
|
||||
|
||||
filePath = _tempDirectory + "\\.\\" + fileName;
|
||||
|
||||
string fileRef = filePath + ";" + typeof (string).AssemblyQualifiedName;
|
||||
string result = _converter.ConvertFrom (fileRef) as string;
|
||||
Assert.IsNotNull (result, "#A1");
|
||||
Assert.AreEqual (result, fileContents, "#A2");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ConvertFrom_Type_StreamReader ()
|
||||
{
|
||||
|
||||
@@ -31,7 +31,13 @@ LIB_MCS_FLAGS += -d:INSIDE_SYSTEM
|
||||
endif
|
||||
|
||||
ifndef MOBILE_PROFILE
|
||||
TEST_LIB_REFS = System.Drawing $(MONO_SECURITY) System.Data System.Xml System.Core System.Configuration
|
||||
LIB_MCS_FLAGS += -d:CODEDOM
|
||||
TEST_LIB_REFS = $(MONO_SECURITY) System.Data System.Xml System.Core System.Configuration
|
||||
|
||||
ifndef NO_SYSTEM_DRAWING_DEPENDENCY
|
||||
TEST_LIB_REFS += System.Drawing
|
||||
endif
|
||||
|
||||
else
|
||||
LIB_MCS_FLAGS += -nowarn:618
|
||||
TEST_LIB_REFS = $(MONO_SECURITY) System.Data System.Xml System.Core
|
||||
@@ -48,6 +54,14 @@ REFERENCE_SOURCES_FLAGS += -d:MONO_FEATURE_PROCESS_START
|
||||
TEST_MCS_FLAGS += -d:MONO_FEATURE_PROCESS_START
|
||||
endif
|
||||
|
||||
ifdef MONO_FEATURE_APPLETLS
|
||||
LIB_MCS_FLAGS += -d:MONO_FEATURE_APPLETLS
|
||||
endif
|
||||
|
||||
ifdef ONLY_APPLETLS
|
||||
LIB_MCS_FLAGS += -d:ONLY_APPLETLS
|
||||
endif
|
||||
|
||||
ifndef PROFILE_DISABLE_BTLS
|
||||
ifdef HAVE_BTLS
|
||||
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
#if SECURITY_DEP && MONO_FEATURE_APPLETLS
|
||||
//
|
||||
// AppleCertificateHelper.cs
|
||||
//
|
||||
// Author:
|
||||
// Martin Baulig <[email protected]>
|
||||
//
|
||||
// Copyright (c) 2015 Xamarin, Inc.
|
||||
//
|
||||
|
||||
#if MONO_SECURITY_ALIAS
|
||||
extern alias MonoSecurity;
|
||||
#endif
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
|
||||
#if MONO_SECURITY_ALIAS
|
||||
using MonoSecurity::Mono.Security.Interface;
|
||||
#else
|
||||
using Mono.Security.Interface;
|
||||
#endif
|
||||
|
||||
namespace Mono.AppleTls
|
||||
{
|
||||
static class AppleCertificateHelper
|
||||
{
|
||||
public static SecIdentity GetIdentity (X509Certificate certificate)
|
||||
{
|
||||
/*
|
||||
* If we got an 'X509Certificate2', then we require it to have a private key
|
||||
* and import it.
|
||||
*/
|
||||
var certificate2 = certificate as X509Certificate2;
|
||||
if (certificate2 != null)
|
||||
#if MONOTOUCH
|
||||
return SecIdentity.Import (certificate2);
|
||||
#else
|
||||
return SecImportExport.ItemImport (certificate2);
|
||||
#endif
|
||||
|
||||
/*
|
||||
* Reading Certificates from the Mac Keychain
|
||||
* ==========================================
|
||||
*
|
||||
* Reading the private key from the keychain is a new feature introduced with
|
||||
* AppleTls on XamMac and iOS. On Desktop Mono, this new feature has several
|
||||
* known issues and it also did not received any testing yet. We go back to the old
|
||||
* way of doing things, which is to explicitly provide an X509Certificate2 with a
|
||||
* private key.
|
||||
*
|
||||
* Keychain Dialog Popups
|
||||
* ======================
|
||||
*
|
||||
* When using Xamarin.Mac or Xamarin.iOS, we try to search the keychain
|
||||
* for the certificate and private key.
|
||||
*
|
||||
* On Xamarin.iOS, this is easy because each app has its own keychain.
|
||||
*
|
||||
* On Xamarin.Mac, the .app package needs to be trusted via code-sign
|
||||
* to get permission to access the user's keychain. [FIXME: I still have to
|
||||
* research how to actually do that.] Without this, you will get a popup
|
||||
* message each time, asking you whether you want to allow the app to access
|
||||
* the keychain, but you can make these go away by selecting "Trust always".
|
||||
*
|
||||
* On Desktop Mono, this is problematic because selecting "Trust always"
|
||||
* give the 'mono' binary (and thus everything you'll ever run with Mono)
|
||||
* permission to retrieve the private key from the keychain.
|
||||
*
|
||||
* This code would also trigger constant keychain popup messages,
|
||||
* which could only be suppressed by granting full trust. It also makes it
|
||||
* impossible to run Mono in headless mode.
|
||||
*
|
||||
* SecIdentityCreate
|
||||
* =================
|
||||
*
|
||||
* To avoid these problems, we are currently using an undocumented API
|
||||
* called SecIdentityRef() to avoid using the Mac keychain whenever a
|
||||
* X509Certificate2 with a private key is used.
|
||||
*
|
||||
* On iOS and XamMac, you can still provide the X509Certificate without
|
||||
* a private key - in this case, a keychain search will be performed (and you
|
||||
* may get a popup message on XamMac).
|
||||
*/
|
||||
|
||||
#if MOBILE
|
||||
using (var secCert = new SecCertificate (certificate)) {
|
||||
return SecKeyChain.FindIdentity (secCert, true);
|
||||
}
|
||||
#else
|
||||
return null;
|
||||
#endif
|
||||
}
|
||||
|
||||
public static SecIdentity GetIdentity (X509Certificate certificate, out SecCertificate[] intermediateCerts)
|
||||
{
|
||||
var identity = GetIdentity (certificate);
|
||||
|
||||
var impl2 = certificate.Impl as X509Certificate2Impl;
|
||||
if (impl2 == null || impl2.IntermediateCertificates == null) {
|
||||
intermediateCerts = new SecCertificate [0];
|
||||
return identity;
|
||||
}
|
||||
|
||||
try {
|
||||
intermediateCerts = new SecCertificate [impl2.IntermediateCertificates.Count];
|
||||
for (int i = 0; i < intermediateCerts.Length; i++)
|
||||
intermediateCerts [i] = new SecCertificate (impl2.IntermediateCertificates [i]);
|
||||
|
||||
return identity;
|
||||
} catch {
|
||||
identity.Dispose ();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool InvokeSystemCertificateValidator (
|
||||
ICertificateValidator2 validator, string targetHost, bool serverMode,
|
||||
X509CertificateCollection certificates,
|
||||
ref MonoSslPolicyErrors errors, ref int status11)
|
||||
{
|
||||
if (certificates == null) {
|
||||
errors |= MonoSslPolicyErrors.RemoteCertificateNotAvailable;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty (targetHost)) {
|
||||
var pos = targetHost.IndexOf (':');
|
||||
if (pos > 0)
|
||||
targetHost = targetHost.Substring (0, pos);
|
||||
}
|
||||
|
||||
var policy = SecPolicy.CreateSslPolicy (!serverMode, targetHost);
|
||||
var trust = new SecTrust (certificates, policy);
|
||||
|
||||
if (validator.Settings.TrustAnchors != null) {
|
||||
var status = trust.SetAnchorCertificates (validator.Settings.TrustAnchors);
|
||||
if (status != SecStatusCode.Success)
|
||||
throw new InvalidOperationException (status.ToString ());
|
||||
trust.SetAnchorCertificatesOnly (false);
|
||||
}
|
||||
|
||||
var result = trust.Evaluate ();
|
||||
if (result == SecTrustResult.Unspecified)
|
||||
return true;
|
||||
|
||||
errors |= MonoSslPolicyErrors.RemoteCertificateChainErrors;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,907 @@
|
||||
#if SECURITY_DEP && MONO_FEATURE_APPLETLS
|
||||
//
|
||||
// AppleTlsContext.cs
|
||||
//
|
||||
// Author:
|
||||
// Martin Baulig <[email protected]>
|
||||
//
|
||||
// Copyright (c) 2015 Xamarin, Inc.
|
||||
//
|
||||
|
||||
#if MONO_SECURITY_ALIAS
|
||||
extern alias MonoSecurity;
|
||||
#endif
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Globalization;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Runtime.InteropServices;
|
||||
using SSA = System.Security.Authentication;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
|
||||
#if MONO_SECURITY_ALIAS
|
||||
using MonoSecurity::Mono.Security.Interface;
|
||||
#else
|
||||
using Mono.Security.Interface;
|
||||
#endif
|
||||
|
||||
using Mono.Net;
|
||||
using Mono.Net.Security;
|
||||
using Mono.Util;
|
||||
|
||||
using ObjCRuntime;
|
||||
|
||||
namespace Mono.AppleTls
|
||||
{
|
||||
class AppleTlsContext : MobileTlsContext
|
||||
{
|
||||
public const string SecurityLibrary = "/System/Library/Frameworks/Security.framework/Security";
|
||||
|
||||
GCHandle handle;
|
||||
IntPtr context;
|
||||
IntPtr connectionId;
|
||||
SslReadFunc readFunc;
|
||||
SslWriteFunc writeFunc;
|
||||
|
||||
SecIdentity serverIdentity;
|
||||
SecIdentity clientIdentity;
|
||||
|
||||
X509Certificate remoteCertificate;
|
||||
X509Certificate localClientCertificate;
|
||||
MonoTlsConnectionInfo connectionInfo;
|
||||
bool havePeerTrust;
|
||||
bool isAuthenticated;
|
||||
bool handshakeFinished;
|
||||
int handshakeStarted;
|
||||
|
||||
bool closed;
|
||||
bool disposed;
|
||||
bool closedGraceful;
|
||||
int pendingIO;
|
||||
|
||||
Exception lastException;
|
||||
|
||||
public AppleTlsContext (
|
||||
MobileAuthenticatedStream parent, bool serverMode, string targetHost,
|
||||
SSA.SslProtocols enabledProtocols, X509Certificate serverCertificate,
|
||||
X509CertificateCollection clientCertificates, bool askForClientCert)
|
||||
: base (parent, serverMode, targetHost, enabledProtocols,
|
||||
serverCertificate, clientCertificates, askForClientCert)
|
||||
{
|
||||
handle = GCHandle.Alloc (this);
|
||||
connectionId = GCHandle.ToIntPtr (handle);
|
||||
readFunc = NativeReadCallback;
|
||||
writeFunc = NativeWriteCallback;
|
||||
|
||||
if (IsServer) {
|
||||
if (serverCertificate == null)
|
||||
throw new ArgumentNullException ("serverCertificate");
|
||||
}
|
||||
}
|
||||
|
||||
public IntPtr Handle {
|
||||
get {
|
||||
if (!HasContext)
|
||||
throw new ObjectDisposedException ("AppleTlsContext");
|
||||
return context;
|
||||
}
|
||||
}
|
||||
|
||||
public override bool HasContext {
|
||||
get { return !disposed && context != IntPtr.Zero; }
|
||||
}
|
||||
|
||||
[System.Diagnostics.Conditional ("APPLE_TLS_DEBUG")]
|
||||
protected new void Debug (string message, params object[] args)
|
||||
{
|
||||
Console.Error.WriteLine ("MobileTlsStream({0}): {1}", Parent.ID, string.Format (message, args));
|
||||
}
|
||||
|
||||
void CheckStatusAndThrow (SslStatus status, params SslStatus[] acceptable)
|
||||
{
|
||||
var last = Interlocked.Exchange (ref lastException, null);
|
||||
if (last != null)
|
||||
throw last;
|
||||
|
||||
if (status == SslStatus.Success || Array.IndexOf (acceptable, status) > -1)
|
||||
return;
|
||||
|
||||
switch (status) {
|
||||
case SslStatus.ClosedAbort:
|
||||
throw new IOException ("Connection closed.");
|
||||
|
||||
case SslStatus.BadCert:
|
||||
throw new TlsException (AlertDescription.BadCertificate);
|
||||
|
||||
case SslStatus.UnknownRootCert:
|
||||
case SslStatus.NoRootCert:
|
||||
case SslStatus.XCertChainInvalid:
|
||||
throw new TlsException (AlertDescription.CertificateUnknown, status.ToString ());
|
||||
|
||||
case SslStatus.CertExpired:
|
||||
case SslStatus.CertNotYetValid:
|
||||
throw new TlsException (AlertDescription.CertificateExpired);
|
||||
|
||||
case SslStatus.Protocol:
|
||||
throw new TlsException (AlertDescription.ProtocolVersion);
|
||||
|
||||
default:
|
||||
throw new TlsException (AlertDescription.InternalError, "Unknown Secure Transport error `{0}'.", status);
|
||||
}
|
||||
}
|
||||
|
||||
#region Handshake
|
||||
|
||||
public override bool IsAuthenticated {
|
||||
get { return isAuthenticated; }
|
||||
}
|
||||
|
||||
public override void StartHandshake ()
|
||||
{
|
||||
Debug ("StartHandshake: {0}", IsServer);
|
||||
|
||||
if (Interlocked.CompareExchange (ref handshakeStarted, 1, 1) != 0)
|
||||
throw new InvalidOperationException ();
|
||||
|
||||
InitializeConnection ();
|
||||
|
||||
SetSessionOption (SslSessionOption.BreakOnCertRequested, true);
|
||||
SetSessionOption (SslSessionOption.BreakOnClientAuth, true);
|
||||
SetSessionOption (SslSessionOption.BreakOnServerAuth, true);
|
||||
|
||||
if (IsServer) {
|
||||
SecCertificate[] intermediateCerts;
|
||||
serverIdentity = AppleCertificateHelper.GetIdentity (LocalServerCertificate, out intermediateCerts);
|
||||
if (serverIdentity == null)
|
||||
throw new SSA.AuthenticationException ("Unable to get server certificate from keychain.");
|
||||
|
||||
SetCertificate (serverIdentity, intermediateCerts);
|
||||
for (int i = 0; i < intermediateCerts.Length; i++)
|
||||
intermediateCerts [i].Dispose ();
|
||||
}
|
||||
}
|
||||
|
||||
public override void FinishHandshake ()
|
||||
{
|
||||
InitializeSession ();
|
||||
|
||||
isAuthenticated = true;
|
||||
}
|
||||
|
||||
public override void Flush ()
|
||||
{
|
||||
}
|
||||
|
||||
public override bool ProcessHandshake ()
|
||||
{
|
||||
if (handshakeFinished)
|
||||
throw new NotSupportedException ("Handshake already finished.");
|
||||
|
||||
while (true) {
|
||||
lastException = null;
|
||||
var status = SSLHandshake (Handle);
|
||||
Debug ("Handshake: {0} - {0:x}", status);
|
||||
|
||||
CheckStatusAndThrow (status, SslStatus.WouldBlock, SslStatus.PeerAuthCompleted, SslStatus.PeerClientCertRequested);
|
||||
|
||||
if (status == SslStatus.PeerAuthCompleted) {
|
||||
RequirePeerTrust ();
|
||||
} else if (status == SslStatus.PeerClientCertRequested) {
|
||||
RequirePeerTrust ();
|
||||
if (remoteCertificate == null)
|
||||
throw new TlsException (AlertDescription.InternalError, "Cannot request client certificate before receiving one from the server.");
|
||||
localClientCertificate = SelectClientCertificate (remoteCertificate, null);
|
||||
if (localClientCertificate == null)
|
||||
continue;
|
||||
clientIdentity = AppleCertificateHelper.GetIdentity (localClientCertificate);
|
||||
if (clientIdentity == null)
|
||||
throw new TlsException (AlertDescription.CertificateUnknown);
|
||||
SetCertificate (clientIdentity, new SecCertificate [0]);
|
||||
} else if (status == SslStatus.WouldBlock) {
|
||||
return false;
|
||||
} else if (status == SslStatus.Success) {
|
||||
handshakeFinished = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void RequirePeerTrust ()
|
||||
{
|
||||
if (!havePeerTrust) {
|
||||
EvaluateTrust ();
|
||||
havePeerTrust = true;
|
||||
}
|
||||
}
|
||||
|
||||
void EvaluateTrust ()
|
||||
{
|
||||
InitializeSession ();
|
||||
|
||||
/*
|
||||
* We're using .NET's SslStream semantics here.
|
||||
*
|
||||
* A server must always provide a valid certificate.
|
||||
*
|
||||
* However, in server mode, "ask for client certificate" means that
|
||||
* we ask the client to provide a certificate, then invoke the client
|
||||
* certificate validator - passing 'null' if the client didn't provide
|
||||
* any.
|
||||
*
|
||||
*/
|
||||
|
||||
var trust = GetPeerTrust (!IsServer);
|
||||
X509CertificateCollection certificates;
|
||||
|
||||
if (trust == null || trust.Count == 0) {
|
||||
remoteCertificate = null;
|
||||
if (!IsServer)
|
||||
throw new TlsException (AlertDescription.CertificateUnknown);
|
||||
certificates = null;
|
||||
} else {
|
||||
if (trust.Count > 1)
|
||||
Debug ("WARNING: Got multiple certificates in SecTrust!");
|
||||
|
||||
certificates = new X509CertificateCollection ();
|
||||
for (int i = 0; i < trust.Count; i++)
|
||||
certificates.Add (trust [(IntPtr)i].ToX509Certificate ());
|
||||
|
||||
remoteCertificate = certificates [0];
|
||||
Debug ("Got peer trust: {0}", remoteCertificate);
|
||||
}
|
||||
|
||||
bool ok;
|
||||
try {
|
||||
ok = ValidateCertificate (certificates);
|
||||
} catch (Exception ex) {
|
||||
Debug ("Certificate validation failed: {0}", ex);
|
||||
throw new TlsException (AlertDescription.CertificateUnknown, "Certificate validation threw exception.");
|
||||
}
|
||||
|
||||
if (!ok)
|
||||
throw new TlsException (AlertDescription.CertificateUnknown);
|
||||
}
|
||||
|
||||
void InitializeConnection ()
|
||||
{
|
||||
context = SSLCreateContext (IntPtr.Zero, IsServer ? SslProtocolSide.Server : SslProtocolSide.Client, SslConnectionType.Stream);
|
||||
|
||||
var result = SSLSetIOFuncs (Handle, readFunc, writeFunc);
|
||||
CheckStatusAndThrow (result);
|
||||
|
||||
result = SSLSetConnection (Handle, connectionId);
|
||||
CheckStatusAndThrow (result);
|
||||
|
||||
if ((EnabledProtocols & SSA.SslProtocols.Tls) != 0)
|
||||
MinProtocol = SslProtocol.Tls_1_0;
|
||||
else if ((EnabledProtocols & SSA.SslProtocols.Tls11) != 0)
|
||||
MinProtocol = SslProtocol.Tls_1_1;
|
||||
else
|
||||
MinProtocol = SslProtocol.Tls_1_2;
|
||||
|
||||
if ((EnabledProtocols & SSA.SslProtocols.Tls12) != 0)
|
||||
MaxProtocol = SslProtocol.Tls_1_2;
|
||||
else if ((EnabledProtocols & SSA.SslProtocols.Tls11) != 0)
|
||||
MaxProtocol = SslProtocol.Tls_1_1;
|
||||
else
|
||||
MaxProtocol = SslProtocol.Tls_1_0;
|
||||
|
||||
#if APPLE_TLS_DEBUG
|
||||
foreach (var c in GetSupportedCiphers ())
|
||||
Debug (" {0} SslCipherSuite.{1} {2:x} {3}", IsServer ? "Server" : "Client", c, (int)c, (CipherSuiteCode)c);
|
||||
#endif
|
||||
|
||||
if (Settings != null && Settings.EnabledCiphers != null) {
|
||||
SslCipherSuite [] ciphers = new SslCipherSuite [Settings.EnabledCiphers.Length];
|
||||
for (int i = 0 ; i < Settings.EnabledCiphers.Length; ++i)
|
||||
ciphers [i] = (SslCipherSuite)Settings.EnabledCiphers[i];
|
||||
SetEnabledCiphers (ciphers);
|
||||
}
|
||||
|
||||
if (AskForClientCertificate)
|
||||
SetClientSideAuthenticate (SslAuthenticate.Try);
|
||||
|
||||
IPAddress address;
|
||||
if (!IsServer && !string.IsNullOrEmpty (TargetHost) &&
|
||||
!IPAddress.TryParse (TargetHost, out address)) {
|
||||
PeerDomainName = ServerName;
|
||||
}
|
||||
}
|
||||
|
||||
void InitializeSession ()
|
||||
{
|
||||
if (connectionInfo != null)
|
||||
return;
|
||||
|
||||
var cipher = NegotiatedCipher;
|
||||
var protocol = GetNegotiatedProtocolVersion ();
|
||||
Debug ("GET CONNECTION INFO: {0:x}:{0} {1:x}:{1} {2}", cipher, protocol, (TlsProtocolCode)protocol);
|
||||
|
||||
connectionInfo = new MonoTlsConnectionInfo {
|
||||
CipherSuiteCode = (CipherSuiteCode)cipher,
|
||||
ProtocolVersion = GetProtocol (protocol),
|
||||
PeerDomainName = PeerDomainName
|
||||
};
|
||||
}
|
||||
|
||||
static TlsProtocols GetProtocol (SslProtocol protocol)
|
||||
{
|
||||
switch (protocol) {
|
||||
case SslProtocol.Tls_1_0:
|
||||
return TlsProtocols.Tls10;
|
||||
case SslProtocol.Tls_1_1:
|
||||
return TlsProtocols.Tls11;
|
||||
case SslProtocol.Tls_1_2:
|
||||
return TlsProtocols.Tls12;
|
||||
default:
|
||||
throw new NotSupportedException ();
|
||||
}
|
||||
}
|
||||
|
||||
public override MonoTlsConnectionInfo ConnectionInfo {
|
||||
get { return connectionInfo; }
|
||||
}
|
||||
|
||||
internal override bool IsRemoteCertificateAvailable {
|
||||
get { return remoteCertificate != null; }
|
||||
}
|
||||
|
||||
internal override X509Certificate LocalClientCertificate {
|
||||
get { return localClientCertificate; }
|
||||
}
|
||||
|
||||
public override X509Certificate RemoteCertificate {
|
||||
get { return remoteCertificate; }
|
||||
}
|
||||
|
||||
public override TlsProtocols NegotiatedProtocol {
|
||||
get { return connectionInfo.ProtocolVersion; }
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region General P/Invokes
|
||||
|
||||
[DllImport (SecurityLibrary )]
|
||||
extern static /* OSStatus */ SslStatus SSLGetProtocolVersionMax (/* SSLContextRef */ IntPtr context, out SslProtocol maxVersion);
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern static /* OSStatus */ SslStatus SSLSetProtocolVersionMax (/* SSLContextRef */ IntPtr context, SslProtocol maxVersion);
|
||||
|
||||
public SslProtocol MaxProtocol {
|
||||
get {
|
||||
SslProtocol value;
|
||||
var result = SSLGetProtocolVersionMax (Handle, out value);
|
||||
CheckStatusAndThrow (result);
|
||||
return value;
|
||||
}
|
||||
set {
|
||||
var result = SSLSetProtocolVersionMax (Handle, value);
|
||||
CheckStatusAndThrow (result);
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern static /* OSStatus */ SslStatus SSLGetProtocolVersionMin (/* SSLContextRef */ IntPtr context, out SslProtocol minVersion);
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern static /* OSStatus */ SslStatus SSLSetProtocolVersionMin (/* SSLContextRef */ IntPtr context, SslProtocol minVersion);
|
||||
|
||||
public SslProtocol MinProtocol {
|
||||
get {
|
||||
SslProtocol value;
|
||||
var result = SSLGetProtocolVersionMin (Handle, out value);
|
||||
CheckStatusAndThrow (result);
|
||||
return value;
|
||||
}
|
||||
set {
|
||||
var result = SSLSetProtocolVersionMin (Handle, value);
|
||||
CheckStatusAndThrow (result);
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern static /* OSStatus */ SslStatus SSLGetNegotiatedProtocolVersion (/* SSLContextRef */ IntPtr context, out SslProtocol protocol);
|
||||
|
||||
public SslProtocol GetNegotiatedProtocolVersion ()
|
||||
{
|
||||
SslProtocol value;
|
||||
var result = SSLGetNegotiatedProtocolVersion (Handle, out value);
|
||||
CheckStatusAndThrow (result);
|
||||
return value;
|
||||
}
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern static /* OSStatus */ SslStatus SSLGetSessionOption (/* SSLContextRef */ IntPtr context, SslSessionOption option, out bool value);
|
||||
|
||||
public bool GetSessionOption (SslSessionOption option)
|
||||
{
|
||||
bool value;
|
||||
var result = SSLGetSessionOption (Handle, option, out value);
|
||||
CheckStatusAndThrow (result);
|
||||
return value;
|
||||
}
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern static /* OSStatus */ SslStatus SSLSetSessionOption (/* SSLContextRef */ IntPtr context, SslSessionOption option, bool value);
|
||||
|
||||
public void SetSessionOption (SslSessionOption option, bool value)
|
||||
{
|
||||
var result = SSLSetSessionOption (Handle, option, value);
|
||||
CheckStatusAndThrow (result);
|
||||
}
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern static /* OSStatus */ SslStatus SSLSetClientSideAuthenticate (/* SSLContextRef */ IntPtr context, SslAuthenticate auth);
|
||||
|
||||
public void SetClientSideAuthenticate (SslAuthenticate auth)
|
||||
{
|
||||
var result = SSLSetClientSideAuthenticate (Handle, auth);
|
||||
CheckStatusAndThrow (result);
|
||||
}
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern static /* OSStatus */ SslStatus SSLHandshake (/* SSLContextRef */ IntPtr context);
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern static /* OSStatus */ SslStatus SSLGetSessionState (/* SSLContextRef */ IntPtr context, ref SslSessionState state);
|
||||
|
||||
public SslSessionState SessionState {
|
||||
get {
|
||||
var value = SslSessionState.Invalid;
|
||||
var result = SSLGetSessionState (Handle, ref value);
|
||||
CheckStatusAndThrow (result);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern unsafe static /* OSStatus */ SslStatus SSLGetPeerID (/* SSLContextRef */ IntPtr context, /* const void** */ out IntPtr peerID, /* size_t* */ out IntPtr peerIDLen);
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern unsafe static /* OSStatus */ SslStatus SSLSetPeerID (/* SSLContextRef */ IntPtr context, /* const void* */ byte* peerID, /* size_t */ IntPtr peerIDLen);
|
||||
|
||||
public unsafe byte[] PeerId {
|
||||
get {
|
||||
IntPtr length;
|
||||
IntPtr id;
|
||||
var result = SSLGetPeerID (Handle, out id, out length);
|
||||
CheckStatusAndThrow (result);
|
||||
if ((result != SslStatus.Success) || ((int)length == 0))
|
||||
return null;
|
||||
var data = new byte [(int)length];
|
||||
Marshal.Copy (id, data, 0, (int) length);
|
||||
return data;
|
||||
}
|
||||
set {
|
||||
SslStatus result;
|
||||
IntPtr length = (value == null) ? IntPtr.Zero : (IntPtr)value.Length;
|
||||
fixed (byte *p = value) {
|
||||
result = SSLSetPeerID (Handle, p, length);
|
||||
}
|
||||
CheckStatusAndThrow (result);
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern unsafe static /* OSStatus */ SslStatus SSLGetBufferedReadSize (/* SSLContextRef */ IntPtr context, /* size_t* */ out IntPtr bufSize);
|
||||
|
||||
public IntPtr BufferedReadSize {
|
||||
get {
|
||||
IntPtr value;
|
||||
var result = SSLGetBufferedReadSize (Handle, out value);
|
||||
CheckStatusAndThrow (result);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern unsafe static /* OSStatus */ SslStatus SSLGetNumberSupportedCiphers (/* SSLContextRef */ IntPtr context, /* size_t* */ out IntPtr numCiphers);
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern unsafe static /* OSStatus */ SslStatus SSLGetSupportedCiphers (/* SSLContextRef */ IntPtr context, SslCipherSuite *ciphers, /* size_t* */ ref IntPtr numCiphers);
|
||||
|
||||
public unsafe IList<SslCipherSuite> GetSupportedCiphers ()
|
||||
{
|
||||
IntPtr n;
|
||||
var result = SSLGetNumberSupportedCiphers (Handle, out n);
|
||||
CheckStatusAndThrow (result);
|
||||
if ((result != SslStatus.Success) || ((int)n <= 0))
|
||||
return null;
|
||||
|
||||
var ciphers = new SslCipherSuite [(int)n];
|
||||
fixed (SslCipherSuite *p = ciphers) {
|
||||
result = SSLGetSupportedCiphers (Handle, p, ref n);
|
||||
}
|
||||
CheckStatusAndThrow (result);
|
||||
return ciphers;
|
||||
}
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern unsafe static /* OSStatus */ SslStatus SSLGetNumberEnabledCiphers (/* SSLContextRef */ IntPtr context, /* size_t* */ out IntPtr numCiphers);
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern unsafe static /* OSStatus */ SslStatus SSLGetEnabledCiphers (/* SSLContextRef */ IntPtr context, SslCipherSuite *ciphers, /* size_t* */ ref IntPtr numCiphers);
|
||||
|
||||
public unsafe IList<SslCipherSuite> GetEnabledCiphers ()
|
||||
{
|
||||
IntPtr n;
|
||||
var result = SSLGetNumberEnabledCiphers (Handle, out n);
|
||||
CheckStatusAndThrow (result);
|
||||
if ((result != SslStatus.Success) || ((int)n <= 0))
|
||||
return null;
|
||||
|
||||
var ciphers = new SslCipherSuite [(int)n];
|
||||
fixed (SslCipherSuite *p = ciphers) {
|
||||
result = SSLGetEnabledCiphers (Handle, p, ref n);
|
||||
}
|
||||
CheckStatusAndThrow (result);
|
||||
return ciphers;
|
||||
}
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern unsafe static /* OSStatus */ SslStatus SSLSetEnabledCiphers (/* SSLContextRef */ IntPtr context, SslCipherSuite *ciphers, /* size_t */ IntPtr numCiphers);
|
||||
|
||||
public unsafe void SetEnabledCiphers (SslCipherSuite [] ciphers)
|
||||
{
|
||||
if (ciphers == null)
|
||||
throw new ArgumentNullException ("ciphers");
|
||||
|
||||
SslStatus result;
|
||||
|
||||
fixed (SslCipherSuite *p = ciphers)
|
||||
result = SSLSetEnabledCiphers (Handle, p, (IntPtr)ciphers.Length);
|
||||
CheckStatusAndThrow (result);
|
||||
}
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern unsafe static /* OSStatus */ SslStatus SSLGetNegotiatedCipher (/* SSLContextRef */ IntPtr context, /* SslCipherSuite* */ out SslCipherSuite cipherSuite);
|
||||
|
||||
public SslCipherSuite NegotiatedCipher {
|
||||
get {
|
||||
SslCipherSuite value;
|
||||
var result = SSLGetNegotiatedCipher (Handle, out value);
|
||||
CheckStatusAndThrow (result);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern unsafe static /* OSStatus */ SslStatus SSLGetPeerDomainNameLength (/* SSLContextRef */ IntPtr context, /* size_t* */ out IntPtr peerNameLen);
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern unsafe static /* OSStatus */ SslStatus SSLGetPeerDomainName (/* SSLContextRef */ IntPtr context, /* char* */ byte[] peerName, /* size_t */ ref IntPtr peerNameLen);
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern unsafe static /* OSStatus */ SslStatus SSLSetPeerDomainName (/* SSLContextRef */ IntPtr context, /* char* */ byte[] peerName, /* size_t */ IntPtr peerNameLen);
|
||||
|
||||
public string PeerDomainName {
|
||||
get {
|
||||
IntPtr length;
|
||||
var result = SSLGetPeerDomainNameLength (Handle, out length);
|
||||
CheckStatusAndThrow (result);
|
||||
if (result != SslStatus.Success || (int)length == 0)
|
||||
return String.Empty;
|
||||
var bytes = new byte [(int)length];
|
||||
result = SSLGetPeerDomainName (Handle, bytes, ref length);
|
||||
CheckStatusAndThrow (result);
|
||||
|
||||
int peerDomainLength = (int)length;
|
||||
|
||||
if (result != SslStatus.Success)
|
||||
return string.Empty;
|
||||
if (peerDomainLength > 0 && bytes [peerDomainLength-1] == 0)
|
||||
peerDomainLength = peerDomainLength - 1;
|
||||
return Encoding.UTF8.GetString (bytes, 0, peerDomainLength);
|
||||
}
|
||||
set {
|
||||
SslStatus result;
|
||||
if (value == null) {
|
||||
result = SSLSetPeerDomainName (Handle, null, (IntPtr)0);
|
||||
} else {
|
||||
var bytes = Encoding.UTF8.GetBytes (value);
|
||||
result = SSLSetPeerDomainName (Handle, bytes, (IntPtr)bytes.Length);
|
||||
}
|
||||
CheckStatusAndThrow (result);
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern unsafe static /* OSStatus */ SslStatus SSLSetCertificate (/* SSLContextRef */ IntPtr context, /* CFArrayRef */ IntPtr certRefs);
|
||||
|
||||
CFArray Bundle (SecIdentity identity, IEnumerable<SecCertificate> certificates)
|
||||
{
|
||||
if (identity == null)
|
||||
throw new ArgumentNullException ("identity");
|
||||
int i = 0;
|
||||
|
||||
int n = 0;
|
||||
if (certificates != null) {
|
||||
foreach (var obj in certificates)
|
||||
n++;
|
||||
}
|
||||
|
||||
var ptrs = new IntPtr [n + 1];
|
||||
ptrs [0] = identity.Handle;
|
||||
foreach (var certificate in certificates)
|
||||
ptrs [++i] = certificate.Handle;
|
||||
return CFArray.CreateArray (ptrs);
|
||||
}
|
||||
|
||||
public void SetCertificate (SecIdentity identify, IEnumerable<SecCertificate> certificates)
|
||||
{
|
||||
using (var array = Bundle (identify, certificates)) {
|
||||
var result = SSLSetCertificate (Handle, array.Handle);
|
||||
CheckStatusAndThrow (result);
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern unsafe static /* OSStatus */ SslStatus SSLGetClientCertificateState (/* SSLContextRef */ IntPtr context, out SslClientCertificateState clientState);
|
||||
|
||||
public SslClientCertificateState ClientCertificateState {
|
||||
get {
|
||||
SslClientCertificateState value;
|
||||
var result = SSLGetClientCertificateState (Handle, out value);
|
||||
CheckStatusAndThrow (result);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern unsafe static /* OSStatus */ SslStatus SSLCopyPeerTrust (/* SSLContextRef */ IntPtr context, /* SecTrustRef */ out IntPtr trust);
|
||||
|
||||
public SecTrust GetPeerTrust (bool requireTrust)
|
||||
{
|
||||
IntPtr value;
|
||||
var result = SSLCopyPeerTrust (Handle, out value);
|
||||
if (requireTrust) {
|
||||
CheckStatusAndThrow (result);
|
||||
if (value == IntPtr.Zero)
|
||||
throw new TlsException (AlertDescription.CertificateUnknown);
|
||||
}
|
||||
return (value == IntPtr.Zero) ? null : new SecTrust (value);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IO Functions
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern static /* SSLContextRef */ IntPtr SSLCreateContext (/* CFAllocatorRef */ IntPtr alloc, SslProtocolSide protocolSide, SslConnectionType connectionType);
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern static /* OSStatus */ SslStatus SSLSetConnection (/* SSLContextRef */ IntPtr context, /* SSLConnectionRef */ IntPtr connection);
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern static /* OSStatus */ SslStatus SSLSetIOFuncs (/* SSLContextRef */ IntPtr context, /* SSLReadFunc */ SslReadFunc readFunc, /* SSLWriteFunc */ SslWriteFunc writeFunc);
|
||||
|
||||
[MonoPInvokeCallback (typeof (SslReadFunc))]
|
||||
static SslStatus NativeReadCallback (IntPtr ptr, IntPtr data, ref IntPtr dataLength)
|
||||
{
|
||||
var handle = GCHandle.FromIntPtr (ptr);
|
||||
if (!handle.IsAllocated)
|
||||
return SslStatus.Internal;
|
||||
|
||||
var context = (AppleTlsContext) handle.Target;
|
||||
if (context.disposed)
|
||||
return SslStatus.ClosedAbort;
|
||||
|
||||
try {
|
||||
return context.NativeReadCallback (data, ref dataLength);
|
||||
} catch (Exception ex) {
|
||||
if (context.lastException == null)
|
||||
context.lastException = ex;
|
||||
return SslStatus.Internal;
|
||||
}
|
||||
}
|
||||
|
||||
[MonoPInvokeCallback (typeof (SslWriteFunc))]
|
||||
static SslStatus NativeWriteCallback (IntPtr ptr, IntPtr data, ref IntPtr dataLength)
|
||||
{
|
||||
var handle = GCHandle.FromIntPtr (ptr);
|
||||
if (!handle.IsAllocated)
|
||||
return SslStatus.Internal;
|
||||
|
||||
var context = (AppleTlsContext) handle.Target;
|
||||
if (context.disposed)
|
||||
return SslStatus.ClosedAbort;
|
||||
|
||||
try {
|
||||
return context.NativeWriteCallback (data, ref dataLength);
|
||||
} catch (Exception ex) {
|
||||
if (context.lastException == null)
|
||||
context.lastException = ex;
|
||||
return SslStatus.Internal;
|
||||
}
|
||||
}
|
||||
|
||||
SslStatus NativeReadCallback (IntPtr data, ref IntPtr dataLength)
|
||||
{
|
||||
if (closed || disposed || Parent == null)
|
||||
return SslStatus.ClosedAbort;
|
||||
|
||||
var len = (int)dataLength;
|
||||
var readBuffer = new byte [len];
|
||||
|
||||
Debug ("NativeReadCallback: {0} {1}", dataLength, len);
|
||||
|
||||
bool wantMore;
|
||||
var ret = Parent.InternalRead (readBuffer, 0, len, out wantMore);
|
||||
dataLength = (IntPtr)ret;
|
||||
|
||||
Debug ("NativeReadCallback #1: {0} - {1} {2}", len, ret, wantMore);
|
||||
|
||||
if (ret < 0)
|
||||
return SslStatus.ClosedAbort;
|
||||
|
||||
Marshal.Copy (readBuffer, 0, data, ret);
|
||||
|
||||
if (ret > 0)
|
||||
return SslStatus.Success;
|
||||
else if (wantMore)
|
||||
return SslStatus.WouldBlock;
|
||||
else if (ret == 0) {
|
||||
closedGraceful = true;
|
||||
return SslStatus.ClosedGraceful;
|
||||
} else {
|
||||
return SslStatus.Success;
|
||||
}
|
||||
}
|
||||
|
||||
SslStatus NativeWriteCallback (IntPtr data, ref IntPtr dataLength)
|
||||
{
|
||||
if (closed || disposed || Parent == null)
|
||||
return SslStatus.ClosedAbort;
|
||||
|
||||
var len = (int)dataLength;
|
||||
var writeBuffer = new byte [len];
|
||||
|
||||
Marshal.Copy (data, writeBuffer, 0, len);
|
||||
|
||||
Debug ("NativeWriteCallback: {0}", len);
|
||||
|
||||
var ok = Parent.InternalWrite (writeBuffer, 0, len);
|
||||
|
||||
Debug ("NativeWriteCallback done: {0} {1}", len, ok);
|
||||
|
||||
return ok ? SslStatus.Success : SslStatus.ClosedAbort;
|
||||
}
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern unsafe static /* OSStatus */ SslStatus SSLRead (/* SSLContextRef */ IntPtr context, /* const void* */ byte* data, /* size_t */ IntPtr dataLength, /* size_t* */ out IntPtr processed);
|
||||
|
||||
public override unsafe int Read (byte[] buffer, int offset, int count, out bool wantMore)
|
||||
{
|
||||
if (Interlocked.Exchange (ref pendingIO, 1) == 1)
|
||||
throw new InvalidOperationException ();
|
||||
|
||||
Debug ("Read: {0},{1}", offset, count);
|
||||
|
||||
lastException = null;
|
||||
|
||||
try {
|
||||
IntPtr processed;
|
||||
SslStatus status;
|
||||
|
||||
fixed (byte *d = &buffer [offset])
|
||||
status = SSLRead (Handle, d, (IntPtr)count, out processed);
|
||||
|
||||
Debug ("Read done: {0} {1} {2}", status, count, processed);
|
||||
|
||||
if (closedGraceful && (status == SslStatus.ClosedAbort || status == SslStatus.ClosedGraceful)) {
|
||||
/*
|
||||
* This is really ugly, but unfortunately SSLRead() also returns 'SslStatus.ClosedAbort'
|
||||
* when the first inner Read() returns 0. MobileAuthenticatedStream.InnerRead() attempts
|
||||
* to distinguish between a graceful close and abnormal termination of connection.
|
||||
*/
|
||||
wantMore = false;
|
||||
return 0;
|
||||
}
|
||||
|
||||
CheckStatusAndThrow (status, SslStatus.WouldBlock, SslStatus.ClosedGraceful);
|
||||
wantMore = status == SslStatus.WouldBlock;
|
||||
return (int)processed;
|
||||
} catch (Exception ex) {
|
||||
Debug ("Read error: {0}", ex);
|
||||
throw;
|
||||
} finally {
|
||||
pendingIO = 0;
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern unsafe static /* OSStatus */ SslStatus SSLWrite (/* SSLContextRef */ IntPtr context, /* const void* */ byte* data, /* size_t */ IntPtr dataLength, /* size_t* */ out IntPtr processed);
|
||||
|
||||
public override unsafe int Write (byte[] buffer, int offset, int count, out bool wantMore)
|
||||
{
|
||||
if (Interlocked.Exchange (ref pendingIO, 1) == 1)
|
||||
throw new InvalidOperationException ();
|
||||
|
||||
Debug ("Write: {0},{1}", offset, count);
|
||||
|
||||
lastException = null;
|
||||
|
||||
try {
|
||||
SslStatus status = SslStatus.ClosedAbort;
|
||||
IntPtr processed = (IntPtr)(-1);
|
||||
|
||||
fixed (byte *d = &buffer [offset])
|
||||
status = SSLWrite (Handle, d, (IntPtr)count, out processed);
|
||||
|
||||
Debug ("Write done: {0} {1}", status, processed);
|
||||
|
||||
CheckStatusAndThrow (status, SslStatus.WouldBlock);
|
||||
|
||||
wantMore = status == SslStatus.WouldBlock;
|
||||
return (int)processed;
|
||||
} finally {
|
||||
pendingIO = 0;
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport (SecurityLibrary)]
|
||||
extern static /* OSStatus */ SslStatus SSLClose (/* SSLContextRef */ IntPtr context);
|
||||
|
||||
public override void Close ()
|
||||
{
|
||||
if (Interlocked.Exchange (ref pendingIO, 1) == 1)
|
||||
throw new InvalidOperationException ();
|
||||
|
||||
Debug ("Close");
|
||||
|
||||
lastException = null;
|
||||
|
||||
try {
|
||||
if (closed || disposed)
|
||||
return;
|
||||
|
||||
var status = SSLClose (Handle);
|
||||
Debug ("Close done: {0}", status);
|
||||
CheckStatusAndThrow (status);
|
||||
} finally {
|
||||
closed = true;
|
||||
pendingIO = 0;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
protected override void Dispose (bool disposing)
|
||||
{
|
||||
try {
|
||||
if (disposed)
|
||||
return;
|
||||
if (disposing) {
|
||||
disposed = true;
|
||||
if (serverIdentity != null) {
|
||||
serverIdentity.Dispose ();
|
||||
serverIdentity = null;
|
||||
}
|
||||
if (clientIdentity != null) {
|
||||
clientIdentity.Dispose ();
|
||||
clientIdentity = null;
|
||||
}
|
||||
if (remoteCertificate != null) {
|
||||
remoteCertificate.Dispose ();
|
||||
remoteCertificate = null;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
disposed = true;
|
||||
if (context != IntPtr.Zero) {
|
||||
CFObject.CFRelease (context);
|
||||
context = IntPtr.Zero;
|
||||
}
|
||||
base.Dispose (disposing);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,77 @@
|
||||
#if SECURITY_DEP && MONO_FEATURE_APPLETLS
|
||||
//
|
||||
// AppleTlsProvider.cs
|
||||
//
|
||||
// Author:
|
||||
// Martin Baulig <[email protected]>
|
||||
//
|
||||
// Copyright (c) 2015 Xamarin, Inc.
|
||||
//
|
||||
|
||||
#if MONO_SECURITY_ALIAS
|
||||
extern alias MonoSecurity;
|
||||
#endif
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Security.Authentication;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
|
||||
using MNS = Mono.Net.Security;
|
||||
#if MONO_SECURITY_ALIAS
|
||||
using MonoSecurity::Mono.Security.Interface;
|
||||
#else
|
||||
using Mono.Security.Interface;
|
||||
#endif
|
||||
|
||||
namespace Mono.AppleTls
|
||||
{
|
||||
class AppleTlsProvider : MonoTlsProvider
|
||||
{
|
||||
static readonly Guid id = new Guid ("981af8af-a3a3-419a-9f01-a518e3a17c1c");
|
||||
|
||||
public override string Name {
|
||||
get { return "apple-tls"; }
|
||||
}
|
||||
|
||||
public override Guid ID {
|
||||
get { return id; }
|
||||
}
|
||||
|
||||
public override IMonoSslStream CreateSslStream (
|
||||
Stream innerStream, bool leaveInnerStreamOpen,
|
||||
MonoTlsSettings settings = null)
|
||||
{
|
||||
return new AppleTlsStream (innerStream, leaveInnerStreamOpen, settings, this);
|
||||
}
|
||||
|
||||
public override bool SupportsSslStream {
|
||||
get { return true; }
|
||||
}
|
||||
|
||||
public override bool SupportsMonoExtensions {
|
||||
get { return true; }
|
||||
}
|
||||
|
||||
public override bool SupportsConnectionInfo {
|
||||
get { return true; }
|
||||
}
|
||||
|
||||
public override SslProtocols SupportedProtocols {
|
||||
get { return SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls; }
|
||||
}
|
||||
|
||||
internal override bool ValidateCertificate (
|
||||
ICertificateValidator2 validator, string targetHost, bool serverMode,
|
||||
X509CertificateCollection certificates, bool wantsChain, ref X509Chain chain,
|
||||
ref MonoSslPolicyErrors errors, ref int status11)
|
||||
{
|
||||
if (wantsChain)
|
||||
chain = MNS.SystemCertificateValidator.CreateX509Chain (certificates);
|
||||
return AppleCertificateHelper.InvokeSystemCertificateValidator (validator, targetHost, serverMode, certificates, ref errors, ref status11);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,50 @@
|
||||
#if SECURITY_DEP && MONO_FEATURE_APPLETLS
|
||||
//
|
||||
// AppleTlsStream.cs
|
||||
//
|
||||
// Author:
|
||||
// Martin Baulig <[email protected]>
|
||||
//
|
||||
// Copyright (c) 2016 Xamarin, Inc.
|
||||
//
|
||||
|
||||
#if MONO_SECURITY_ALIAS
|
||||
extern alias MonoSecurity;
|
||||
#endif
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Security.Authentication;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
|
||||
using MNS = Mono.Net.Security;
|
||||
#if MONO_SECURITY_ALIAS
|
||||
using MonoSecurity::Mono.Security.Interface;
|
||||
#else
|
||||
using Mono.Security.Interface;
|
||||
#endif
|
||||
|
||||
namespace Mono.AppleTls
|
||||
{
|
||||
class AppleTlsStream : MNS.MobileAuthenticatedStream
|
||||
{
|
||||
public AppleTlsStream (Stream innerStream, bool leaveInnerStreamOpen, MonoTlsSettings settings, MonoTlsProvider provider)
|
||||
: base (innerStream, leaveInnerStreamOpen, settings, provider)
|
||||
{
|
||||
}
|
||||
|
||||
protected override MNS.MobileTlsContext CreateContext (
|
||||
MNS.MobileAuthenticatedStream parent, bool serverMode, string targetHost,
|
||||
SslProtocols enabledProtocols, X509Certificate serverCertificate,
|
||||
X509CertificateCollection clientCertificates, bool askForClientCert)
|
||||
{
|
||||
return new AppleTlsContext (
|
||||
parent, serverMode, targetHost,
|
||||
enabledProtocols, serverCertificate,
|
||||
clientCertificates, askForClientCert);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,450 @@
|
||||
//
|
||||
// Certificate.cs: Implements the managed SecCertificate wrapper.
|
||||
//
|
||||
// Authors:
|
||||
// Miguel de Icaza
|
||||
// Sebastien Pouliot <[email protected]>
|
||||
//
|
||||
// Copyright 2010 Novell, Inc
|
||||
// Copyright 2012-2013 Xamarin Inc.
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
|
||||
#if SECURITY_DEP && MONO_FEATURE_APPLETLS
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Mono.Net;
|
||||
|
||||
using ObjCRuntime;
|
||||
|
||||
namespace Mono.AppleTls {
|
||||
|
||||
partial class SecCertificate : INativeObject, IDisposable {
|
||||
internal IntPtr handle;
|
||||
|
||||
internal SecCertificate (IntPtr handle, bool owns = false)
|
||||
{
|
||||
if (handle == IntPtr.Zero)
|
||||
throw new Exception ("Invalid handle");
|
||||
|
||||
this.handle = handle;
|
||||
if (!owns)
|
||||
CFObject.CFRetain (handle);
|
||||
}
|
||||
|
||||
[DllImport (AppleTlsContext.SecurityLibrary, EntryPoint="SecCertificateGetTypeID")]
|
||||
public extern static IntPtr GetTypeID ();
|
||||
|
||||
[DllImport (AppleTlsContext.SecurityLibrary)]
|
||||
extern static IntPtr SecCertificateCreateWithData (IntPtr allocator, IntPtr cfData);
|
||||
|
||||
public SecCertificate (X509Certificate certificate)
|
||||
{
|
||||
if (certificate == null)
|
||||
throw new ArgumentNullException ("certificate");
|
||||
|
||||
handle = certificate.Impl.GetNativeAppleCertificate ();
|
||||
if (handle != IntPtr.Zero) {
|
||||
CFObject.CFRetain (handle);
|
||||
return;
|
||||
}
|
||||
|
||||
using (CFData cert = CFData.FromData (certificate.GetRawCertData ())) {
|
||||
Initialize (cert);
|
||||
}
|
||||
}
|
||||
|
||||
internal SecCertificate (X509CertificateImpl impl)
|
||||
{
|
||||
handle = impl.GetNativeAppleCertificate ();
|
||||
if (handle != IntPtr.Zero) {
|
||||
CFObject.CFRetain (handle);
|
||||
return;
|
||||
}
|
||||
|
||||
using (CFData cert = CFData.FromData (impl.GetRawCertData ())) {
|
||||
Initialize (cert);
|
||||
}
|
||||
}
|
||||
|
||||
void Initialize (CFData data)
|
||||
{
|
||||
handle = SecCertificateCreateWithData (IntPtr.Zero, data.Handle);
|
||||
if (handle == IntPtr.Zero)
|
||||
throw new ArgumentException ("Not a valid DER-encoded X.509 certificate");
|
||||
}
|
||||
|
||||
[DllImport (AppleTlsContext.SecurityLibrary)]
|
||||
extern static IntPtr SecCertificateCopySubjectSummary (IntPtr cert);
|
||||
|
||||
public string SubjectSummary {
|
||||
get {
|
||||
if (handle == IntPtr.Zero)
|
||||
throw new ObjectDisposedException ("SecCertificate");
|
||||
|
||||
IntPtr subjectSummaryHandle = IntPtr.Zero;
|
||||
try {
|
||||
subjectSummaryHandle = SecCertificateCopySubjectSummary (handle);
|
||||
CFString subjectSummary = CFString.AsString (subjectSummaryHandle);
|
||||
return subjectSummary;
|
||||
}
|
||||
finally {
|
||||
if (subjectSummaryHandle != IntPtr.Zero)
|
||||
CFObject.CFRelease (subjectSummaryHandle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport (AppleTlsContext.SecurityLibrary)]
|
||||
extern static /* CFDataRef */ IntPtr SecCertificateCopyData (/* SecCertificateRef */ IntPtr cert);
|
||||
|
||||
public CFData DerData {
|
||||
get {
|
||||
if (handle == IntPtr.Zero)
|
||||
throw new ObjectDisposedException ("SecCertificate");
|
||||
|
||||
IntPtr data = SecCertificateCopyData (handle);
|
||||
if (data == IntPtr.Zero)
|
||||
throw new ArgumentException ("Not a valid certificate");
|
||||
return new CFData (data, true);
|
||||
}
|
||||
}
|
||||
|
||||
public X509Certificate ToX509Certificate ()
|
||||
{
|
||||
if (handle == IntPtr.Zero)
|
||||
throw new ObjectDisposedException ("SecCertificate");
|
||||
|
||||
return new X509Certificate (handle);
|
||||
}
|
||||
|
||||
internal static bool Equals (SecCertificate first, SecCertificate second)
|
||||
{
|
||||
/*
|
||||
* This is a little bit expensive, but unfortunately there is no better API to compare two
|
||||
* SecCertificateRef's for equality.
|
||||
*/
|
||||
if (first == null)
|
||||
throw new ArgumentNullException ("first");
|
||||
if (second == null)
|
||||
throw new ArgumentNullException ("second");
|
||||
if (first.Handle == second.Handle)
|
||||
return true;
|
||||
|
||||
using (var firstData = first.DerData)
|
||||
using (var secondData = second.DerData) {
|
||||
if (firstData.Handle == secondData.Handle)
|
||||
return true;
|
||||
|
||||
if (firstData.Length != secondData.Length)
|
||||
return false;
|
||||
IntPtr length = (IntPtr)firstData.Length;
|
||||
for (long i = 0; i < (long)length; i++) {
|
||||
if (firstData [i] != secondData [i])
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
~SecCertificate ()
|
||||
{
|
||||
Dispose (false);
|
||||
}
|
||||
|
||||
public IntPtr Handle {
|
||||
get {
|
||||
return handle;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose ()
|
||||
{
|
||||
Dispose (true);
|
||||
GC.SuppressFinalize (this);
|
||||
}
|
||||
|
||||
protected virtual void Dispose (bool disposing)
|
||||
{
|
||||
if (handle != IntPtr.Zero){
|
||||
CFObject.CFRelease (handle);
|
||||
handle = IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
partial class SecIdentity : INativeObject, IDisposable {
|
||||
|
||||
static readonly CFString ImportExportPassphase;
|
||||
static readonly CFString ImportItemIdentity;
|
||||
static readonly CFString ImportExportAccess;
|
||||
static readonly CFString ImportExportKeychain;
|
||||
|
||||
static SecIdentity ()
|
||||
{
|
||||
var handle = CFObject.dlopen (AppleTlsContext.SecurityLibrary, 0);
|
||||
if (handle == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
try {
|
||||
ImportExportPassphase = CFObject.GetStringConstant (handle, "kSecImportExportPassphrase");
|
||||
ImportItemIdentity = CFObject.GetStringConstant (handle, "kSecImportItemIdentity");
|
||||
ImportExportAccess = CFObject.GetStringConstant (handle, "kSecImportExportAccess");
|
||||
ImportExportKeychain = CFObject.GetStringConstant (handle, "kSecImportExportKeychain");
|
||||
} finally {
|
||||
CFObject.dlclose (handle);
|
||||
}
|
||||
}
|
||||
|
||||
internal IntPtr handle;
|
||||
|
||||
internal SecIdentity (IntPtr handle, bool owns = false)
|
||||
{
|
||||
this.handle = handle;
|
||||
if (!owns)
|
||||
CFObject.CFRetain (handle);
|
||||
}
|
||||
|
||||
[DllImport (AppleTlsContext.SecurityLibrary, EntryPoint="SecIdentityGetTypeID")]
|
||||
public extern static IntPtr GetTypeID ();
|
||||
|
||||
[DllImport (AppleTlsContext.SecurityLibrary)]
|
||||
extern static /* OSStatus */ SecStatusCode SecIdentityCopyCertificate (/* SecIdentityRef */ IntPtr identityRef, /* SecCertificateRef* */ out IntPtr certificateRef);
|
||||
|
||||
public SecCertificate Certificate {
|
||||
get {
|
||||
if (handle == IntPtr.Zero)
|
||||
throw new ObjectDisposedException ("SecIdentity");
|
||||
IntPtr cert;
|
||||
SecStatusCode result = SecIdentityCopyCertificate (handle, out cert);
|
||||
if (result != SecStatusCode.Success)
|
||||
throw new InvalidOperationException (result.ToString ());
|
||||
return new SecCertificate (cert, true);
|
||||
}
|
||||
}
|
||||
|
||||
internal class ImportOptions
|
||||
{
|
||||
#if !MONOTOUCH
|
||||
public SecAccess Access {
|
||||
get; set;
|
||||
}
|
||||
public SecKeyChain KeyChain {
|
||||
get; set;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
static CFDictionary CreateImportOptions (CFString password, ImportOptions options = null)
|
||||
{
|
||||
if (options == null)
|
||||
return CFDictionary.FromObjectAndKey (password.Handle, ImportExportPassphase.Handle);
|
||||
|
||||
var items = new List<Tuple<IntPtr, IntPtr>> ();
|
||||
items.Add (new Tuple<IntPtr, IntPtr> (ImportExportPassphase.Handle, password.Handle));
|
||||
|
||||
#if !MONOTOUCH
|
||||
if (options.KeyChain != null)
|
||||
items.Add (new Tuple<IntPtr, IntPtr> (ImportExportKeychain.Handle, options.KeyChain.Handle));
|
||||
if (options.Access != null)
|
||||
items.Add (new Tuple<IntPtr, IntPtr> (ImportExportAccess.Handle, options.Access.Handle));
|
||||
#endif
|
||||
|
||||
return CFDictionary.FromKeysAndObjects (items);
|
||||
}
|
||||
|
||||
public static SecIdentity Import (byte[] data, string password, ImportOptions options = null)
|
||||
{
|
||||
if (data == null)
|
||||
throw new ArgumentNullException ("data");
|
||||
if (string.IsNullOrEmpty (password)) // SecPKCS12Import() doesn't allow empty passwords.
|
||||
throw new ArgumentException ("password");
|
||||
using (var pwstring = CFString.Create (password))
|
||||
using (var optionDict = CreateImportOptions (pwstring, options)) {
|
||||
CFDictionary [] array;
|
||||
SecStatusCode result = SecImportExport.ImportPkcs12 (data, optionDict, out array);
|
||||
if (result != SecStatusCode.Success)
|
||||
throw new InvalidOperationException (result.ToString ());
|
||||
|
||||
return new SecIdentity (array [0].GetValue (ImportItemIdentity.Handle));
|
||||
}
|
||||
}
|
||||
|
||||
public static SecIdentity Import (X509Certificate2 certificate, ImportOptions options = null)
|
||||
{
|
||||
if (certificate == null)
|
||||
throw new ArgumentNullException ("certificate");
|
||||
if (!certificate.HasPrivateKey)
|
||||
throw new InvalidOperationException ("Need X509Certificate2 with a private key.");
|
||||
|
||||
/*
|
||||
* SecPSK12Import does not allow any empty passwords, so let's generate
|
||||
* a semi-random one here.
|
||||
*/
|
||||
var password = Guid.NewGuid ().ToString ();
|
||||
var pkcs12 = certificate.Export (X509ContentType.Pfx, password);
|
||||
return Import (pkcs12, password, options);
|
||||
}
|
||||
|
||||
~SecIdentity ()
|
||||
{
|
||||
Dispose (false);
|
||||
}
|
||||
|
||||
public IntPtr Handle {
|
||||
get {
|
||||
return handle;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose ()
|
||||
{
|
||||
Dispose (true);
|
||||
GC.SuppressFinalize (this);
|
||||
}
|
||||
|
||||
protected virtual void Dispose (bool disposing)
|
||||
{
|
||||
if (handle != IntPtr.Zero){
|
||||
CFObject.CFRelease (handle);
|
||||
handle = IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
partial class SecKey : INativeObject, IDisposable {
|
||||
internal IntPtr handle;
|
||||
internal IntPtr owner;
|
||||
|
||||
public SecKey (IntPtr handle, bool owns = false)
|
||||
{
|
||||
this.handle = handle;
|
||||
if (!owns)
|
||||
CFObject.CFRetain (handle);
|
||||
}
|
||||
|
||||
/*
|
||||
* SecItemImport() returns a SecArrayRef. We need to free the array, not the items inside it.
|
||||
*
|
||||
*/
|
||||
internal SecKey (IntPtr handle, IntPtr owner)
|
||||
{
|
||||
this.handle = handle;
|
||||
this.owner = owner;
|
||||
CFObject.CFRetain (owner);
|
||||
}
|
||||
|
||||
[DllImport (AppleTlsContext.SecurityLibrary, EntryPoint="SecKeyGetTypeID")]
|
||||
public extern static IntPtr GetTypeID ();
|
||||
|
||||
~SecKey ()
|
||||
{
|
||||
Dispose (false);
|
||||
}
|
||||
|
||||
public IntPtr Handle {
|
||||
get {
|
||||
return handle;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose ()
|
||||
{
|
||||
Dispose (true);
|
||||
GC.SuppressFinalize (this);
|
||||
}
|
||||
|
||||
protected virtual void Dispose (bool disposing)
|
||||
{
|
||||
if (owner != IntPtr.Zero) {
|
||||
CFObject.CFRelease (owner);
|
||||
owner = handle = IntPtr.Zero;
|
||||
} else if (handle != IntPtr.Zero) {
|
||||
CFObject.CFRelease (handle);
|
||||
handle = IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if !MONOTOUCH
|
||||
class SecAccess : INativeObject, IDisposable {
|
||||
internal IntPtr handle;
|
||||
|
||||
public SecAccess (IntPtr handle, bool owns = false)
|
||||
{
|
||||
this.handle = handle;
|
||||
if (!owns)
|
||||
CFObject.CFRetain (handle);
|
||||
}
|
||||
|
||||
~SecAccess ()
|
||||
{
|
||||
Dispose (false);
|
||||
}
|
||||
|
||||
public IntPtr Handle {
|
||||
get {
|
||||
return handle;
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport (AppleTlsContext.SecurityLibrary)]
|
||||
extern static /* OSStatus */ SecStatusCode SecAccessCreate (/* CFStringRef */ IntPtr descriptor, /* CFArrayRef */ IntPtr trustedList, /* SecAccessRef _Nullable * */ out IntPtr accessRef);
|
||||
|
||||
public static SecAccess Create (string descriptor)
|
||||
{
|
||||
var descriptorHandle = CFString.Create (descriptor);
|
||||
if (descriptorHandle == null)
|
||||
throw new InvalidOperationException ();
|
||||
|
||||
try {
|
||||
IntPtr accessRef;
|
||||
var result = SecAccessCreate (descriptorHandle.Handle, IntPtr.Zero, out accessRef);
|
||||
if (result != SecStatusCode.Success)
|
||||
throw new InvalidOperationException (result.ToString ());
|
||||
|
||||
return new SecAccess (accessRef, true);
|
||||
} finally {
|
||||
descriptorHandle.Dispose ();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose ()
|
||||
{
|
||||
Dispose (true);
|
||||
GC.SuppressFinalize (this);
|
||||
}
|
||||
|
||||
protected virtual void Dispose (bool disposing)
|
||||
{
|
||||
if (handle != IntPtr.Zero) {
|
||||
CFObject.CFRelease (handle);
|
||||
handle = IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,408 @@
|
||||
#if MONO_FEATURE_APPLETLS
|
||||
// Copyright 2011-2015 Xamarin Inc. All rights reserved.
|
||||
|
||||
using ObjCRuntime;
|
||||
|
||||
namespace Mono.AppleTls {
|
||||
|
||||
// this is a subset of OSStatus -> SInt32 -> signed int - see CoreFoundation.framework/Headers/CFBase.h
|
||||
// values are defined in Security.framework/Headers/SecBase.h
|
||||
enum SecStatusCode {
|
||||
Success = 0,
|
||||
Unimplemented = -4,
|
||||
DiskFull = -34,
|
||||
IO = -36,
|
||||
OpWr = -49,
|
||||
Param = -50,
|
||||
WritePermissions = -61,
|
||||
Allocate = -108,
|
||||
UserCanceled = -128,
|
||||
BadReq = -909,
|
||||
InternalComponent = -2070,
|
||||
CoreFoundationUnknown = -4960,
|
||||
NotAvailable = -25291,
|
||||
ReadOnly = -25292,
|
||||
AuthFailed = -25293,
|
||||
NoSuchKeyChain = -25294,
|
||||
InvalidKeyChain = -25295,
|
||||
DuplicateKeyChain = -25296,
|
||||
DuplicateItem = -25299,
|
||||
ItemNotFound = -25300,
|
||||
InteractionNotAllowed = -25308,
|
||||
Decode = -26275,
|
||||
DuplicateCallback = -25297,
|
||||
InvalidCallback = -25298,
|
||||
BufferTooSmall = -25301,
|
||||
DataTooLarge = -25302,
|
||||
NoSuchAttribute = -25303,
|
||||
InvalidItemRef = -25304,
|
||||
InvalidSearchRef = -25305,
|
||||
NoSuchClass = -25306,
|
||||
NoDefaultKeychain = -25307,
|
||||
ReadOnlyAttribute = -25309,
|
||||
WrongSecVersion = -25310,
|
||||
KeySizeNotAllowed = -25311,
|
||||
NoStorageModule = -25312,
|
||||
NoCertificateModule = -25313,
|
||||
NoPolicyModule = -25314,
|
||||
InteractionRequired = -25315,
|
||||
DataNotAvailable = -25316,
|
||||
DataNotModifiable = -25317,
|
||||
CreateChainFailed = -25318,
|
||||
InvalidPrefsDomain = -25319,
|
||||
InDarkWake = -25320,
|
||||
ACLNotSimple = -25240,
|
||||
PolicyNotFound = -25241,
|
||||
InvalidTrustSetting = -25242,
|
||||
NoAccessForItem = -25243,
|
||||
InvalidOwnerEdit = -25244,
|
||||
TrustNotAvailable = -25245,
|
||||
UnsupportedFormat = -25256,
|
||||
UnknownFormat = -25257,
|
||||
KeyIsSensitive = -25258,
|
||||
MultiplePrivateKeys = -25259,
|
||||
PassphraseRequired = -25260,
|
||||
InvalidPasswordRef = -25261,
|
||||
InvalidTrustSettings = -25262,
|
||||
NoTrustSettings = -25263,
|
||||
Pkcs12VerifyFailure = -25264,
|
||||
NotSigner = -26267,
|
||||
ServiceNotAvailable = -67585,
|
||||
InsufficientClientID = -67586,
|
||||
DeviceReset = -67587,
|
||||
DeviceFailed = -67588,
|
||||
AppleAddAppACLSubject = -67589,
|
||||
ApplePublicKeyIncomplete = -67590,
|
||||
AppleSignatureMismatch = -67591,
|
||||
AppleInvalidKeyStartDate = -67592,
|
||||
AppleInvalidKeyEndDate = -67593,
|
||||
ConversionError = -67594,
|
||||
AppleSSLv2Rollback = -67595,
|
||||
QuotaExceeded = -67596,
|
||||
FileTooBig = -67597,
|
||||
InvalidDatabaseBlob = -67598,
|
||||
InvalidKeyBlob = -67599,
|
||||
IncompatibleDatabaseBlob = -67600,
|
||||
IncompatibleKeyBlob = -67601,
|
||||
HostNameMismatch = -67602,
|
||||
UnknownCriticalExtensionFlag = -67603,
|
||||
NoBasicConstraints = -67604,
|
||||
NoBasicConstraintsCA = -67605,
|
||||
InvalidAuthorityKeyID = -67606,
|
||||
InvalidSubjectKeyID = -67607, /* The subject key ID is not valid. */
|
||||
InvalidKeyUsageForPolicy = -67608, /* The key usage is not valid for the specified policy. */
|
||||
InvalidExtendedKeyUsage = -67609, /* The extended key usage is not valid. */
|
||||
InvalidIDLinkage = -67610, /* The ID linkage is not valid. */
|
||||
PathLengthConstraintExceeded = -67611, /* The path length constraint was exceeded. */
|
||||
InvalidRoot = -67612, /* The root or anchor certificate is not valid. */
|
||||
CRLExpired = -67613, /* The CRL has expired. */
|
||||
CRLNotValidYet = -67614, /* The CRL is not yet valid. */
|
||||
CRLNotFound = -67615, /* The CRL was not found. */
|
||||
CRLServerDown = -67616, /* The CRL server is down. */
|
||||
CRLBadURI = -67617, /* The CRL has a bad Uniform Resource Identifier. */
|
||||
UnknownCertExtension = -67618, /* An unknown certificate extension was encountered. */
|
||||
UnknownCRLExtension = -67619, /* An unknown CRL extension was encountered. */
|
||||
CRLNotTrusted = -67620, /* The CRL is not trusted. */
|
||||
CRLPolicyFailed = -67621, /* The CRL policy failed. */
|
||||
IDPFailure = -67622, /* The issuing distribution point was not valid. */
|
||||
SMIMEEmailAddressesNotFound = -67623, /* An email address mismatch was encountered. */
|
||||
SMIMEBadExtendedKeyUsage = -67624, /* The appropriate extended key usage for SMIME was not found. */
|
||||
SMIMEBadKeyUsage = -67625, /* The key usage is not compatible with SMIME. */
|
||||
SMIMEKeyUsageNotCritical = -67626, /* The key usage extension is not marked as critical. */
|
||||
SMIMENoEmailAddress = -67627, /* No email address was found in the certificate. */
|
||||
SMIMESubjAltNameNotCritical = -67628, /* The subject alternative name extension is not marked as critical. */
|
||||
SSLBadExtendedKeyUsage = -67629, /* The appropriate extended key usage for SSL was not found. */
|
||||
OCSPBadResponse = -67630, /* The OCSP response was incorrect or could not be parsed. */
|
||||
OCSPBadRequest = -67631, /* The OCSP request was incorrect or could not be parsed. */
|
||||
OCSPUnavailable = -67632, /* OCSP service is unavailable. */
|
||||
OCSPStatusUnrecognized = -67633, /* The OCSP server did not recognize this certificate. */
|
||||
EndOfData = -67634, /* An end-of-data was detected. */
|
||||
IncompleteCertRevocationCheck = -67635, /* An incomplete certificate revocation check occurred. */
|
||||
NetworkFailure = -67636, /* A network failure occurred. */
|
||||
OCSPNotTrustedToAnchor = -67637, /* The OCSP response was not trusted to a root or anchor certificate. */
|
||||
RecordModified = -67638, /* The record was modified. */
|
||||
OCSPSignatureError = -67639, /* The OCSP response had an invalid signature. */
|
||||
OCSPNoSigner = -67640, /* The OCSP response had no signer. */
|
||||
OCSPResponderMalformedReq = -67641, /* The OCSP responder was given a malformed request. */
|
||||
OCSPResponderInternalError = -67642, /* The OCSP responder encountered an internal error. */
|
||||
OCSPResponderTryLater = -67643, /* The OCSP responder is busy, try again later. */
|
||||
OCSPResponderSignatureRequired = -67644, /* The OCSP responder requires a signature. */
|
||||
OCSPResponderUnauthorized = -67645, /* The OCSP responder rejected this request as unauthorized. */
|
||||
OCSPResponseNonceMismatch = -67646, /* The OCSP response nonce did not match the request. */
|
||||
CodeSigningBadCertChainLength = -67647, /* Code signing encountered an incorrect certificate chain length. */
|
||||
CodeSigningNoBasicConstraints = -67648, /* Code signing found no basic constraints. */
|
||||
CodeSigningBadPathLengthConstraint = -67649, /* Code signing encountered an incorrect path length constraint. */
|
||||
CodeSigningNoExtendedKeyUsage = -67650, /* Code signing found no extended key usage. */
|
||||
CodeSigningDevelopment = -67651, /* Code signing indicated use of a development-only certificate. */
|
||||
ResourceSignBadCertChainLength = -67652, /* Resource signing has encountered an incorrect certificate chain length. */
|
||||
ResourceSignBadExtKeyUsage = -67653, /* Resource signing has encountered an error in the extended key usage. */
|
||||
TrustSettingDeny = -67654, /* The trust setting for this policy was set to Deny. */
|
||||
InvalidSubjectName = -67655, /* An invalid certificate subject name was encountered. */
|
||||
UnknownQualifiedCertStatement = -67656, /* An unknown qualified certificate statement was encountered. */
|
||||
MobileMeRequestQueued = -67657, /* The MobileMe request will be sent during the next connection. */
|
||||
MobileMeRequestRedirected = -67658, /* The MobileMe request was redirected. */
|
||||
MobileMeServerError = -67659, /* A MobileMe server error occurred. */
|
||||
MobileMeServerNotAvailable = -67660, /* The MobileMe server is not available. */
|
||||
MobileMeServerAlreadyExists = -67661, /* The MobileMe server reported that the item already exists. */
|
||||
MobileMeServerServiceErr = -67662, /* A MobileMe service error has occurred. */
|
||||
MobileMeRequestAlreadyPending = -67663, /* A MobileMe request is already pending. */
|
||||
MobileMeNoRequestPending = -67664, /* MobileMe has no request pending. */
|
||||
MobileMeCSRVerifyFailure = -67665, /* A MobileMe CSR verification failure has occurred. */
|
||||
MobileMeFailedConsistencyCheck = -67666, /* MobileMe has found a failed consistency check. */
|
||||
NotInitialized = -67667, /* A function was called without initializing CSSM. */
|
||||
InvalidHandleUsage = -67668, /* The CSSM handle does not match with the service type. */
|
||||
PVCReferentNotFound = -67669, /* A reference to the calling module was not found in the list of authorized callers. */
|
||||
FunctionIntegrityFail = -67670, /* A function address was not within the verified module. */
|
||||
InternalError = -67671, /* An internal error has occurred. */
|
||||
MemoryError = -67672, /* A memory error has occurred. */
|
||||
InvalidData = -67673, /* Invalid data was encountered. */
|
||||
MDSError = -67674, /* A Module Directory Service error has occurred. */
|
||||
InvalidPointer = -67675, /* An invalid pointer was encountered. */
|
||||
SelfCheckFailed = -67676, /* Self-check has failed. */
|
||||
FunctionFailed = -67677, /* A function has failed. */
|
||||
ModuleManifestVerifyFailed = -67678, /* A module manifest verification failure has occurred. */
|
||||
InvalidGUID = -67679, /* An invalid GUID was encountered. */
|
||||
InvalidHandle = -67680, /* An invalid handle was encountered. */
|
||||
InvalidDBList = -67681, /* An invalid DB list was encountered. */
|
||||
InvalidPassthroughID = -67682, /* An invalid passthrough ID was encountered. */
|
||||
InvalidNetworkAddress = -67683, /* An invalid network address was encountered. */
|
||||
CRLAlreadySigned = -67684, /* The certificate revocation list is already signed. */
|
||||
InvalidNumberOfFields = -67685, /* An invalid number of fields were encountered. */
|
||||
VerificationFailure = -67686, /* A verification failure occurred. */
|
||||
UnknownTag = -67687, /* An unknown tag was encountered. */
|
||||
InvalidSignature = -67688, /* An invalid signature was encountered. */
|
||||
InvalidName = -67689, /* An invalid name was encountered. */
|
||||
InvalidCertificateRef = -67690, /* An invalid certificate reference was encountered. */
|
||||
InvalidCertificateGroup = -67691, /* An invalid certificate group was encountered. */
|
||||
TagNotFound = -67692, /* The specified tag was not found. */
|
||||
InvalidQuery = -67693, /* The specified query was not valid. */
|
||||
InvalidValue = -67694, /* An invalid value was detected. */
|
||||
CallbackFailed = -67695, /* A callback has failed. */
|
||||
ACLDeleteFailed = -67696, /* An ACL delete operation has failed. */
|
||||
ACLReplaceFailed = -67697, /* An ACL replace operation has failed. */
|
||||
ACLAddFailed = -67698, /* An ACL add operation has failed. */
|
||||
ACLChangeFailed = -67699, /* An ACL change operation has failed. */
|
||||
InvalidAccessCredentials = -67700, /* Invalid access credentials were encountered. */
|
||||
InvalidRecord = -67701, /* An invalid record was encountered. */
|
||||
InvalidACL = -67702, /* An invalid ACL was encountered. */
|
||||
InvalidSampleValue = -67703, /* An invalid sample value was encountered. */
|
||||
IncompatibleVersion = -67704, /* An incompatible version was encountered. */
|
||||
PrivilegeNotGranted = -67705, /* The privilege was not granted. */
|
||||
InvalidScope = -67706, /* An invalid scope was encountered. */
|
||||
PVCAlreadyConfigured = -67707, /* The PVC is already configured. */
|
||||
InvalidPVC = -67708, /* An invalid PVC was encountered. */
|
||||
EMMLoadFailed = -67709, /* The EMM load has failed. */
|
||||
EMMUnloadFailed = -67710, /* The EMM unload has failed. */
|
||||
AddinLoadFailed = -67711, /* The add-in load operation has failed. */
|
||||
InvalidKeyRef = -67712, /* An invalid key was encountered. */
|
||||
InvalidKeyHierarchy = -67713, /* An invalid key hierarchy was encountered. */
|
||||
AddinUnloadFailed = -67714, /* The add-in unload operation has failed. */
|
||||
LibraryReferenceNotFound = -67715, /* A library reference was not found. */
|
||||
InvalidAddinFunctionTable = -67716, /* An invalid add-in function table was encountered. */
|
||||
InvalidServiceMask = -67717, /* An invalid service mask was encountered. */
|
||||
ModuleNotLoaded = -67718, /* A module was not loaded. */
|
||||
InvalidSubServiceID = -67719, /* An invalid subservice ID was encountered. */
|
||||
AttributeNotInContext = -67720, /* An attribute was not in the context. */
|
||||
ModuleManagerInitializeFailed = -67721, /* A module failed to initialize. */
|
||||
ModuleManagerNotFound = -67722, /* A module was not found. */
|
||||
EventNotificationCallbackNotFound = -67723, /* An event notification callback was not found. */
|
||||
InputLengthError = -67724, /* An input length error was encountered. */
|
||||
OutputLengthError = -67725, /* An output length error was encountered. */
|
||||
PrivilegeNotSupported = -67726, /* The privilege is not supported. */
|
||||
DeviceError = -67727, /* A device error was encountered. */
|
||||
AttachHandleBusy = -67728, /* The CSP handle was busy. */
|
||||
NotLoggedIn = -67729, /* You are not logged in. */
|
||||
AlgorithmMismatch = -67730, /* An algorithm mismatch was encountered. */
|
||||
KeyUsageIncorrect = -67731, /* The key usage is incorrect. */
|
||||
KeyBlobTypeIncorrect = -67732, /* The key blob type is incorrect. */
|
||||
KeyHeaderInconsistent = -67733, /* The key header is inconsistent. */
|
||||
UnsupportedKeyFormat = -67734, /* The key header format is not supported. */
|
||||
UnsupportedKeySize = -67735, /* The key size is not supported. */
|
||||
InvalidKeyUsageMask = -67736, /* The key usage mask is not valid. */
|
||||
UnsupportedKeyUsageMask = -67737, /* The key usage mask is not supported. */
|
||||
InvalidKeyAttributeMask = -67738, /* The key attribute mask is not valid. */
|
||||
UnsupportedKeyAttributeMask = -67739, /* The key attribute mask is not supported. */
|
||||
InvalidKeyLabel = -67740, /* The key label is not valid. */
|
||||
UnsupportedKeyLabel = -67741, /* The key label is not supported. */
|
||||
InvalidKeyFormat = -67742, /* The key format is not valid. */
|
||||
UnsupportedVectorOfBuffers = -67743, /* The vector of buffers is not supported. */
|
||||
InvalidInputVector = -67744, /* The input vector is not valid. */
|
||||
InvalidOutputVector = -67745, /* The output vector is not valid. */
|
||||
InvalidContext = -67746, /* An invalid context was encountered. */
|
||||
InvalidAlgorithm = -67747, /* An invalid algorithm was encountered. */
|
||||
InvalidAttributeKey = -67748, /* A key attribute was not valid. */
|
||||
MissingAttributeKey = -67749, /* A key attribute was missing. */
|
||||
InvalidAttributeInitVector = -67750, /* An init vector attribute was not valid. */
|
||||
MissingAttributeInitVector = -67751, /* An init vector attribute was missing. */
|
||||
InvalidAttributeSalt = -67752, /* A salt attribute was not valid. */
|
||||
MissingAttributeSalt = -67753, /* A salt attribute was missing. */
|
||||
InvalidAttributePadding = -67754, /* A padding attribute was not valid. */
|
||||
MissingAttributePadding = -67755, /* A padding attribute was missing. */
|
||||
InvalidAttributeRandom = -67756, /* A random number attribute was not valid. */
|
||||
MissingAttributeRandom = -67757, /* A random number attribute was missing. */
|
||||
InvalidAttributeSeed = -67758, /* A seed attribute was not valid. */
|
||||
MissingAttributeSeed = -67759, /* A seed attribute was missing. */
|
||||
InvalidAttributePassphrase = -67760, /* A passphrase attribute was not valid. */
|
||||
MissingAttributePassphrase = -67761, /* A passphrase attribute was missing. */
|
||||
InvalidAttributeKeyLength = -67762, /* A key length attribute was not valid. */
|
||||
MissingAttributeKeyLength = -67763, /* A key length attribute was missing. */
|
||||
InvalidAttributeBlockSize = -67764, /* A block size attribute was not valid. */
|
||||
MissingAttributeBlockSize = -67765, /* A block size attribute was missing. */
|
||||
InvalidAttributeOutputSize = -67766, /* An output size attribute was not valid. */
|
||||
MissingAttributeOutputSize = -67767, /* An output size attribute was missing. */
|
||||
InvalidAttributeRounds = -67768, /* The number of rounds attribute was not valid. */
|
||||
MissingAttributeRounds = -67769, /* The number of rounds attribute was missing. */
|
||||
InvalidAlgorithmParms = -67770, /* An algorithm parameters attribute was not valid. */
|
||||
MissingAlgorithmParms = -67771, /* An algorithm parameters attribute was missing. */
|
||||
InvalidAttributeLabel = -67772, /* A label attribute was not valid. */
|
||||
MissingAttributeLabel = -67773, /* A label attribute was missing. */
|
||||
InvalidAttributeKeyType = -67774, /* A key type attribute was not valid. */
|
||||
MissingAttributeKeyType = -67775, /* A key type attribute was missing. */
|
||||
InvalidAttributeMode = -67776, /* A mode attribute was not valid. */
|
||||
MissingAttributeMode = -67777, /* A mode attribute was missing. */
|
||||
InvalidAttributeEffectiveBits = -67778, /* An effective bits attribute was not valid. */
|
||||
MissingAttributeEffectiveBits = -67779, /* An effective bits attribute was missing. */
|
||||
InvalidAttributeStartDate = -67780, /* A start date attribute was not valid. */
|
||||
MissingAttributeStartDate = -67781, /* A start date attribute was missing. */
|
||||
InvalidAttributeEndDate = -67782, /* An end date attribute was not valid. */
|
||||
MissingAttributeEndDate = -67783, /* An end date attribute was missing. */
|
||||
InvalidAttributeVersion = -67784, /* A version attribute was not valid. */
|
||||
MissingAttributeVersion = -67785, /* A version attribute was missing. */
|
||||
InvalidAttributePrime = -67786, /* A prime attribute was not valid. */
|
||||
MissingAttributePrime = -67787, /* A prime attribute was missing. */
|
||||
InvalidAttributeBase = -67788, /* A base attribute was not valid. */
|
||||
MissingAttributeBase = -67789, /* A base attribute was missing. */
|
||||
InvalidAttributeSubprime = -67790, /* A subprime attribute was not valid. */
|
||||
MissingAttributeSubprime = -67791, /* A subprime attribute was missing. */
|
||||
InvalidAttributeIterationCount = -67792, /* An iteration count attribute was not valid. */
|
||||
MissingAttributeIterationCount = -67793, /* An iteration count attribute was missing. */
|
||||
InvalidAttributeDLDBHandle = -67794, /* A database handle attribute was not valid. */
|
||||
MissingAttributeDLDBHandle = -67795, /* A database handle attribute was missing. */
|
||||
InvalidAttributeAccessCredentials = -67796, /* An access credentials attribute was not valid. */
|
||||
MissingAttributeAccessCredentials = -67797, /* An access credentials attribute was missing. */
|
||||
InvalidAttributePublicKeyFormat = -67798, /* A public key format attribute was not valid. */
|
||||
MissingAttributePublicKeyFormat = -67799, /* A public key format attribute was missing. */
|
||||
InvalidAttributePrivateKeyFormat = -67800, /* A private key format attribute was not valid. */
|
||||
MissingAttributePrivateKeyFormat = -67801, /* A private key format attribute was missing. */
|
||||
InvalidAttributeSymmetricKeyFormat = -67802, /* A symmetric key format attribute was not valid. */
|
||||
MissingAttributeSymmetricKeyFormat = -67803, /* A symmetric key format attribute was missing. */
|
||||
InvalidAttributeWrappedKeyFormat = -67804, /* A wrapped key format attribute was not valid. */
|
||||
MissingAttributeWrappedKeyFormat = -67805, /* A wrapped key format attribute was missing. */
|
||||
StagedOperationInProgress = -67806, /* A staged operation is in progress. */
|
||||
StagedOperationNotStarted = -67807, /* A staged operation was not started. */
|
||||
VerifyFailed = -67808, /* A cryptographic verification failure has occurred. */
|
||||
QuerySizeUnknown = -67809, /* The query size is unknown. */
|
||||
BlockSizeMismatch = -67810, /* A block size mismatch occurred. */
|
||||
PublicKeyInconsistent = -67811, /* The public key was inconsistent. */
|
||||
DeviceVerifyFailed = -67812, /* A device verification failure has occurred. */
|
||||
InvalidLoginName = -67813, /* An invalid login name was detected. */
|
||||
AlreadyLoggedIn = -67814, /* The user is already logged in. */
|
||||
InvalidDigestAlgorithm = -67815, /* An invalid digest algorithm was detected. */
|
||||
InvalidCRLGroup = -67816, /* An invalid CRL group was detected. */
|
||||
CertificateCannotOperate = -67817, /* The certificate cannot operate. */
|
||||
CertificateExpired = -67818, /* An expired certificate was detected. */
|
||||
CertificateNotValidYet = -67819, /* The certificate is not yet valid. */
|
||||
CertificateRevoked = -67820, /* The certificate was revoked. */
|
||||
CertificateSuspended = -67821, /* The certificate was suspended. */
|
||||
InsufficientCredentials = -67822, /* Insufficient credentials were detected. */
|
||||
InvalidAction = -67823, /* The action was not valid. */
|
||||
InvalidAuthority = -67824, /* The authority was not valid. */
|
||||
VerifyActionFailed = -67825, /* A verify action has failed. */
|
||||
InvalidCertAuthority = -67826, /* The certificate authority was not valid. */
|
||||
InvalidCRLAuthority = -67827, /* The CRL authority was not valid. */
|
||||
#if MONOMAC
|
||||
[Obsolete ("Use InvalidCRLAuthority")]
|
||||
InvaldCRLAuthority = InvalidCRLAuthority,
|
||||
#endif
|
||||
InvalidCRLEncoding = -67828, /* The CRL encoding was not valid. */
|
||||
InvalidCRLType = -67829, /* The CRL type was not valid. */
|
||||
InvalidCRL = -67830, /* The CRL was not valid. */
|
||||
InvalidFormType = -67831, /* The form type was not valid. */
|
||||
InvalidID = -67832, /* The ID was not valid. */
|
||||
InvalidIdentifier = -67833, /* The identifier was not valid. */
|
||||
InvalidIndex = -67834, /* The index was not valid. */
|
||||
InvalidPolicyIdentifiers = -67835, /* The policy identifiers are not valid. */
|
||||
InvalidTimeString = -67836, /* The time specified was not valid. */
|
||||
InvalidReason = -67837, /* The trust policy reason was not valid. */
|
||||
InvalidRequestInputs = -67838, /* The request inputs are not valid. */
|
||||
InvalidResponseVector = -67839, /* The response vector was not valid. */
|
||||
InvalidStopOnPolicy = -67840, /* The stop-on policy was not valid. */
|
||||
InvalidTuple = -67841, /* The tuple was not valid. */
|
||||
MultipleValuesUnsupported = -67842, /* Multiple values are not supported. */
|
||||
NotTrusted = -67843, /* The trust policy was not trusted. */
|
||||
NoDefaultAuthority = -67844, /* No default authority was detected. */
|
||||
RejectedForm = -67845, /* The trust policy had a rejected form. */
|
||||
RequestLost = -67846, /* The request was lost. */
|
||||
RequestRejected = -67847, /* The request was rejected. */
|
||||
UnsupportedAddressType = -67848, /* The address type is not supported. */
|
||||
UnsupportedService = -67849, /* The service is not supported. */
|
||||
InvalidTupleGroup = -67850, /* The tuple group was not valid. */
|
||||
InvalidBaseACLs = -67851, /* The base ACLs are not valid. */
|
||||
InvalidTupleCredentials = -67852, /* The tuple credentials are not valid. */
|
||||
#if MONOMAC
|
||||
[Obsolete ("Use InvalidTupleCredentials")]
|
||||
InvalidTupleCredendtials = InvalidTupleCredentials,
|
||||
#endif
|
||||
InvalidEncoding = -67853, /* The encoding was not valid. */
|
||||
InvalidValidityPeriod = -67854, /* The validity period was not valid. */
|
||||
InvalidRequestor = -67855, /* The requestor was not valid. */
|
||||
RequestDescriptor = -67856, /* The request descriptor was not valid. */
|
||||
InvalidBundleInfo = -67857, /* The bundle information was not valid. */
|
||||
InvalidCRLIndex = -67858, /* The CRL index was not valid. */
|
||||
NoFieldValues = -67859, /* No field values were detected. */
|
||||
UnsupportedFieldFormat = -67860, /* The field format is not supported. */
|
||||
UnsupportedIndexInfo = -67861, /* The index information is not supported. */
|
||||
UnsupportedLocality = -67862, /* The locality is not supported. */
|
||||
UnsupportedNumAttributes = -67863, /* The number of attributes is not supported. */
|
||||
UnsupportedNumIndexes = -67864, /* The number of indexes is not supported. */
|
||||
UnsupportedNumRecordTypes = -67865, /* The number of record types is not supported. */
|
||||
FieldSpecifiedMultiple = -67866, /* Too many fields were specified. */
|
||||
IncompatibleFieldFormat = -67867, /* The field format was incompatible. */
|
||||
InvalidParsingModule = -67868, /* The parsing module was not valid. */
|
||||
DatabaseLocked = -67869, /* The database is locked. */
|
||||
DatastoreIsOpen = -67870, /* The data store is open. */
|
||||
MissingValue = -67871, /* A missing value was detected. */
|
||||
UnsupportedQueryLimits = -67872, /* The query limits are not supported. */
|
||||
UnsupportedNumSelectionPreds = -67873, /* The number of selection predicates is not supported. */
|
||||
UnsupportedOperator = -67874, /* The operator is not supported. */
|
||||
InvalidDBLocation = -67875, /* The database location is not valid. */
|
||||
InvalidAccessRequest = -67876, /* The access request is not valid. */
|
||||
InvalidIndexInfo = -67877, /* The index information is not valid. */
|
||||
InvalidNewOwner = -67878, /* The new owner is not valid. */
|
||||
InvalidModifyMode = -67879, /* The modify mode is not valid. */
|
||||
MissingRequiredExtension = -67880, /* A required certificate extension is missing. */
|
||||
ExtendedKeyUsageNotCritical = -67881, /* The extended key usage extension was not marked critical. */
|
||||
TimestampMissing = -67882, /* A timestamp was expected but was not found. */
|
||||
TimestampInvalid = -67883, /* The timestamp was not valid. */
|
||||
TimestampNotTrusted = -67884, /* The timestamp was not trusted. */
|
||||
TimestampServiceNotAvailable = -67885, /* The timestamp service is not available. */
|
||||
TimestampBadAlg = -67886, /* An unrecognized or unsupported Algorithm Identifier in timestamp. */
|
||||
TimestampBadRequest = -67887, /* The timestamp transaction is not permitted or supported. */
|
||||
TimestampBadDataFormat = -67888, /* The timestamp data submitted has the wrong format. */
|
||||
TimestampTimeNotAvailable = -67889, /* The time source for the Timestamp Authority is not available. */
|
||||
TimestampUnacceptedPolicy = -67890, /* The requested policy is not supported by the Timestamp Authority. */
|
||||
TimestampUnacceptedExtension = -67891, /* The requested extension is not supported by the Timestamp Authority. */
|
||||
TimestampAddInfoNotAvailable = -67892, /* The additional information requested is not available. */
|
||||
TimestampSystemFailure = -67893, /* The timestamp request cannot be handled due to system failure. */
|
||||
SigningTimeMissing = -67894, /* A signing time was expected but was not found. */
|
||||
TimestampRejection = -67895, /* A timestamp transaction was rejected. */
|
||||
TimestampWaiting = -67896, /* A timestamp transaction is waiting. */
|
||||
TimestampRevocationWarning = -67897, /* A timestamp authority revocation warning was issued. */
|
||||
TimestampRevocationNotification = -67898, /* A timestamp authority revocation notification was issued. */
|
||||
}
|
||||
|
||||
// typedef uint32_t SecTrustResultType;
|
||||
// values are defined in Security.framework/Headers/SecTrust.h
|
||||
enum SecTrustResult {
|
||||
Invalid,
|
||||
Proceed,
|
||||
|
||||
Confirm,
|
||||
Deny,
|
||||
Unspecified,
|
||||
RecoverableTrustFailure,
|
||||
FatalTrustFailure,
|
||||
ResultOtherError,
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,21 @@
|
||||
using System;
|
||||
|
||||
namespace ObjCRuntime {
|
||||
|
||||
internal interface INativeObject {
|
||||
IntPtr Handle {
|
||||
get;
|
||||
}
|
||||
}
|
||||
|
||||
static class NativeObjectHelper {
|
||||
|
||||
// help to avoid the (too common pattern)
|
||||
// var p = x == null ? IntPtr.Zero : x.Handle;
|
||||
static public IntPtr GetHandle (this INativeObject self)
|
||||
{
|
||||
return self == null ? IntPtr.Zero : self.Handle;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
#if SECURITY_DEP && MONO_FEATURE_APPLETLS
|
||||
//
|
||||
// ImportExport.cs
|
||||
//
|
||||
// Authors:
|
||||
// Sebastien Pouliot <[email protected]>
|
||||
//
|
||||
// Copyright 2011-2014 Xamarin Inc.
|
||||
//
|
||||
// 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.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using ObjCRuntime;
|
||||
using Mono.Net;
|
||||
|
||||
#if MONO_FEATURE_BTLS
|
||||
using Mono.Btls;
|
||||
#else
|
||||
using Mono.Security.Cryptography;
|
||||
#endif
|
||||
|
||||
namespace Mono.AppleTls {
|
||||
|
||||
internal partial class SecImportExport {
|
||||
|
||||
[DllImport (AppleTlsContext.SecurityLibrary)]
|
||||
extern static SecStatusCode SecPKCS12Import (IntPtr pkcs12_data, IntPtr options, out IntPtr items);
|
||||
|
||||
static public SecStatusCode ImportPkcs12 (byte[] buffer, CFDictionary options, out CFDictionary[] array)
|
||||
{
|
||||
using (CFData data = CFData.FromData (buffer)) {
|
||||
return ImportPkcs12 (data, options, out array);
|
||||
}
|
||||
}
|
||||
|
||||
static public SecStatusCode ImportPkcs12 (CFData data, CFDictionary options, out CFDictionary [] array)
|
||||
{
|
||||
if (options == null)
|
||||
throw new ArgumentNullException ("options");
|
||||
|
||||
IntPtr handle;
|
||||
SecStatusCode code = SecPKCS12Import (data.Handle, options.Handle, out handle);
|
||||
array = CFArray.ArrayFromHandle <CFDictionary> (handle, h => new CFDictionary (h, false));
|
||||
if (handle != IntPtr.Zero)
|
||||
CFObject.CFRelease (handle);
|
||||
return code;
|
||||
}
|
||||
|
||||
#if !MONOTOUCH
|
||||
[DllImport (AppleTlsContext.SecurityLibrary)]
|
||||
extern static SecStatusCode SecItemImport (
|
||||
/* CFDataRef */ IntPtr importedData,
|
||||
/* CFStringRef */ IntPtr fileNameOrExtension, // optional
|
||||
/* SecExternalFormat* */ ref SecExternalFormat inputFormat, // optional, IN/OUT
|
||||
/* SecExternalItemType* */ ref SecExternalItemType itemType, // optional, IN/OUT
|
||||
/* SecItemImportExportFlags */ SecItemImportExportFlags flags,
|
||||
/* const SecItemImportExportKeyParameters* */ IntPtr keyParams, // optional
|
||||
/* SecKeychainRef */ IntPtr importKeychain, // optional
|
||||
/* CFArrayRef* */ out IntPtr outItems);
|
||||
|
||||
static public CFArray ItemImport (byte[] buffer, string password)
|
||||
{
|
||||
using (var data = CFData.FromData (buffer))
|
||||
using (var pwstring = CFString.Create (password)) {
|
||||
SecItemImportExportKeyParameters keyParams = new SecItemImportExportKeyParameters ();
|
||||
keyParams.passphrase = pwstring.Handle;
|
||||
|
||||
return ItemImport (data, SecExternalFormat.PKCS12, SecExternalItemType.Aggregate, SecItemImportExportFlags.None, keyParams);
|
||||
}
|
||||
}
|
||||
|
||||
static CFArray ItemImport (CFData data, SecExternalFormat format, SecExternalItemType itemType,
|
||||
SecItemImportExportFlags flags = SecItemImportExportFlags.None,
|
||||
SecItemImportExportKeyParameters? keyParams = null)
|
||||
{
|
||||
return ItemImport (data, ref format, ref itemType, flags, keyParams);
|
||||
}
|
||||
|
||||
static CFArray ItemImport (CFData data, ref SecExternalFormat format, ref SecExternalItemType itemType,
|
||||
SecItemImportExportFlags flags = SecItemImportExportFlags.None,
|
||||
SecItemImportExportKeyParameters? keyParams = null)
|
||||
{
|
||||
IntPtr keyParamsPtr = IntPtr.Zero;
|
||||
if (keyParams != null) {
|
||||
keyParamsPtr = Marshal.AllocHGlobal (Marshal.SizeOf (keyParams.Value));
|
||||
if (keyParamsPtr == IntPtr.Zero)
|
||||
throw new OutOfMemoryException ();
|
||||
Marshal.StructureToPtr (keyParams.Value, keyParamsPtr, false);
|
||||
}
|
||||
|
||||
IntPtr result;
|
||||
var status = SecItemImport (data.Handle, IntPtr.Zero, ref format, ref itemType, flags, keyParamsPtr, IntPtr.Zero, out result);
|
||||
|
||||
if (keyParamsPtr != IntPtr.Zero)
|
||||
Marshal.FreeHGlobal (keyParamsPtr);
|
||||
|
||||
if (status != SecStatusCode.Success)
|
||||
throw new NotSupportedException (status.ToString ());
|
||||
|
||||
return new CFArray (result, true);
|
||||
}
|
||||
|
||||
[DllImport (AppleTlsContext.SecurityLibrary)]
|
||||
extern static /* SecIdentityRef */ IntPtr SecIdentityCreate (
|
||||
/* CFAllocatorRef */ IntPtr allocator,
|
||||
/* SecCertificateRef */ IntPtr certificate,
|
||||
/* SecKeyRef */ IntPtr privateKey);
|
||||
|
||||
static public SecIdentity ItemImport (X509Certificate2 certificate)
|
||||
{
|
||||
if (!certificate.HasPrivateKey)
|
||||
throw new NotSupportedException ();
|
||||
|
||||
using (var key = ImportPrivateKey (certificate))
|
||||
using (var cert = new SecCertificate (certificate)) {
|
||||
var identity = SecIdentityCreate (IntPtr.Zero, cert.Handle, key.Handle);
|
||||
if (CFType.GetTypeID (identity) != SecIdentity.GetTypeID ())
|
||||
throw new InvalidOperationException ();
|
||||
|
||||
return new SecIdentity (identity, true);
|
||||
}
|
||||
}
|
||||
|
||||
static byte[] ExportKey (RSA key)
|
||||
{
|
||||
#if MONO_FEATURE_BTLS
|
||||
using (var btlsKey = MonoBtlsKey.CreateFromRSAPrivateKey (key))
|
||||
return btlsKey.GetBytes (true);
|
||||
#else
|
||||
return PKCS8.PrivateKeyInfo.Encode (key);
|
||||
#endif
|
||||
}
|
||||
|
||||
static SecKey ImportPrivateKey (X509Certificate2 certificate)
|
||||
{
|
||||
if (!certificate.HasPrivateKey)
|
||||
throw new NotSupportedException ();
|
||||
|
||||
CFArray items;
|
||||
using (var data = CFData.FromData (ExportKey ((RSA)certificate.PrivateKey)))
|
||||
items = ItemImport (data, SecExternalFormat.OpenSSL, SecExternalItemType.PrivateKey);
|
||||
|
||||
try {
|
||||
if (items.Count != 1)
|
||||
throw new InvalidOperationException ("Private key import failed.");
|
||||
|
||||
var imported = items[0];
|
||||
if (CFType.GetTypeID (imported) != SecKey.GetTypeID ())
|
||||
throw new InvalidOperationException ("Private key import doesn't return SecKey.");
|
||||
|
||||
return new SecKey (imported, items.Handle);
|
||||
} finally {
|
||||
items.Dispose ();
|
||||
}
|
||||
}
|
||||
|
||||
const int SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION = 0;
|
||||
|
||||
// Native enum; don't change.
|
||||
enum SecExternalFormat : int {
|
||||
Unknown = 0,
|
||||
OpenSSL = 1,
|
||||
X509Cert = 9,
|
||||
PEMSequence = 10,
|
||||
PKCS7 = 11,
|
||||
PKCS12 = 12
|
||||
}
|
||||
|
||||
// Native enum; don't change.
|
||||
enum SecExternalItemType : int {
|
||||
Unknown = 0,
|
||||
PrivateKey = 1,
|
||||
PublicKey = 2,
|
||||
SessionKey = 3,
|
||||
Certificate = 4,
|
||||
Aggregate = 5
|
||||
}
|
||||
|
||||
// Native enum; don't change
|
||||
enum SecItemImportExportFlags : int {
|
||||
None,
|
||||
PemArmour = 0x00000001, /* exported blob is PEM formatted */
|
||||
}
|
||||
|
||||
// Native struct; don't change
|
||||
[StructLayout (LayoutKind.Sequential)]
|
||||
struct SecItemImportExportKeyParameters {
|
||||
public int version; /* SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION */
|
||||
public int flags; /* SecKeyImportExportFlags bits */
|
||||
public IntPtr passphrase; /* SecExternalFormat.PKCS12 only. Legal types are CFStringRef and CFDataRef. */
|
||||
|
||||
IntPtr alertTitle;
|
||||
IntPtr alertPrompt;
|
||||
|
||||
public IntPtr accessRef; /* SecAccessRef */
|
||||
|
||||
IntPtr keyUsage;
|
||||
IntPtr keyAttributes;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,356 @@
|
||||
#if SECURITY_DEP && MONO_FEATURE_APPLETLS
|
||||
//
|
||||
// Items.cs: Implements the KeyChain query access APIs
|
||||
//
|
||||
// We use strong types and a helper SecQuery class to simplify the
|
||||
// creation of the dictionary used to query the Keychain
|
||||
//
|
||||
// Authors:
|
||||
// Miguel de Icaza
|
||||
// Sebastien Pouliot
|
||||
//
|
||||
// Copyright 2010 Novell, Inc
|
||||
// Copyright 2011-2016 Xamarin Inc
|
||||
//
|
||||
// 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.Collections;
|
||||
using System.Runtime.InteropServices;
|
||||
using ObjCRuntime;
|
||||
using Mono.Net;
|
||||
|
||||
namespace Mono.AppleTls {
|
||||
|
||||
enum SecKind {
|
||||
Identity,
|
||||
Certificate
|
||||
}
|
||||
|
||||
#if MONOTOUCH
|
||||
static class SecKeyChain {
|
||||
#else
|
||||
class SecKeyChain : INativeObject, IDisposable {
|
||||
#endif
|
||||
internal static readonly IntPtr MatchLimitAll;
|
||||
internal static readonly IntPtr MatchLimitOne;
|
||||
internal static readonly IntPtr MatchLimit;
|
||||
|
||||
#if !MONOTOUCH
|
||||
IntPtr handle;
|
||||
|
||||
internal SecKeyChain (IntPtr handle, bool owns = false)
|
||||
{
|
||||
if (handle == IntPtr.Zero)
|
||||
throw new ArgumentException ("Invalid handle");
|
||||
|
||||
this.handle = handle;
|
||||
if (!owns)
|
||||
CFObject.CFRetain (handle);
|
||||
}
|
||||
#endif
|
||||
|
||||
static SecKeyChain ()
|
||||
{
|
||||
var handle = CFObject.dlopen (AppleTlsContext.SecurityLibrary, 0);
|
||||
if (handle == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
try {
|
||||
MatchLimit = CFObject.GetIntPtr (handle, "kSecMatchLimit");
|
||||
MatchLimitAll = CFObject.GetIntPtr (handle, "kSecMatchLimitAll");
|
||||
MatchLimitOne = CFObject.GetIntPtr (handle, "kSecMatchLimitOne");
|
||||
} finally {
|
||||
CFObject.dlclose (handle);
|
||||
}
|
||||
}
|
||||
|
||||
public static SecIdentity FindIdentity (SecCertificate certificate, bool throwOnError = false)
|
||||
{
|
||||
if (certificate == null)
|
||||
throw new ArgumentNullException ("certificate");
|
||||
var identity = FindIdentity (cert => SecCertificate.Equals (certificate, cert));
|
||||
if (!throwOnError || identity != null)
|
||||
return identity;
|
||||
|
||||
throw new InvalidOperationException (string.Format ("Could not find SecIdentity for certificate '{0}' in keychain.", certificate.SubjectSummary));
|
||||
}
|
||||
|
||||
static SecIdentity FindIdentity (Predicate<SecCertificate> filter)
|
||||
{
|
||||
/*
|
||||
* Unfortunately, SecItemCopyMatching() does not allow any search
|
||||
* filters when looking up an identity.
|
||||
*
|
||||
* The following lookup will return all identities from the keychain -
|
||||
* we then need need to find the right one.
|
||||
*/
|
||||
using (var record = new SecRecord (SecKind.Identity)) {
|
||||
SecStatusCode status;
|
||||
var result = SecKeyChain.QueryAsReference (record, -1, out status);
|
||||
if (status != SecStatusCode.Success || result == null)
|
||||
return null;
|
||||
|
||||
for (int i = 0; i < result.Length; i++) {
|
||||
var identity = (SecIdentity)result [i];
|
||||
if (filter (identity.Certificate))
|
||||
return identity;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
static INativeObject [] QueryAsReference (SecRecord query, int max, out SecStatusCode result)
|
||||
{
|
||||
if (query == null) {
|
||||
result = SecStatusCode.Param;
|
||||
return null;
|
||||
}
|
||||
|
||||
using (var copy = query.QueryDict.MutableCopy ()) {
|
||||
copy.SetValue (CFBoolean.True.Handle, SecItem.ReturnRef);
|
||||
SetLimit (copy, max);
|
||||
return QueryAsReference (copy, out result);
|
||||
}
|
||||
}
|
||||
|
||||
static INativeObject [] QueryAsReference (CFDictionary query, out SecStatusCode result)
|
||||
{
|
||||
if (query == null) {
|
||||
result = SecStatusCode.Param;
|
||||
return null;
|
||||
}
|
||||
|
||||
IntPtr ptr;
|
||||
result = SecItem.SecItemCopyMatching (query.Handle, out ptr);
|
||||
if (result == SecStatusCode.Success && ptr != IntPtr.Zero) {
|
||||
var array = CFArray.ArrayFromHandle<INativeObject> (ptr, p => {
|
||||
IntPtr cfType = CFType.GetTypeID (p);
|
||||
if (cfType == SecCertificate.GetTypeID ())
|
||||
return new SecCertificate (p, true);
|
||||
if (cfType == SecKey.GetTypeID ())
|
||||
return new SecKey (p, true);
|
||||
if (cfType == SecIdentity.GetTypeID ())
|
||||
return new SecIdentity (p, true);
|
||||
throw new Exception (String.Format ("Unexpected type: 0x{0:x}", cfType));
|
||||
});
|
||||
return array;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
internal static CFNumber SetLimit (CFMutableDictionary dict, int max)
|
||||
{
|
||||
CFNumber n = null;
|
||||
IntPtr val;
|
||||
if (max == -1)
|
||||
val = MatchLimitAll;
|
||||
else if (max == 1)
|
||||
val = MatchLimitOne;
|
||||
else {
|
||||
n = CFNumber.FromInt32 (max);
|
||||
val = n.Handle;
|
||||
}
|
||||
|
||||
dict.SetValue (val, SecKeyChain.MatchLimit);
|
||||
return n;
|
||||
}
|
||||
|
||||
#if !MONOTOUCH
|
||||
[DllImport (AppleTlsContext.SecurityLibrary)]
|
||||
extern static /* OSStatus */ SecStatusCode SecKeychainCreate (/* const char * */ IntPtr pathName, uint passwordLength, /* const void * */ IntPtr password,
|
||||
bool promptUser, /* SecAccessRef */ IntPtr initialAccess,
|
||||
/* SecKeychainRef _Nullable * */ out IntPtr keychain);
|
||||
|
||||
internal static SecKeyChain Create (string pathName, string password)
|
||||
{
|
||||
IntPtr handle;
|
||||
var pathNamePtr = Marshal.StringToHGlobalAnsi (pathName);
|
||||
var passwordPtr = Marshal.StringToHGlobalAnsi (password);
|
||||
var result = SecKeychainCreate (pathNamePtr, (uint)password.Length, passwordPtr, false, IntPtr.Zero, out handle);
|
||||
if (result != SecStatusCode.Success)
|
||||
throw new InvalidOperationException (result.ToString ());
|
||||
return new SecKeyChain (handle, true);
|
||||
}
|
||||
|
||||
[DllImport (AppleTlsContext.SecurityLibrary)]
|
||||
extern static /* OSStatus */ SecStatusCode SecKeychainOpen (/* const char * */ IntPtr pathName, /* SecKeychainRef _Nullable * */ out IntPtr keychain);
|
||||
|
||||
internal static SecKeyChain Open (string pathName)
|
||||
{
|
||||
IntPtr handle;
|
||||
IntPtr pathNamePtr = IntPtr.Zero;
|
||||
try {
|
||||
pathNamePtr = Marshal.StringToHGlobalAnsi (pathName);
|
||||
var result = SecKeychainOpen (pathNamePtr, out handle);
|
||||
if (result != SecStatusCode.Success)
|
||||
throw new InvalidOperationException (result.ToString ());
|
||||
return new SecKeyChain (handle, true);
|
||||
} finally {
|
||||
if (pathNamePtr != IntPtr.Zero)
|
||||
Marshal.FreeHGlobal (pathNamePtr);
|
||||
}
|
||||
}
|
||||
|
||||
internal static SecKeyChain OpenSystemRootCertificates ()
|
||||
{
|
||||
return Open ("/System/Library/Keychains/SystemRootCertificates.keychain");
|
||||
}
|
||||
|
||||
~SecKeyChain ()
|
||||
{
|
||||
Dispose (false);
|
||||
}
|
||||
|
||||
public IntPtr Handle {
|
||||
get {
|
||||
return handle;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose ()
|
||||
{
|
||||
Dispose (true);
|
||||
GC.SuppressFinalize (this);
|
||||
}
|
||||
|
||||
protected virtual void Dispose (bool disposing)
|
||||
{
|
||||
if (handle != IntPtr.Zero) {
|
||||
CFObject.CFRelease (handle);
|
||||
handle = IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
class SecRecord : IDisposable {
|
||||
|
||||
internal static readonly IntPtr SecClassKey;
|
||||
static SecRecord ()
|
||||
{
|
||||
var handle = CFObject.dlopen (AppleTlsContext.SecurityLibrary, 0);
|
||||
if (handle == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
try {
|
||||
SecClassKey = CFObject.GetIntPtr (handle, "kSecClass");
|
||||
} finally {
|
||||
CFObject.dlclose (handle);
|
||||
}
|
||||
}
|
||||
|
||||
CFMutableDictionary _queryDict;
|
||||
internal CFMutableDictionary QueryDict {
|
||||
get {
|
||||
return _queryDict;
|
||||
}
|
||||
}
|
||||
|
||||
internal void SetValue (IntPtr key, IntPtr value)
|
||||
{
|
||||
_queryDict.SetValue (key, value);
|
||||
}
|
||||
|
||||
public SecRecord (SecKind secKind)
|
||||
{
|
||||
var kind = SecClass.FromSecKind (secKind);
|
||||
_queryDict = CFMutableDictionary.Create ();
|
||||
_queryDict.SetValue (SecClassKey, kind);
|
||||
}
|
||||
|
||||
public void Dispose ()
|
||||
{
|
||||
Dispose (true);
|
||||
GC.SuppressFinalize (this);
|
||||
}
|
||||
|
||||
protected virtual void Dispose (bool disposing)
|
||||
{
|
||||
if (_queryDict != null){
|
||||
if (disposing){
|
||||
_queryDict.Dispose ();
|
||||
_queryDict = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
~SecRecord ()
|
||||
{
|
||||
Dispose (false);
|
||||
}
|
||||
}
|
||||
|
||||
partial class SecItem {
|
||||
public static readonly IntPtr ReturnRef;
|
||||
public static readonly IntPtr MatchSearchList;
|
||||
|
||||
static SecItem ()
|
||||
{
|
||||
var handle = CFObject.dlopen (AppleTlsContext.SecurityLibrary, 0);
|
||||
if (handle == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
try {
|
||||
ReturnRef = CFObject.GetIntPtr (handle, "kSecReturnRef");
|
||||
MatchSearchList = CFObject.GetIntPtr (handle, "kSecMatchSearchList");
|
||||
} finally {
|
||||
CFObject.dlclose (handle);
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport (AppleTlsContext.SecurityLibrary)]
|
||||
internal extern static SecStatusCode SecItemCopyMatching (/* CFDictionaryRef */ IntPtr query, /* CFTypeRef* */ out IntPtr result);
|
||||
}
|
||||
|
||||
static partial class SecClass {
|
||||
|
||||
public static readonly IntPtr Identity;
|
||||
public static readonly IntPtr Certificate;
|
||||
|
||||
static SecClass ()
|
||||
{
|
||||
var handle = CFObject.dlopen (AppleTlsContext.SecurityLibrary, 0);
|
||||
if (handle == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
try {
|
||||
Identity = CFObject.GetIntPtr (handle, "kSecClassIdentity");
|
||||
Certificate = CFObject.GetIntPtr (handle, "kSecClassCertificate");
|
||||
} finally {
|
||||
CFObject.dlclose (handle);
|
||||
}
|
||||
}
|
||||
|
||||
public static IntPtr FromSecKind (SecKind secKind)
|
||||
{
|
||||
switch (secKind){
|
||||
case SecKind.Identity:
|
||||
return Identity;
|
||||
case SecKind.Certificate:
|
||||
return Certificate;
|
||||
default:
|
||||
throw new ArgumentException ("secKind");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,87 @@
|
||||
#if SECURITY_DEP && MONO_FEATURE_APPLETLS
|
||||
//
|
||||
// Policy.cs: Implements the managed SecPolicy wrapper.
|
||||
//
|
||||
// Authors:
|
||||
// Miguel de Icaza
|
||||
// Sebastien Pouliot <[email protected]>
|
||||
//
|
||||
// Copyright 2010 Novell, Inc
|
||||
// Copyright 2012-2014 Xamarin Inc.
|
||||
//
|
||||
// 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.Runtime.InteropServices;
|
||||
using ObjCRuntime;
|
||||
using Mono.Net;
|
||||
|
||||
namespace Mono.AppleTls {
|
||||
partial class SecPolicy : INativeObject, IDisposable {
|
||||
IntPtr handle;
|
||||
|
||||
internal SecPolicy (IntPtr handle, bool owns = false)
|
||||
{
|
||||
if (handle == IntPtr.Zero)
|
||||
throw new Exception ("Invalid handle");
|
||||
|
||||
this.handle = handle;
|
||||
if (!owns)
|
||||
CFObject.CFRetain (handle);
|
||||
}
|
||||
|
||||
[DllImport (AppleTlsContext.SecurityLibrary)]
|
||||
extern static IntPtr /* SecPolicyRef */ SecPolicyCreateSSL (bool server, IntPtr /* CFStringRef */ hostname);
|
||||
|
||||
static public SecPolicy CreateSslPolicy (bool server, string hostName)
|
||||
{
|
||||
CFString host = hostName == null ? null : CFString.Create (hostName);
|
||||
IntPtr handle = host == null ? IntPtr.Zero : host.Handle;
|
||||
SecPolicy policy = new SecPolicy (SecPolicyCreateSSL (server, handle), true);
|
||||
if (host != null)
|
||||
host.Dispose ();
|
||||
return policy;
|
||||
}
|
||||
|
||||
~SecPolicy ()
|
||||
{
|
||||
Dispose (false);
|
||||
}
|
||||
|
||||
public void Dispose ()
|
||||
{
|
||||
Dispose (true);
|
||||
GC.SuppressFinalize (this);
|
||||
}
|
||||
|
||||
public IntPtr Handle {
|
||||
get { return handle; }
|
||||
}
|
||||
|
||||
protected virtual void Dispose (bool disposing)
|
||||
{
|
||||
if (handle != IntPtr.Zero){
|
||||
CFObject.CFRelease (handle);
|
||||
handle = IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,251 @@
|
||||
#if MONO_FEATURE_APPLETLS
|
||||
// Copyright 2014 Xamarin Inc. All rights reserved.
|
||||
|
||||
namespace Mono.AppleTls {
|
||||
|
||||
// Security.framework/Headers/SecureTransport.h
|
||||
// untyped enum
|
||||
enum SslProtocol {
|
||||
Unknown = 0,
|
||||
// Ssl_3_0 = 2,
|
||||
Tls_1_0 = 4,
|
||||
Tls_1_1 = 7,
|
||||
Tls_1_2 = 8,
|
||||
// Dtls_1_0 = 9,
|
||||
|
||||
/* Obsolete on iOS */
|
||||
// Ssl_2_0 = 1,
|
||||
// Ssl_3_0_only = 3,
|
||||
// Tls_1_0_only = 5,
|
||||
// All = 6,
|
||||
}
|
||||
|
||||
// subset of OSStatus (int)
|
||||
enum SslStatus {
|
||||
Success = 0, // errSecSuccess in SecBase.h
|
||||
Protocol = -9800,
|
||||
Negotiation = -9801,
|
||||
FatalAlert = -9802,
|
||||
WouldBlock = -9803,
|
||||
SessionNotFound = -9804,
|
||||
ClosedGraceful = -9805,
|
||||
ClosedAbort = -9806,
|
||||
XCertChainInvalid = -9807,
|
||||
BadCert = -9808,
|
||||
Crypto = -9809,
|
||||
Internal = -9810,
|
||||
ModuleAttach = -9811,
|
||||
UnknownRootCert = -9812,
|
||||
NoRootCert = -9813,
|
||||
CertExpired = -9814,
|
||||
CertNotYetValid = -9815,
|
||||
ClosedNotNotified = -9816,
|
||||
BufferOverflow = -9817,
|
||||
BadCipherSuite = -9818,
|
||||
PeerUnexpectedMsg = -9819,
|
||||
PeerBadRecordMac = -9820,
|
||||
PeerDecryptionFail = -9821,
|
||||
PeerRecordOverflow = -9822,
|
||||
PeerDecompressFail = -9823,
|
||||
PeerHandshakeFail = -9824,
|
||||
PeerBadCert = -9825,
|
||||
PeerUnsupportedCert = -9826,
|
||||
PeerCertRevoked = -9827,
|
||||
PeerCertExpired = -9828,
|
||||
PeerCertUnknown = -9829,
|
||||
IllegalParam = -9830,
|
||||
PeerUnknownCA = -9831,
|
||||
PeerAccessDenied = -9832,
|
||||
PeerDecodeError = -9833,
|
||||
PeerDecryptError = -9834,
|
||||
PeerExportRestriction = -9835,
|
||||
PeerProtocolVersion = -9836,
|
||||
PeerInsufficientSecurity = -9837,
|
||||
PeerInternalError = -9838,
|
||||
PeerUserCancelled = -9839,
|
||||
PeerNoRenegotiation = -9840,
|
||||
PeerAuthCompleted = -9841, // non fatal
|
||||
PeerClientCertRequested = -9842, // non fatal
|
||||
HostNameMismatch = -9843,
|
||||
ConnectionRefused = -9844,
|
||||
DecryptionFail = -9845,
|
||||
BadRecordMac = -9846,
|
||||
RecordOverflow = -9847,
|
||||
BadConfiguration = -9848,
|
||||
UnexpectedRecord = -9849,
|
||||
SSLWeakPeerEphemeralDHKey = -9850,
|
||||
SSLClientHelloReceived = -9851 // non falta
|
||||
}
|
||||
|
||||
// Security.framework/Headers/SecureTransport.h
|
||||
// untyped enum
|
||||
enum SslSessionOption {
|
||||
BreakOnServerAuth,
|
||||
BreakOnCertRequested,
|
||||
BreakOnClientAuth,
|
||||
|
||||
// FalseStart,
|
||||
|
||||
// SendOneByteRecord,
|
||||
|
||||
// AllowServerIdentityChange = 5,
|
||||
|
||||
// Fallback = 6,
|
||||
|
||||
// BreakOnClientHello = 7,
|
||||
|
||||
// AllowRenegotiation = 8,
|
||||
}
|
||||
|
||||
// Security.framework/Headers/SecureTransport.h
|
||||
// untyped enum
|
||||
enum SslAuthenticate {
|
||||
// Never,
|
||||
// Always,
|
||||
Try = 2,
|
||||
}
|
||||
|
||||
// Security.framework/Headers/SecureTransport.h
|
||||
// untyped enum
|
||||
enum SslProtocolSide {
|
||||
Server,
|
||||
Client,
|
||||
}
|
||||
|
||||
// Security.framework/Headers/SecureTransport.h
|
||||
// untyped enum
|
||||
enum SslConnectionType {
|
||||
Stream,
|
||||
// Datagram
|
||||
}
|
||||
|
||||
// Security.framework/Headers/SecureTransport.h
|
||||
// untyped enum
|
||||
enum SslSessionState {
|
||||
Invalid = -1,
|
||||
// Idle,
|
||||
// Handshake,
|
||||
// Connected,
|
||||
// Closed,
|
||||
// Aborted
|
||||
}
|
||||
|
||||
// Security.framework/Headers/SecureTransport.h
|
||||
// untyped enum
|
||||
enum SslClientCertificateState {
|
||||
None,
|
||||
Requested,
|
||||
Sent,
|
||||
Rejected
|
||||
}
|
||||
|
||||
// Security.framework/Headers/CipherSuite.h
|
||||
// 32 bits (uint32_t) on OSX, 16 bits (uint16_t) on iOS
|
||||
#if XAMMAC || XAMMAC_4_5
|
||||
enum SslCipherSuite : uint {
|
||||
#else
|
||||
enum SslCipherSuite : ushort {
|
||||
#endif
|
||||
// DO NOT RENAME VALUES - they don't look good but we need them to keep compatibility with our System.dll code
|
||||
// it's how it's defined across most SSL/TLS implementation (from RFC)
|
||||
|
||||
SSL_NULL_WITH_NULL_NULL = 0x0000, // value used before (not after) negotiation
|
||||
TLS_NULL_WITH_NULL_NULL = 0x0000,
|
||||
|
||||
// Not the whole list (too much unneeed metadata) but only what's supported
|
||||
// FIXME needs to be expended with OSX 10.9
|
||||
|
||||
SSL_RSA_WITH_NULL_MD5 = 0x0001,
|
||||
SSL_RSA_WITH_NULL_SHA = 0x0002,
|
||||
SSL_RSA_EXPORT_WITH_RC4_40_MD5 = 0x0003, // iOS 5.1 only
|
||||
SSL_RSA_WITH_RC4_128_MD5 = 0x0004,
|
||||
SSL_RSA_WITH_RC4_128_SHA = 0x0005,
|
||||
SSL_RSA_WITH_3DES_EDE_CBC_SHA = 0x000A,
|
||||
SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA = 0x0016,
|
||||
SSL_DH_anon_EXPORT_WITH_RC4_40_MD5 = 0x0017, // iOS 5.1 only
|
||||
SSL_DH_anon_WITH_RC4_128_MD5 = 0x0018,
|
||||
SSL_DH_anon_WITH_3DES_EDE_CBC_SHA = 0x001B,
|
||||
|
||||
// TLS - identical values to SSL (above)
|
||||
|
||||
TLS_RSA_WITH_NULL_MD5 = 0x0001,
|
||||
TLS_RSA_WITH_NULL_SHA = 0x0002,
|
||||
TLS_RSA_WITH_RC4_128_MD5 = 0x0004,
|
||||
TLS_RSA_WITH_RC4_128_SHA = 0x0005,
|
||||
TLS_RSA_WITH_3DES_EDE_CBC_SHA = 0x000A,
|
||||
TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = 0x0016,
|
||||
TLS_DH_anon_WITH_RC4_128_MD5 = 0x0018,
|
||||
TLS_DH_anon_WITH_3DES_EDE_CBC_SHA = 0x001B,
|
||||
|
||||
// TLS specific
|
||||
|
||||
TLS_PSK_WITH_NULL_SHA = 0x002C,
|
||||
TLS_RSA_WITH_AES_128_CBC_SHA = 0x002F,
|
||||
TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x0033,
|
||||
TLS_DH_anon_WITH_AES_128_CBC_SHA = 0x0034,
|
||||
TLS_RSA_WITH_AES_256_CBC_SHA = 0x0035,
|
||||
TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x0039,
|
||||
TLS_DH_anon_WITH_AES_256_CBC_SHA = 0x003A,
|
||||
TLS_RSA_WITH_NULL_SHA256 = 0x003B,
|
||||
TLS_RSA_WITH_AES_128_CBC_SHA256 = 0x003C,
|
||||
TLS_RSA_WITH_AES_256_CBC_SHA256 = 0x003D,
|
||||
TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x0067,
|
||||
TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x006B,
|
||||
TLS_DH_anon_WITH_AES_128_CBC_SHA256 = 0x006C,
|
||||
TLS_DH_anon_WITH_AES_256_CBC_SHA256 = 0x006D,
|
||||
TLS_PSK_WITH_RC4_128_SHA = 0x008A,
|
||||
TLS_PSK_WITH_3DES_EDE_CBC_SHA = 0x008B,
|
||||
TLS_PSK_WITH_AES_128_CBC_SHA = 0x008C,
|
||||
TLS_PSK_WITH_AES_256_CBC_SHA = 0x008D,
|
||||
|
||||
TLS_RSA_WITH_AES_128_GCM_SHA256 = 0x009C, // iOS 9+
|
||||
TLS_RSA_WITH_AES_256_GCM_SHA384 = 0x009D, // iOS 9+
|
||||
TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 = 0x009E, // iOS 9+
|
||||
TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 = 0x009F, // iOS 9+
|
||||
|
||||
TLS_DH_anon_WITH_AES_128_GCM_SHA256 = 0x00A6, // iOS 5.1 only
|
||||
TLS_DH_anon_WITH_AES_256_GCM_SHA384 = 0x00A7, // iOS 5.1 only
|
||||
TLS_PSK_WITH_AES_128_CBC_SHA256 = 0x00AE,
|
||||
TLS_PSK_WITH_AES_256_CBC_SHA384 = 0x00AF,
|
||||
TLS_PSK_WITH_NULL_SHA256 = 0x00B0,
|
||||
TLS_PSK_WITH_NULL_SHA384 = 0x00B1,
|
||||
TLS_ECDH_ECDSA_WITH_NULL_SHA = 0xC001,
|
||||
TLS_ECDH_ECDSA_WITH_RC4_128_SHA = 0xC002,
|
||||
TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA = 0xC003,
|
||||
TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA = 0xC004,
|
||||
TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA = 0xC005,
|
||||
TLS_ECDHE_ECDSA_WITH_NULL_SHA = 0xC006,
|
||||
TLS_ECDHE_ECDSA_WITH_RC4_128_SHA = 0xC007,
|
||||
TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA = 0xC008,
|
||||
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = 0xC009,
|
||||
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = 0xC00A,
|
||||
TLS_ECDH_RSA_WITH_NULL_SHA = 0xC00B,
|
||||
TLS_ECDH_RSA_WITH_RC4_128_SHA = 0xC00C,
|
||||
TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA = 0xC00D,
|
||||
TLS_ECDH_RSA_WITH_AES_128_CBC_SHA = 0xC00E,
|
||||
TLS_ECDH_RSA_WITH_AES_256_CBC_SHA = 0xC00F,
|
||||
TLS_ECDHE_RSA_WITH_NULL_SHA = 0xC010,
|
||||
TLS_ECDHE_RSA_WITH_RC4_128_SHA = 0xC011,
|
||||
TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA = 0xC012,
|
||||
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = 0xC013,
|
||||
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = 0xC014,
|
||||
TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = 0xC023,
|
||||
TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = 0xC024,
|
||||
TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 = 0xC025,
|
||||
TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 = 0xC026,
|
||||
TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 = 0xC027,
|
||||
TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 = 0xC028,
|
||||
TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 = 0xC029,
|
||||
TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 = 0xC02A,
|
||||
|
||||
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02B, // iOS 9+
|
||||
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02C, // iOS 9+
|
||||
TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02D, // iOS 9+
|
||||
TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02E, // iOS 9+
|
||||
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = 0xC02F, // iOS 9+
|
||||
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = 0xC030, // iOS 9+
|
||||
TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 = 0xC031, // iOS 9+
|
||||
TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 = 0xC032, // iOS 9+
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,18 @@
|
||||
#if MONO_FEATURE_APPLETLS
|
||||
//
|
||||
// SslConnection
|
||||
//
|
||||
// Authors:
|
||||
// Sebastien Pouliot <[email protected]>
|
||||
//
|
||||
// Copyright 2014 Xamarin Inc.
|
||||
//
|
||||
|
||||
using System;
|
||||
|
||||
namespace Mono.AppleTls
|
||||
{
|
||||
delegate SslStatus SslReadFunc (IntPtr connection, IntPtr data, /* size_t* */ ref IntPtr dataLength);
|
||||
delegate SslStatus SslWriteFunc (IntPtr connection, IntPtr data, /* size_t* */ ref IntPtr dataLength);
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,186 @@
|
||||
#if SECURITY_DEP && MONO_FEATURE_APPLETLS
|
||||
//
|
||||
// Trust.cs: Implements the managed SecTrust wrapper.
|
||||
//
|
||||
// Authors:
|
||||
// Miguel de Icaza
|
||||
// Sebastien Pouliot <[email protected]>
|
||||
//
|
||||
// Copyright 2010 Novell, Inc
|
||||
// Copyright 2012-2014 Xamarin Inc.
|
||||
//
|
||||
// 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.Runtime.InteropServices;
|
||||
using System.Security;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using ObjCRuntime;
|
||||
using Mono.Net;
|
||||
|
||||
namespace Mono.AppleTls {
|
||||
partial class SecTrust : INativeObject, IDisposable {
|
||||
IntPtr handle;
|
||||
|
||||
internal SecTrust (IntPtr handle, bool owns = false)
|
||||
{
|
||||
if (handle == IntPtr.Zero)
|
||||
throw new Exception ("Invalid handle");
|
||||
|
||||
this.handle = handle;
|
||||
if (!owns)
|
||||
CFObject.CFRetain (handle);
|
||||
}
|
||||
|
||||
[DllImport (AppleTlsContext.SecurityLibrary)]
|
||||
extern static SecStatusCode SecTrustCreateWithCertificates (
|
||||
/* CFTypeRef */ IntPtr certOrCertArray,
|
||||
/* CFTypeRef __nullable */ IntPtr policies,
|
||||
/* SecTrustRef *__nonull */ out IntPtr sectrustref);
|
||||
|
||||
|
||||
public SecTrust (X509CertificateCollection certificates, SecPolicy policy)
|
||||
{
|
||||
if (certificates == null)
|
||||
throw new ArgumentNullException ("certificates");
|
||||
|
||||
SecCertificate[] array = new SecCertificate [certificates.Count];
|
||||
int i = 0;
|
||||
foreach (var certificate in certificates)
|
||||
array [i++] = new SecCertificate (certificate);
|
||||
Initialize (array, policy);
|
||||
}
|
||||
|
||||
void Initialize (SecCertificate[] array, SecPolicy policy)
|
||||
{
|
||||
using (var certs = CFArray.CreateArray (array)) {
|
||||
Initialize (certs.Handle, policy);
|
||||
}
|
||||
}
|
||||
|
||||
void Initialize (IntPtr certHandle, SecPolicy policy)
|
||||
{
|
||||
SecStatusCode result = SecTrustCreateWithCertificates (certHandle, policy == null ? IntPtr.Zero : policy.Handle, out handle);
|
||||
if (result != SecStatusCode.Success)
|
||||
throw new ArgumentException (result.ToString ());
|
||||
}
|
||||
|
||||
[DllImport (AppleTlsContext.SecurityLibrary)]
|
||||
extern static SecStatusCode /* OSStatus */ SecTrustEvaluate (IntPtr /* SecTrustRef */ trust, out /* SecTrustResultType */ SecTrustResult result);
|
||||
|
||||
public SecTrustResult Evaluate ()
|
||||
{
|
||||
if (handle == IntPtr.Zero)
|
||||
throw new ObjectDisposedException ("SecTrust");
|
||||
|
||||
SecTrustResult trust;
|
||||
SecStatusCode result = SecTrustEvaluate (handle, out trust);
|
||||
if (result != SecStatusCode.Success)
|
||||
throw new InvalidOperationException (result.ToString ());
|
||||
return trust;
|
||||
}
|
||||
|
||||
[DllImport (AppleTlsContext.SecurityLibrary)]
|
||||
extern static IntPtr /* CFIndex */ SecTrustGetCertificateCount (IntPtr /* SecTrustRef */ trust);
|
||||
|
||||
public int Count {
|
||||
get {
|
||||
if (handle == IntPtr.Zero)
|
||||
return 0;
|
||||
return (int) SecTrustGetCertificateCount (handle);
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport (AppleTlsContext.SecurityLibrary)]
|
||||
extern static IntPtr /* SecCertificateRef */ SecTrustGetCertificateAtIndex (IntPtr /* SecTrustRef */ trust, IntPtr /* CFIndex */ ix);
|
||||
|
||||
public SecCertificate this [IntPtr index] {
|
||||
get {
|
||||
if (handle == IntPtr.Zero)
|
||||
throw new ObjectDisposedException ("SecTrust");
|
||||
if (((long)index < 0) || ((long)index >= Count))
|
||||
throw new ArgumentOutOfRangeException ("index");
|
||||
|
||||
return new SecCertificate (SecTrustGetCertificateAtIndex (handle, index));
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport (AppleTlsContext.SecurityLibrary)]
|
||||
extern static SecStatusCode /* OSStatus */ SecTrustSetAnchorCertificates (IntPtr /* SecTrustRef */ trust, IntPtr /* CFArrayRef */ anchorCertificates);
|
||||
|
||||
public SecStatusCode SetAnchorCertificates (X509CertificateCollection certificates)
|
||||
{
|
||||
if (handle == IntPtr.Zero)
|
||||
throw new ObjectDisposedException ("SecTrust");
|
||||
if (certificates == null)
|
||||
return SecTrustSetAnchorCertificates (handle, IntPtr.Zero);
|
||||
|
||||
SecCertificate[] array = new SecCertificate [certificates.Count];
|
||||
int i = 0;
|
||||
foreach (var certificate in certificates)
|
||||
array [i++] = new SecCertificate (certificate);
|
||||
return SetAnchorCertificates (array);
|
||||
}
|
||||
|
||||
public SecStatusCode SetAnchorCertificates (SecCertificate[] array)
|
||||
{
|
||||
if (array == null)
|
||||
return SecTrustSetAnchorCertificates (handle, IntPtr.Zero);
|
||||
using (var certs = CFArray.FromNativeObjects (array)) {
|
||||
return SecTrustSetAnchorCertificates (handle, certs.Handle);
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport (AppleTlsContext.SecurityLibrary)]
|
||||
extern static SecStatusCode /* OSStatus */ SecTrustSetAnchorCertificatesOnly (IntPtr /* SecTrustRef */ trust, bool anchorCertificatesOnly);
|
||||
|
||||
public SecStatusCode SetAnchorCertificatesOnly (bool anchorCertificatesOnly)
|
||||
{
|
||||
if (handle == IntPtr.Zero)
|
||||
throw new ObjectDisposedException ("SecTrust");
|
||||
|
||||
return SecTrustSetAnchorCertificatesOnly (handle, anchorCertificatesOnly);
|
||||
}
|
||||
|
||||
~SecTrust ()
|
||||
{
|
||||
Dispose (false);
|
||||
}
|
||||
|
||||
protected virtual void Dispose (bool disposing)
|
||||
{
|
||||
if (handle != IntPtr.Zero) {
|
||||
CFObject.CFRelease (handle);
|
||||
handle = IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose ()
|
||||
{
|
||||
Dispose (true);
|
||||
GC.SuppressFinalize (this);
|
||||
}
|
||||
|
||||
public IntPtr Handle {
|
||||
get { return handle; }
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -159,7 +159,7 @@ namespace Mono.Btls
|
||||
string file;
|
||||
int line;
|
||||
var error = MonoBtlsError.GetError (out file, out line);
|
||||
if (error == null)
|
||||
if (error == 0)
|
||||
return new MonoBtlsException (status);
|
||||
|
||||
var text = MonoBtlsError.GetErrorString (error);
|
||||
@@ -218,16 +218,6 @@ namespace Mono.Btls
|
||||
isAuthenticated = true;
|
||||
}
|
||||
|
||||
void SetupCertificateStore ()
|
||||
{
|
||||
MonoBtlsProvider.SetupCertificateStore (ctx.CertificateStore);
|
||||
|
||||
if (Settings != null && Settings.TrustAnchors != null) {
|
||||
var trust = IsServer ? MonoBtlsX509TrustKind.TRUST_CLIENT : MonoBtlsX509TrustKind.TRUST_SERVER;
|
||||
ctx.CertificateStore.AddCollection (Settings.TrustAnchors, trust);
|
||||
}
|
||||
}
|
||||
|
||||
void InitializeConnection ()
|
||||
{
|
||||
ctx = new MonoBtlsSslCtx ();
|
||||
@@ -237,7 +227,7 @@ namespace Mono.Btls
|
||||
ctx.SetDebugBio (errbio);
|
||||
#endif
|
||||
|
||||
SetupCertificateStore ();
|
||||
MonoBtlsProvider.SetupCertificateStore (ctx.CertificateStore, Settings, IsServer);
|
||||
|
||||
if (!IsServer || AskForClientCertificate)
|
||||
ctx.SetVerifyCallback (VerifyCallback, false);
|
||||
|
||||
@@ -150,7 +150,7 @@ namespace Mono.Btls
|
||||
using (var nativeChain = MonoBtlsProvider.GetNativeChain (certificates))
|
||||
using (var param = GetVerifyParam (targetHost, serverMode))
|
||||
using (var storeCtx = new MonoBtlsX509StoreCtx ()) {
|
||||
SetupCertificateStore (store);
|
||||
SetupCertificateStore (store, validator.Settings, serverMode);
|
||||
|
||||
storeCtx.Initialize (store, nativeChain);
|
||||
|
||||
@@ -201,19 +201,45 @@ namespace Mono.Btls
|
||||
}
|
||||
}
|
||||
|
||||
internal static void SetupCertificateStore (MonoBtlsX509Store store, MonoTlsSettings settings, bool server)
|
||||
{
|
||||
AddTrustedRoots (store, settings, server);
|
||||
SetupCertificateStore (store);
|
||||
}
|
||||
|
||||
internal static void SetupCertificateStore (MonoBtlsX509Store store)
|
||||
{
|
||||
#if MONODROID
|
||||
store.SetDefaultPaths ();
|
||||
store.AddAndroidLookup ();
|
||||
#else
|
||||
AddUserStore (store);
|
||||
AddMachineStore (store);
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !MONODROID
|
||||
static void AddUserStore (MonoBtlsX509Store store)
|
||||
{
|
||||
var userPath = MonoBtlsX509StoreManager.GetStorePath (MonoBtlsX509StoreType.UserTrustedRoots);
|
||||
if (Directory.Exists (userPath))
|
||||
store.AddDirectoryLookup (userPath, MonoBtlsX509FileType.PEM);
|
||||
}
|
||||
|
||||
static void AddMachineStore (MonoBtlsX509Store store)
|
||||
{
|
||||
var machinePath = MonoBtlsX509StoreManager.GetStorePath (MonoBtlsX509StoreType.MachineTrustedRoots);
|
||||
if (Directory.Exists (machinePath))
|
||||
store.AddDirectoryLookup (machinePath, MonoBtlsX509FileType.PEM);
|
||||
}
|
||||
#endif
|
||||
|
||||
static void AddTrustedRoots (MonoBtlsX509Store store, MonoTlsSettings settings, bool server)
|
||||
{
|
||||
if (settings?.TrustAnchors == null)
|
||||
return;
|
||||
var trust = server ? MonoBtlsX509TrustKind.TRUST_CLIENT : MonoBtlsX509TrustKind.TRUST_SERVER;
|
||||
store.AddCollection (settings.TrustAnchors, trust);
|
||||
}
|
||||
|
||||
public static string GetSystemStoreLocation ()
|
||||
|
||||
@@ -159,8 +159,7 @@ namespace Mono.Btls
|
||||
|
||||
internal void AddTrustedRoots ()
|
||||
{
|
||||
var systemRoot = MonoBtlsProvider.GetSystemStoreLocation ();
|
||||
LoadLocations (null, systemRoot);
|
||||
MonoBtlsProvider.SetupCertificateStore (this);
|
||||
}
|
||||
|
||||
public MonoBtlsX509Lookup AddLookup (MonoBtlsX509LookupType type)
|
||||
|
||||
@@ -1,24 +1,146 @@
|
||||
// Copyright 2015 Xamarin Inc. All rights reserved.
|
||||
//
|
||||
// MonoTlsProviderFactory.cs
|
||||
//
|
||||
// Author:
|
||||
// Chris Hamons <[email protected]>
|
||||
// Martin Baulig <[email protected]>
|
||||
//
|
||||
// Copyright (c) 2015 Xamarin, Inc.
|
||||
//
|
||||
// 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.
|
||||
|
||||
#if !ONLY_APPLETLS
|
||||
#error Use MonoTlsProviderFactory.cs instead
|
||||
#endif
|
||||
|
||||
#if SECURITY_DEP
|
||||
|
||||
#if MONO_SECURITY_ALIAS
|
||||
extern alias MonoSecurity;
|
||||
using MSI = MonoSecurity::Mono.Security.Interface;
|
||||
using MX = MonoSecurity::Mono.Security.X509;
|
||||
#else
|
||||
using MSI = Mono.Security.Interface;
|
||||
using MX = Mono.Security.X509;
|
||||
#endif
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Mono.AppleTls;
|
||||
|
||||
#endif
|
||||
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace Mono.Net.Security
|
||||
{
|
||||
/*
|
||||
* Keep in sync with Mono.Security/Mono.Security.Interface/MonoTlsProvider.cs.
|
||||
* Simple implementation that does hard codes only a single provider
|
||||
*/
|
||||
static partial class MonoTlsProviderFactory
|
||||
{
|
||||
static MSI.MonoTlsProvider CreateDefaultProviderImpl ()
|
||||
#region Internal API
|
||||
|
||||
/*
|
||||
* APIs in this section are for consumption within System.dll only - do not access via
|
||||
* reflection or from friend assemblies.
|
||||
*
|
||||
* @IMonoTlsProvider is defined as empty interface outside 'SECURITY_DEP', so we don't need
|
||||
* this conditional here.
|
||||
*/
|
||||
|
||||
internal static IMonoTlsProvider GetProviderInternal ()
|
||||
{
|
||||
MSI.MonoTlsProvider provider = null;
|
||||
if (MSI.MonoTlsProviderFactory._PrivateFactoryDelegate != null)
|
||||
provider = MSI.MonoTlsProviderFactory._PrivateFactoryDelegate ();
|
||||
return provider;
|
||||
#if SECURITY_DEP
|
||||
return GetTlsProvider ();
|
||||
#else
|
||||
throw new NotSupportedException ("TLS Support not available.");
|
||||
#endif
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#if SECURITY_DEP
|
||||
static object locker = new object ();
|
||||
static IMonoTlsProvider provider;
|
||||
static IMonoTlsProvider GetTlsProvider ()
|
||||
{
|
||||
lock (locker) {
|
||||
if (provider == null)
|
||||
provider = new Private.MonoTlsProviderWrapper (new AppleTlsProvider ());
|
||||
return provider;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#region Mono.Security visible API
|
||||
|
||||
/*
|
||||
* "Public" section, intended to be consumed via reflection.
|
||||
*
|
||||
* Mono.Security.dll provides a public wrapper around these.
|
||||
*/
|
||||
|
||||
internal static MSI.MonoTlsProvider GetProvider ()
|
||||
{
|
||||
return GetTlsProvider ().Provider;
|
||||
}
|
||||
|
||||
internal static bool IsProviderSupported (string name)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
internal static MSI.MonoTlsProvider GetProvider (string name)
|
||||
{
|
||||
return GetTlsProvider ().Provider;
|
||||
}
|
||||
|
||||
internal static bool IsInitialized => true;
|
||||
|
||||
internal static void Initialize ()
|
||||
{
|
||||
}
|
||||
|
||||
internal static void Initialize (string provider)
|
||||
{
|
||||
}
|
||||
|
||||
internal static HttpWebRequest CreateHttpsRequest (Uri requestUri, MSI.MonoTlsProvider provider, MSI.MonoTlsSettings settings)
|
||||
{
|
||||
lock (locker) {
|
||||
var internalProvider = provider != null ? new Private.MonoTlsProviderWrapper (provider) : null;
|
||||
return new HttpWebRequest (requestUri, internalProvider, settings);
|
||||
}
|
||||
}
|
||||
|
||||
internal static HttpListener CreateHttpListener (X509Certificate certificate, MSI.MonoTlsProvider provider, MSI.MonoTlsSettings settings)
|
||||
{
|
||||
lock (locker) {
|
||||
var internalProvider = provider != null ? new Private.MonoTlsProviderWrapper (provider) : null;
|
||||
return new HttpListener (certificate, internalProvider, settings);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
#endif
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -24,6 +24,8 @@
|
||||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
// THE SOFTWARE.
|
||||
|
||||
#if !ONLY_APPLETLS // ONLY_APPLETLS uses MonoTlsProviderFactory.Apple.cs instead
|
||||
|
||||
#if SECURITY_DEP
|
||||
#if MONO_SECURITY_ALIAS
|
||||
extern alias MonoSecurity;
|
||||
@@ -159,10 +161,28 @@ namespace Mono.Net.Security
|
||||
if (providerRegistration != null)
|
||||
return;
|
||||
providerRegistration = new Dictionary<string,string> ();
|
||||
providerRegistration.Add ("legacy", "Mono.Net.Security.LegacyTlsProvider");
|
||||
providerRegistration.Add ("default", "Mono.Net.Security.LegacyTlsProvider");
|
||||
if (IsBtlsSupported ())
|
||||
providerRegistration.Add ("btls", "Mono.Btls.MonoBtlsProvider");
|
||||
|
||||
string legacyProvider = "Mono.Net.Security.LegacyTlsProvider";
|
||||
providerRegistration.Add ("legacy", legacyProvider);
|
||||
|
||||
string defaultProvider = null;
|
||||
if (IsBtlsSupported ()) {
|
||||
var btlsProvider = "Mono.Btls.MonoBtlsProvider";
|
||||
providerRegistration.Add ("btls", btlsProvider);
|
||||
defaultProvider = btlsProvider;
|
||||
}
|
||||
|
||||
if (Platform.IsMacOS) {
|
||||
var appleProvider = "Mono.AppleTls.AppleTlsProvider";
|
||||
providerRegistration.Add ("apple", appleProvider);
|
||||
defaultProvider = appleProvider;
|
||||
}
|
||||
|
||||
if (defaultProvider == null)
|
||||
defaultProvider = legacyProvider;
|
||||
|
||||
providerRegistration.Add ("default", defaultProvider);
|
||||
|
||||
X509Helper2.Initialize ();
|
||||
}
|
||||
}
|
||||
@@ -261,4 +281,4 @@ namespace Mono.Net.Security
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,16 @@
|
||||
#if MONOTOUCH
|
||||
|
||||
namespace MonoTouch
|
||||
{
|
||||
// Exists only not to break existing source code due to broken C# namespace rules
|
||||
// which allow using for empty namespace
|
||||
sealed class Dummy
|
||||
{
|
||||
private Dummy ()
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -485,6 +485,34 @@ namespace System.Diagnostics
|
||||
return (new Process (new SafeProcessHandle (proc, false), processId));
|
||||
}
|
||||
|
||||
public static Process[] GetProcessesByName(string processName, string machineName)
|
||||
{
|
||||
if (machineName == null)
|
||||
throw new ArgumentNullException ("machineName");
|
||||
|
||||
if (!IsLocalMachine (machineName))
|
||||
throw new NotImplementedException ();
|
||||
|
||||
Process[] processes = GetProcesses ();
|
||||
if (processes.Length == 0)
|
||||
return processes;
|
||||
|
||||
int size = 0;
|
||||
|
||||
for (int i = 0; i < processes.Length; i++) {
|
||||
try {
|
||||
if (String.Compare (processName, processes[i].ProcessName, true) == 0)
|
||||
processes [size++] = processes[i];
|
||||
} catch (SystemException) {
|
||||
/* The process might exit between GetProcesses_internal and GetProcessById */
|
||||
}
|
||||
}
|
||||
|
||||
Array.Resize<Process> (ref processes, size);
|
||||
|
||||
return processes;
|
||||
}
|
||||
|
||||
[MethodImplAttribute(MethodImplOptions.InternalCall)]
|
||||
private extern static int[] GetProcesses_internal();
|
||||
|
||||
|
||||
@@ -901,12 +901,11 @@ namespace System.Net.Sockets
|
||||
SocketAsyncResult ares;
|
||||
|
||||
if (!GetCheckedIPs (e, out addresses)) {
|
||||
e.socket_async_result.EndPoint = e.RemoteEndPoint;
|
||||
//NOTE: DualMode may cause Socket's RemoteEndpoint to differ in AddressFamily from the
|
||||
// SocketAsyncEventArgs, but the SocketAsyncEventArgs itself is not changed
|
||||
ares = (SocketAsyncResult) BeginConnect (e.RemoteEndPoint, ConnectAsyncCallback, e);
|
||||
} else {
|
||||
DnsEndPoint dep = (e.RemoteEndPoint as DnsEndPoint);
|
||||
e.socket_async_result.Addresses = addresses;
|
||||
e.socket_async_result.Port = dep.Port;
|
||||
DnsEndPoint dep = (DnsEndPoint)e.RemoteEndPoint;
|
||||
ares = (SocketAsyncResult) BeginConnect (addresses, dep.Port, ConnectAsyncCallback, e);
|
||||
}
|
||||
|
||||
@@ -984,8 +983,8 @@ namespace System.Net.Sockets
|
||||
sockares.Complete (new SocketException ((int) SocketError.AddressNotAvailable), true);
|
||||
return sockares;
|
||||
}
|
||||
|
||||
end_point = RemapIPEndPoint (ep);
|
||||
|
||||
sockares.EndPoint = end_point = RemapIPEndPoint (ep);
|
||||
}
|
||||
|
||||
int error = 0;
|
||||
|
||||
@@ -145,22 +145,33 @@ namespace System.Net.Sockets
|
||||
|
||||
IsCompleted = true;
|
||||
|
||||
/* It is possible that this.socket is modified by this.Init which has been called by the callback. This
|
||||
* would lead to inconsistency, as we would for example not release the correct socket.ReadSem or
|
||||
* socket.WriteSem.
|
||||
* For example, this can happen with AcceptAsync followed by a ReceiveAsync on the same
|
||||
* SocketAsyncEventArgs */
|
||||
Socket completedSocket = socket;
|
||||
SocketOperation completedOperation = operation;
|
||||
|
||||
AsyncCallback callback = AsyncCallback;
|
||||
if (callback != null) {
|
||||
ThreadPool.UnsafeQueueUserWorkItem (_ => callback (this), null);
|
||||
}
|
||||
|
||||
switch (operation) {
|
||||
/* Warning: any field on the current SocketAsyncResult might have changed, as the callback might have
|
||||
* called this.Init */
|
||||
|
||||
switch (completedOperation) {
|
||||
case SocketOperation.Receive:
|
||||
case SocketOperation.ReceiveFrom:
|
||||
case SocketOperation.ReceiveGeneric:
|
||||
case SocketOperation.Accept:
|
||||
socket.ReadSem.Release ();
|
||||
completedSocket.ReadSem.Release ();
|
||||
break;
|
||||
case SocketOperation.Send:
|
||||
case SocketOperation.SendTo:
|
||||
case SocketOperation.SendGeneric:
|
||||
socket.WriteSem.Release ();
|
||||
completedSocket.WriteSem.Release ();
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
@@ -29,10 +29,16 @@ using System.Net;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using ObjCRuntime;
|
||||
|
||||
namespace Mono.Net
|
||||
{
|
||||
internal class CFObject : IDisposable
|
||||
internal class CFType {
|
||||
[DllImport (CFObject.CoreFoundationLibrary, EntryPoint="CFGetTypeID")]
|
||||
public static extern IntPtr GetTypeID (IntPtr typeRef);
|
||||
}
|
||||
|
||||
internal class CFObject : IDisposable, INativeObject
|
||||
{
|
||||
public const string CoreFoundationLibrary = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation";
|
||||
const string SystemLibrary = "/usr/lib/libSystem.dylib";
|
||||
@@ -41,7 +47,7 @@ namespace Mono.Net
|
||||
public static extern IntPtr dlopen (string path, int mode);
|
||||
|
||||
[DllImport (SystemLibrary)]
|
||||
public static extern IntPtr dlsym (IntPtr handle, string symbol);
|
||||
static extern IntPtr dlsym (IntPtr handle, string symbol);
|
||||
|
||||
[DllImport (SystemLibrary)]
|
||||
public static extern void dlclose (IntPtr handle);
|
||||
@@ -51,6 +57,25 @@ namespace Mono.Net
|
||||
return dlsym (handle, symbol);
|
||||
}
|
||||
|
||||
public static CFString GetStringConstant (IntPtr handle, string symbol)
|
||||
{
|
||||
var indirect = dlsym (handle, symbol);
|
||||
if (indirect == IntPtr.Zero)
|
||||
return null;
|
||||
var actual = Marshal.ReadIntPtr (indirect);
|
||||
if (actual == IntPtr.Zero)
|
||||
return null;
|
||||
return new CFString (actual, false);
|
||||
}
|
||||
|
||||
public static IntPtr GetIntPtr (IntPtr handle, string symbol)
|
||||
{
|
||||
var indirect = dlsym (handle, symbol);
|
||||
if (indirect == IntPtr.Zero)
|
||||
return IntPtr.Zero;
|
||||
return Marshal.ReadIntPtr (indirect);
|
||||
}
|
||||
|
||||
public static IntPtr GetCFObjectHandle (IntPtr handle, string symbol)
|
||||
{
|
||||
var indirect = dlsym (handle, symbol);
|
||||
@@ -76,7 +101,7 @@ namespace Mono.Net
|
||||
public IntPtr Handle { get; private set; }
|
||||
|
||||
[DllImport (CoreFoundationLibrary)]
|
||||
extern static IntPtr CFRetain (IntPtr handle);
|
||||
internal extern static IntPtr CFRetain (IntPtr handle);
|
||||
|
||||
void Retain ()
|
||||
{
|
||||
@@ -84,7 +109,7 @@ namespace Mono.Net
|
||||
}
|
||||
|
||||
[DllImport (CoreFoundationLibrary)]
|
||||
extern static void CFRelease (IntPtr handle);
|
||||
internal extern static void CFRelease (IntPtr handle);
|
||||
|
||||
void Release ()
|
||||
{
|
||||
@@ -126,8 +151,22 @@ namespace Mono.Net
|
||||
dlclose (handle);
|
||||
}
|
||||
}
|
||||
|
||||
public static CFArray FromNativeObjects (params INativeObject[] values)
|
||||
{
|
||||
return new CFArray (Create (values), true);
|
||||
}
|
||||
|
||||
static unsafe CFArray Create (params IntPtr[] values)
|
||||
public static unsafe IntPtr Create (params IntPtr[] values)
|
||||
{
|
||||
if (values == null)
|
||||
throw new ArgumentNullException ("values");
|
||||
fixed (IntPtr* pv = values) {
|
||||
return CFArrayCreate (IntPtr.Zero, (IntPtr) pv, (IntPtr)values.Length, kCFTypeArrayCallbacks);
|
||||
}
|
||||
}
|
||||
|
||||
internal static unsafe CFArray CreateArray (params IntPtr[] values)
|
||||
{
|
||||
if (values == null)
|
||||
throw new ArgumentNullException ("values");
|
||||
@@ -138,16 +177,19 @@ namespace Mono.Net
|
||||
return new CFArray (handle, false);
|
||||
}
|
||||
}
|
||||
|
||||
public static CFArray CreateArray (params INativeObject[] values)
|
||||
{
|
||||
return new CFArray (Create (values), true);
|
||||
}
|
||||
|
||||
public static CFArray Create (params CFObject[] values)
|
||||
public static IntPtr Create (params INativeObject[] values)
|
||||
{
|
||||
if (values == null)
|
||||
throw new ArgumentNullException ("values");
|
||||
|
||||
IntPtr[] _values = new IntPtr [values.Length];
|
||||
for (int i = 0; i < _values.Length; i++)
|
||||
_values[i] = values[i].Handle;
|
||||
|
||||
for (int i = 0; i < _values.Length; ++i)
|
||||
_values [i] = values [i].Handle;
|
||||
return Create (_values);
|
||||
}
|
||||
|
||||
@@ -166,6 +208,20 @@ namespace Mono.Net
|
||||
return CFArrayGetValueAtIndex (Handle, (IntPtr) index);
|
||||
}
|
||||
}
|
||||
|
||||
static public T [] ArrayFromHandle<T> (IntPtr handle, Func<IntPtr, T> creation) where T : class, INativeObject
|
||||
{
|
||||
if (handle == IntPtr.Zero)
|
||||
return null;
|
||||
|
||||
var c = CFArrayGetCount (handle);
|
||||
T [] ret = new T [(int)c];
|
||||
|
||||
for (uint i = 0; i < (uint)c; i++) {
|
||||
ret [i] = creation (CFArrayGetValueAtIndex (handle, (IntPtr)i));
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
|
||||
internal class CFNumber : CFObject
|
||||
@@ -209,6 +265,15 @@ namespace Mono.Net
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
[DllImport (CoreFoundationLibrary)]
|
||||
extern static IntPtr CFNumberCreate (IntPtr allocator, IntPtr theType, IntPtr valuePtr);
|
||||
|
||||
public static CFNumber FromInt32 (int number)
|
||||
{
|
||||
// 9 == kCFNumberIntType == C int
|
||||
return new CFNumber (CFNumberCreate (IntPtr.Zero, (IntPtr)9, (IntPtr)number), true);
|
||||
}
|
||||
|
||||
public static implicit operator int (CFNumber number)
|
||||
{
|
||||
@@ -328,13 +393,116 @@ namespace Mono.Net
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
internal class CFData : CFObject
|
||||
{
|
||||
public CFData (IntPtr handle, bool own) : base (handle, own) { }
|
||||
|
||||
[DllImport (CoreFoundationLibrary)]
|
||||
extern static /* CFDataRef */ IntPtr CFDataCreate (/* CFAllocatorRef */ IntPtr allocator, /* UInt8* */ IntPtr bytes, /* CFIndex */ IntPtr length);
|
||||
public unsafe static CFData FromData (byte [] buffer)
|
||||
{
|
||||
fixed (byte* p = buffer)
|
||||
{
|
||||
return FromData ((IntPtr)p, (IntPtr)buffer.Length);
|
||||
}
|
||||
}
|
||||
|
||||
public static CFData FromData (IntPtr buffer, IntPtr length)
|
||||
{
|
||||
return new CFData (CFDataCreate (IntPtr.Zero, buffer, length), true);
|
||||
}
|
||||
|
||||
public IntPtr Length {
|
||||
get { return CFDataGetLength (Handle); }
|
||||
}
|
||||
|
||||
[DllImport (CoreFoundationLibrary)]
|
||||
extern static /* CFIndex */ IntPtr CFDataGetLength (/* CFDataRef */ IntPtr theData);
|
||||
|
||||
[DllImport (CoreFoundationLibrary)]
|
||||
extern static /* UInt8* */ IntPtr CFDataGetBytePtr (/* CFDataRef */ IntPtr theData);
|
||||
|
||||
/*
|
||||
* Exposes a read-only pointer to the underlying storage.
|
||||
*/
|
||||
public IntPtr Bytes {
|
||||
get { return CFDataGetBytePtr (Handle); }
|
||||
}
|
||||
|
||||
public byte this [long idx] {
|
||||
get {
|
||||
if (idx < 0 || (ulong) idx > (ulong) Length)
|
||||
throw new ArgumentException ("idx");
|
||||
return Marshal.ReadByte (new IntPtr (Bytes.ToInt64 () + idx));
|
||||
}
|
||||
|
||||
set {
|
||||
throw new NotImplementedException ("NSData arrays can not be modified, use an NSMutableData instead");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
internal class CFDictionary : CFObject
|
||||
{
|
||||
static readonly IntPtr KeyCallbacks;
|
||||
static readonly IntPtr ValueCallbacks;
|
||||
|
||||
static CFDictionary ()
|
||||
{
|
||||
var handle = dlopen (CoreFoundationLibrary, 0);
|
||||
if (handle == IntPtr.Zero)
|
||||
return;
|
||||
|
||||
try {
|
||||
KeyCallbacks = GetIndirect (handle, "kCFTypeDictionaryKeyCallBacks");
|
||||
ValueCallbacks = GetIndirect (handle, "kCFTypeDictionaryValueCallBacks");
|
||||
} finally {
|
||||
dlclose (handle);
|
||||
}
|
||||
}
|
||||
|
||||
public CFDictionary (IntPtr handle, bool own) : base (handle, own) { }
|
||||
|
||||
public static CFDictionary FromObjectAndKey (IntPtr obj, IntPtr key)
|
||||
{
|
||||
return new CFDictionary (CFDictionaryCreate (IntPtr.Zero, new IntPtr[] { key }, new IntPtr [] { obj }, (IntPtr)1, KeyCallbacks, ValueCallbacks), true);
|
||||
}
|
||||
|
||||
public static CFDictionary FromKeysAndObjects (IList<Tuple<IntPtr,IntPtr>> items)
|
||||
{
|
||||
var keys = new IntPtr [items.Count];
|
||||
var values = new IntPtr [items.Count];
|
||||
for (int i = 0; i < items.Count; i++) {
|
||||
keys [i] = items [i].Item1;
|
||||
values [i] = items [i].Item2;
|
||||
}
|
||||
return new CFDictionary (CFDictionaryCreate (IntPtr.Zero, keys, values, (IntPtr)items.Count, KeyCallbacks, ValueCallbacks), true);
|
||||
}
|
||||
|
||||
[DllImport (CoreFoundationLibrary)]
|
||||
extern static IntPtr CFDictionaryCreate (IntPtr allocator, IntPtr[] keys, IntPtr[] vals, IntPtr len, IntPtr keyCallbacks, IntPtr valCallbacks);
|
||||
|
||||
[DllImport (CoreFoundationLibrary)]
|
||||
extern static IntPtr CFDictionaryGetValue (IntPtr handle, IntPtr key);
|
||||
|
||||
[DllImport (CoreFoundationLibrary)]
|
||||
extern static IntPtr CFDictionaryCreateCopy (IntPtr allocator, IntPtr handle);
|
||||
|
||||
public CFDictionary Copy ()
|
||||
{
|
||||
return new CFDictionary (CFDictionaryCreateCopy (IntPtr.Zero, Handle), true);
|
||||
}
|
||||
|
||||
public CFMutableDictionary MutableCopy ()
|
||||
{
|
||||
return new CFMutableDictionary (CFDictionaryCreateMutableCopy (IntPtr.Zero, IntPtr.Zero, Handle), true);
|
||||
}
|
||||
|
||||
[DllImport (CoreFoundationLibrary)]
|
||||
extern static IntPtr CFDictionaryCreateMutableCopy (IntPtr allocator, IntPtr capacity, IntPtr theDict);
|
||||
|
||||
public IntPtr GetValue (IntPtr key)
|
||||
{
|
||||
return CFDictionaryGetValue (Handle, key);
|
||||
@@ -346,6 +514,31 @@ namespace Mono.Net
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal class CFMutableDictionary : CFDictionary
|
||||
{
|
||||
public CFMutableDictionary (IntPtr handle, bool own) : base (handle, own) { }
|
||||
|
||||
public void SetValue (IntPtr key, IntPtr val)
|
||||
{
|
||||
CFDictionarySetValue (Handle, key, val);
|
||||
}
|
||||
|
||||
public static CFMutableDictionary Create ()
|
||||
{
|
||||
var handle = CFDictionaryCreateMutable (IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
|
||||
if (handle == IntPtr.Zero)
|
||||
throw new InvalidOperationException ();
|
||||
return new CFMutableDictionary (handle, true);
|
||||
}
|
||||
|
||||
[DllImport (CoreFoundationLibrary)]
|
||||
extern static void CFDictionarySetValue (IntPtr handle, IntPtr key, IntPtr val);
|
||||
|
||||
[DllImport (CoreFoundationLibrary)]
|
||||
extern static IntPtr CFDictionaryCreateMutable (IntPtr allocator, IntPtr capacity, IntPtr keyCallback, IntPtr valueCallbacks);
|
||||
|
||||
}
|
||||
|
||||
internal class CFUrl : CFObject
|
||||
{
|
||||
@@ -1066,4 +1259,86 @@ namespace Mono.Net
|
||||
return new CFWebProxy ();
|
||||
}
|
||||
}
|
||||
|
||||
class CFBoolean : INativeObject, IDisposable {
|
||||
IntPtr handle;
|
||||
|
||||
public static readonly CFBoolean True;
|
||||
public static readonly CFBoolean False;
|
||||
|
||||
static CFBoolean ()
|
||||
{
|
||||
var handle = CFObject.dlopen (CFObject.CoreFoundationLibrary, 0);
|
||||
if (handle == IntPtr.Zero)
|
||||
return;
|
||||
try {
|
||||
True = new CFBoolean (CFObject.GetCFObjectHandle (handle, "kCFBooleanTrue"), false);
|
||||
False = new CFBoolean (CFObject.GetCFObjectHandle (handle, "kCFBooleanFalse"), false);
|
||||
}
|
||||
finally {
|
||||
CFObject.dlclose (handle);
|
||||
}
|
||||
}
|
||||
|
||||
internal CFBoolean (IntPtr handle, bool owns)
|
||||
{
|
||||
this.handle = handle;
|
||||
if (!owns)
|
||||
CFObject.CFRetain (handle);
|
||||
}
|
||||
|
||||
~CFBoolean ()
|
||||
{
|
||||
Dispose (false);
|
||||
}
|
||||
|
||||
public IntPtr Handle {
|
||||
get {
|
||||
return handle;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose ()
|
||||
{
|
||||
Dispose (true);
|
||||
GC.SuppressFinalize (this);
|
||||
}
|
||||
|
||||
protected virtual void Dispose (bool disposing)
|
||||
{
|
||||
if (handle != IntPtr.Zero){
|
||||
CFObject.CFRelease (handle);
|
||||
handle = IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
|
||||
public static implicit operator bool (CFBoolean value)
|
||||
{
|
||||
return value.Value;
|
||||
}
|
||||
|
||||
public static explicit operator CFBoolean (bool value)
|
||||
{
|
||||
return FromBoolean (value);
|
||||
}
|
||||
|
||||
public static CFBoolean FromBoolean (bool value)
|
||||
{
|
||||
return value ? True : False;
|
||||
}
|
||||
|
||||
[DllImport (CFObject.CoreFoundationLibrary)]
|
||||
[return: MarshalAs (UnmanagedType.I1)]
|
||||
extern static /* Boolean */ bool CFBooleanGetValue (/* CFBooleanRef */ IntPtr boolean);
|
||||
|
||||
public bool Value {
|
||||
get {return CFBooleanGetValue (handle);}
|
||||
}
|
||||
|
||||
public static bool GetValue (IntPtr boolean)
|
||||
{
|
||||
return CFBooleanGetValue (boolean);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1016,6 +1016,18 @@ namespace System.Net
|
||||
IAsyncResult result = null;
|
||||
try {
|
||||
result = s.BeginWrite (buffer, offset, size, cb, state);
|
||||
} catch (ObjectDisposedException) {
|
||||
lock (this) {
|
||||
if (Data.request != request)
|
||||
return null;
|
||||
}
|
||||
throw;
|
||||
} catch (IOException e) {
|
||||
SocketException se = e.InnerException as SocketException;
|
||||
if (se != null && se.SocketErrorCode == SocketError.NotConnected) {
|
||||
return null;
|
||||
}
|
||||
throw;
|
||||
} catch (Exception) {
|
||||
status = WebExceptionStatus.SendFailure;
|
||||
throw;
|
||||
|
||||
@@ -16,7 +16,7 @@ using System.ComponentModel.Design;
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
#if !MOBILE && !MONOMAC
|
||||
#if !MOBILE && !MONOMAC && !XAMMAC_4_5
|
||||
using System.Drawing.Design;
|
||||
#endif
|
||||
using NUnit.Framework;
|
||||
@@ -1053,7 +1053,7 @@ namespace MonoTests.System.ComponentModel
|
||||
return attr;
|
||||
return null;
|
||||
}
|
||||
#if !MOBILE && !MONOMAC
|
||||
#if !MOBILE && !MONOMAC && !XAMMAC_4_5
|
||||
class GetEditor_test
|
||||
{
|
||||
[Editor (typeof (UIEditor), typeof (UITypeEditor))]
|
||||
|
||||
@@ -16,7 +16,7 @@ namespace MonoTests.System.ComponentModel
|
||||
[TestFixture]
|
||||
public class ToolboxItemAttributeTests
|
||||
{
|
||||
#if !MOBILE && !MONOMAC
|
||||
#if !MOBILE && !MONOMAC && !XAMMAC_4_5
|
||||
[Test]
|
||||
public void DefaultType ()
|
||||
{
|
||||
|
||||
@@ -287,7 +287,11 @@ namespace MonoTests.System.Configuration {
|
||||
[Test]
|
||||
public void TestSettings2_Properties ()
|
||||
{
|
||||
#if XAMMAC_4_5
|
||||
string expected = "MonoTests.System.Configuration.ProviderPoker, xammac_net_4_5_System_test, Version=0.0.0.0";
|
||||
#else
|
||||
string expected = "MonoTests.System.Configuration.ProviderPoker, net_4_x_System_test, Version=0.0.0.0";
|
||||
#endif
|
||||
Assert.AreEqual (expected, new SettingsProviderAttribute (typeof (ProviderPoker)).ProviderTypeName.Substring (0, expected.Length), "#1");
|
||||
TestSettings2 settings = new TestSettings2 ();
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
using NUnit.Framework;
|
||||
|
||||
@@ -22,6 +23,13 @@ namespace MonoTests.System.Diagnostics
|
||||
[TestFixture]
|
||||
public class ProcessTest
|
||||
{
|
||||
static bool RunningOnUnix {
|
||||
get {
|
||||
int p = (int)Environment.OSVersion.Platform;
|
||||
return ((p == 128) || (p == 4) || (p == 6));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void GetProcessById_MachineName_Null ()
|
||||
{
|
||||
@@ -728,13 +736,6 @@ namespace MonoTests.System.Diagnostics
|
||||
bytesRead = stm.EndRead (ar);
|
||||
}
|
||||
|
||||
static bool RunningOnUnix {
|
||||
get {
|
||||
int p = (int)Environment.OSVersion.Platform;
|
||||
return ((p == 128) || (p == 4) || (p == 6));
|
||||
}
|
||||
}
|
||||
|
||||
public int bytesRead = -1;
|
||||
|
||||
[Test]
|
||||
@@ -1113,5 +1114,71 @@ namespace MonoTests.System.Diagnostics
|
||||
}
|
||||
}
|
||||
#endif // MONO_FEATURE_PROCESS_START
|
||||
|
||||
[Test]
|
||||
[NUnit.Framework.Category ("MobileNotWorking")]
|
||||
public void GetProcessesByName()
|
||||
{
|
||||
// This should return Process[0] or a Process[] with all the "foo" programs running
|
||||
Process.GetProcessesByName ("foo");
|
||||
}
|
||||
|
||||
[Test]
|
||||
[NUnit.Framework.Category ("MobileNotWorking")]
|
||||
public void NonChildProcessWaitForExit ()
|
||||
{
|
||||
if (!RunningOnUnix)
|
||||
Assert.Ignore ("accessing parent pid, only available on unix");
|
||||
|
||||
using (Process process = Process.GetProcessById (getppid ()))
|
||||
using (ManualResetEvent mre = new ManualResetEvent (false))
|
||||
{
|
||||
Assert.IsFalse (process.WaitForExit (10), "#1");
|
||||
Assert.IsFalse (process.HasExited, "#2");
|
||||
Assert.Throws<InvalidOperationException>(delegate { int exitCode = process.ExitCode; }, "#3");
|
||||
|
||||
process.Exited += (s, e) => mre.Set ();
|
||||
process.EnableRaisingEvents = true;
|
||||
Assert.IsFalse (mre.WaitOne (100), "#4");
|
||||
|
||||
Assert.IsFalse (process.WaitForExit (10), "#5");
|
||||
Assert.IsFalse (process.HasExited, "#6");
|
||||
Assert.Throws<InvalidOperationException>(delegate { int exitCode = process.ExitCode; }, "#7");
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
[NUnit.Framework.Category ("MobileNotWorking")]
|
||||
public void NonChildProcessName ()
|
||||
{
|
||||
if (!RunningOnUnix)
|
||||
Assert.Ignore ("accessing parent pid, only available on unix");
|
||||
|
||||
using (Process process = Process.GetProcessById (getppid ()))
|
||||
{
|
||||
string pname = process.ProcessName;
|
||||
Assert.IsNotNull (pname, "#1");
|
||||
AssertHelper.IsNotEmpty (pname, "#2");
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
[NUnit.Framework.Category ("MobileNotWorking")]
|
||||
public void NonChildProcessId ()
|
||||
{
|
||||
if (!RunningOnUnix)
|
||||
Assert.Ignore ("accessing parent pid, only available on unix");
|
||||
|
||||
int ppid;
|
||||
using (Process process = Process.GetProcessById (ppid = getppid ()))
|
||||
{
|
||||
int pid = process.Id;
|
||||
Assert.AreEqual (ppid, pid, "#1");
|
||||
AssertHelper.Greater (pid, 0, "#2");
|
||||
}
|
||||
}
|
||||
|
||||
[DllImport ("libc")]
|
||||
static extern int getppid();
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,7 @@ public class SslStreamTest {
|
||||
}
|
||||
|
||||
[Test] //bug https://bugzilla.novell.com/show_bug.cgi?id=457120
|
||||
[Category ("MacNotWorking")] // Works but launches a prompt on 10.12 that will fail if you don't click in a few seconds
|
||||
#if FEATURE_NO_BSD_SOCKETS
|
||||
[ExpectedException (typeof (PlatformNotSupportedException))]
|
||||
#endif
|
||||
|
||||
@@ -4622,6 +4622,8 @@ namespace MonoTests.System.Net.Sockets
|
||||
client.DualMode = true;
|
||||
var ar1 = client.BeginConnect (ep, BCCallback, client);
|
||||
Assert.IsTrue (BCCalledBack.WaitOne (10000), "#1");
|
||||
Assert.AreEqual(server.AddressFamily, client.RemoteEndPoint.AddressFamily, "#2");
|
||||
Assert.AreEqual(server.AddressFamily, client.LocalEndPoint.AddressFamily, "#3");
|
||||
client.Disconnect (false);
|
||||
client.Close ();
|
||||
|
||||
@@ -4629,7 +4631,9 @@ namespace MonoTests.System.Net.Sockets
|
||||
client = new Socket (AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
|
||||
client.DualMode = true;
|
||||
var ar2 = client.BeginConnect (IPAddress.Loopback, ep.Port, BCCallback, client);
|
||||
Assert.IsTrue (BCCalledBack.WaitOne (10000), "#2");
|
||||
Assert.IsTrue (BCCalledBack.WaitOne (10000), "#4");
|
||||
Assert.AreEqual(server.AddressFamily, client.RemoteEndPoint.AddressFamily, "#5");
|
||||
Assert.AreEqual(server.AddressFamily, client.LocalEndPoint.AddressFamily, "#6");
|
||||
client.Disconnect (false);
|
||||
client.Close ();
|
||||
|
||||
@@ -4637,7 +4641,9 @@ namespace MonoTests.System.Net.Sockets
|
||||
client = new Socket (AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
|
||||
client.DualMode = true;
|
||||
var ar3 = client.BeginConnect (new [] {IPAddress.Loopback}, ep.Port, BCCallback, client);
|
||||
Assert.IsTrue (BCCalledBack.WaitOne (10000), "#2");
|
||||
Assert.IsTrue (BCCalledBack.WaitOne (10000), "#7");
|
||||
Assert.AreEqual(server.AddressFamily, client.RemoteEndPoint.AddressFamily, "#8");
|
||||
Assert.AreEqual(server.AddressFamily, client.LocalEndPoint.AddressFamily, "#9");
|
||||
client.Disconnect (false);
|
||||
client.Close();
|
||||
}
|
||||
@@ -4675,6 +4681,26 @@ namespace MonoTests.System.Net.Sockets
|
||||
|
||||
Assert.IsTrue (mre.WaitOne (1000), "ConnectedAsync timeout");
|
||||
}
|
||||
|
||||
[Test] // Covers https://bugzilla.xamarin.com/show_bug.cgi?id=52549
|
||||
public void SocketMismatchProtocol ()
|
||||
{
|
||||
try {
|
||||
using (Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Tcp));
|
||||
Assert.Fail ("#1");
|
||||
} catch (SocketException e) {
|
||||
// Only work on OSX
|
||||
// Assert.AreEqual(SocketError.ProtocolType, e.SocketErrorCode, "#2");
|
||||
}
|
||||
|
||||
try {
|
||||
using (Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Udp));
|
||||
Assert.Fail ("#3");
|
||||
} catch (SocketException e) {
|
||||
// Only work on OSX
|
||||
// Assert.AreEqual(SocketError.ProtocolType, e.SocketErrorCode, "#4");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,7 +166,9 @@ namespace MonoTests.System.Net.WebSockets
|
||||
Assert.AreEqual (WebSocketState.Closed, socket.State);
|
||||
}
|
||||
|
||||
[Test, ExpectedException (typeof (InvalidOperationException))]
|
||||
[Test]
|
||||
[ExpectedException (typeof (InvalidOperationException))]
|
||||
[Category ("MobileNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
|
||||
public void SendAsyncArgTest_NotConnected ()
|
||||
{
|
||||
socket.SendAsync (new ArraySegment<byte> (new byte[0]), WebSocketMessageType.Text, true, CancellationToken.None);
|
||||
@@ -180,7 +182,9 @@ namespace MonoTests.System.Net.WebSockets
|
||||
socket.SendAsync (new ArraySegment<byte> (), WebSocketMessageType.Text, true, CancellationToken.None);
|
||||
}
|
||||
|
||||
[Test, ExpectedException (typeof (InvalidOperationException))]
|
||||
[Test]
|
||||
[ExpectedException (typeof (InvalidOperationException))]
|
||||
[Category ("MobileNotWorking")] // Fails when ran as part of the entire BCL test suite. Works when only this fixture is ran
|
||||
public void ReceiveAsyncArgTest_NotConnected ()
|
||||
{
|
||||
socket.ReceiveAsync (new ArraySegment<byte> (new byte[0]), CancellationToken.None);
|
||||
|
||||
@@ -587,6 +587,7 @@ mgk3bWUV6ChegutbguiKrI/DbO7wPiDLxw==
|
||||
}
|
||||
|
||||
[Test]
|
||||
[Category ("MacNotWorking")] // SecCertificateCreateWithData does different things on 10.11 vs 10.12 with invalid certificates https://bugzilla.xamarin.com/show_bug.cgi?id=53689
|
||||
[ExpectedException (typeof (CryptographicException))]
|
||||
public void Pkcs12_1_WithoutPassword ()
|
||||
{
|
||||
@@ -601,6 +602,7 @@ mgk3bWUV6ChegutbguiKrI/DbO7wPiDLxw==
|
||||
}
|
||||
|
||||
[Test]
|
||||
[Category ("MacNotWorking")] // SecCertificateCreateWithData does different things on 10.11 vs 10.12 with invalid certificates https://bugzilla.xamarin.com/show_bug.cgi?id=53689
|
||||
public void Pkcs12_2_Properties ()
|
||||
{
|
||||
CheckPkcs12 (new X509Certificate (farscape_nopwd_pfx));
|
||||
@@ -732,6 +734,7 @@ mgk3bWUV6ChegutbguiKrI/DbO7wPiDLxw==
|
||||
|
||||
[Test]
|
||||
[ExpectedException (typeof (CryptographicException))]
|
||||
[Category ("MacNotWorking")] // SecCertificateCreateWithData does different things on 10.11 vs 10.12 with invalid certificates https://bugzilla.xamarin.com/show_bug.cgi?id=53689
|
||||
public void Pkcs7_Ctor ()
|
||||
{
|
||||
new X509Certificate (farscape_pkcs7);
|
||||
@@ -739,6 +742,7 @@ mgk3bWUV6ChegutbguiKrI/DbO7wPiDLxw==
|
||||
|
||||
[Test]
|
||||
[ExpectedException (typeof (CryptographicException))]
|
||||
[Category ("MacNotWorking")] // SecCertificateCreateWithData does different things on 10.11 vs 10.12 with invalid certificates https://bugzilla.xamarin.com/show_bug.cgi?id=53689
|
||||
public void Pkcs7_Import ()
|
||||
{
|
||||
X509Certificate x = new X509Certificate ();
|
||||
|
||||
@@ -292,6 +292,20 @@ Mono.Btls/X509ChainImplBtls.cs
|
||||
|
||||
Mono.Http/NtlmClient.cs
|
||||
|
||||
Mono.AppleTls/AppleCertificateHelper.cs
|
||||
Mono.AppleTls/AppleTlsContext.cs
|
||||
Mono.AppleTls/AppleTlsProvider.cs
|
||||
Mono.AppleTls/AppleTlsStream.cs
|
||||
Mono.AppleTls/INativeObject.cs
|
||||
Mono.AppleTls/Certificate.cs
|
||||
Mono.AppleTls/ImportExport.cs
|
||||
Mono.AppleTls/Enums.cs
|
||||
Mono.AppleTls/SecureTransport.cs
|
||||
Mono.AppleTls/Policy.cs
|
||||
Mono.AppleTls/Trust.cs
|
||||
Mono.AppleTls/SslConnection.cs
|
||||
Mono.AppleTls/Items.cs
|
||||
|
||||
Mono.Net.Security/AsyncProtocolRequest.cs
|
||||
Mono.Net.Security/CallbackHelpers.cs
|
||||
Mono.Net.Security/ChainValidationHelper.cs
|
||||
@@ -311,6 +325,8 @@ Mono.Net.Security/SystemCertificateValidator.cs
|
||||
|
||||
Mono.Util/MonoPInvokeCallbackAttribute.cs
|
||||
|
||||
MonoTouch/Dummy.cs
|
||||
|
||||
ReferenceSources/AutoWebProxyScriptEngine.cs
|
||||
ReferenceSources/AssertWrapper.cs
|
||||
ReferenceSources/CAPI.cs
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
#include net_4_x_System.dll.sources
|
||||
Mono.Net.Security/MonoTlsProviderFactory.Apple.cs
|
||||
Loaded 100 of 274 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user