예제 #1
0
        public static HKEYType ConnectRegistry(string computerName, BigInteger key)
        {
            if (string.IsNullOrEmpty(computerName))
            {
                computerName = string.Empty;
            }

            RegistryKey newKey;

            try {
                newKey = RegistryKey.OpenRemoteBaseKey(MapSystemKey(key), computerName);
            }catch (IOException ioe) {
                throw PythonExceptions.CreateThrowable(PythonExceptions.WindowsError, PythonExceptions._WindowsError.ERROR_BAD_NETPATH, ioe.Message);
            } catch (Exception e) {
                throw new ExternalException(e.Message);
            }
            return(new HKEYType(newKey));
        }
예제 #2
0
        public static PythonTuple EnumValue(object key, int index)
        {
            HKEYType rootKey = GetRootKey(key);

            if (index >= rootKey.GetKey().ValueCount)
            {
                throw PythonExceptions.CreateThrowable(PythonExceptions.WindowsError, PythonExceptions._WindowsError.ERROR_BAD_COMMAND, "No more data is available");
            }

            var    nativeRootKey = rootKey.GetKey();
            string valueName     = nativeRootKey.GetValueNames()[index];

            int    valueKind;
            object value;

            QueryValueExImpl(nativeRootKey, valueName, out valueKind, out value);
            return(PythonTuple.MakeTuple(valueName, value, valueKind));
        }
예제 #3
0
        public static bool QueryReflectionKey(object key)
        {
            HKEYType rootKey = GetRootKey(key);
            bool     isDisabled;

            if (!Environment.Is64BitOperatingSystem)
            {
                throw new NotImplementedException("not implemented on this platform");
            }

            int dwRet = RegQueryReflectionKey(rootKey.GetKey().Handle, out isDisabled);

            if (dwRet != ERROR_SUCCESS)
            {
                throw PythonExceptions.CreateThrowable(PythonExceptions.WindowsError, dwRet);
            }
            return(isDisabled);
        }
예제 #4
0
        public static HKEYType OpenKey(object key, string subKeyName, int reserved, int mask)
        {
            HKEYType    rootKey = GetRootKey(key);
            RegistryKey newKey  = null;

            // I'm assuming that the masks that CPy uses are the same as the Win32 API one mentioned here-
            // http://msdn2.microsoft.com/en-us/library/ms724878(VS.85).aspx

            // KEY_WRITE is a combination of KEY_SET_VALUE and KEY_CREATE_SUB_KEY. We'll open with write access
            // if any of this is set.
            // KEY_READ is a combination of KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS and KEY_NOTIFY. We'll open
            // with read access for all of these.


            try {
                if ((mask & KEY_SET_VALUE) == KEY_SET_VALUE ||
                    (mask & KEY_CREATE_SUB_KEY) == KEY_CREATE_SUB_KEY)
                {
                    newKey = rootKey.key.OpenSubKey(subKeyName, true);
                }
                else if ((mask & KEY_QUERY_VALUE) == KEY_QUERY_VALUE ||
                         (mask & KEY_ENUMERATE_SUB_KEYS) == KEY_ENUMERATE_SUB_KEYS ||
                         (mask & KEY_NOTIFY) == KEY_NOTIFY)
                {
                    newKey = rootKey.key.OpenSubKey(subKeyName, false);
                }
                else
                {
                    throw new Win32Exception("Unexpected mode");
                }
            } catch (SecurityException) {
                throw PythonExceptions.CreateThrowable(PythonExceptions.WindowsError, PythonExceptions._WindowsError.ERROR_ACCESS_DENIED, "Access is denied");
            }


            if (newKey == null)
            {
                throw PythonExceptions.CreateThrowable(PythonExceptions.WindowsError, PythonExceptions._WindowsError.ERROR_FILE_NOT_FOUND, "The system cannot find the file specified");
            }

            return(new HKEYType(newKey));
        }
예제 #5
0
            public void do_handshake()
            {
                try {
                    // make sure the remote side hasn't shutdown before authenticating so we don't
                    // hang if we're in blocking mode.
#pragma warning disable 219 // unused variable
                    int available = _socket._socket.Available;
#pragma warning restore 219
                } catch (SocketException) {
                    throw PythonExceptions.CreateThrowable(PythonExceptions.OSError, "socket closed before handshake");
                }

                EnsureSslStream(true);

                var enabledSslProtocols = GetProtocolType(_protocol);

                try {
                    if (_serverSide)
                    {
                        _sslStream.AuthenticateAsServer(_cert, _certsMode == PythonSsl.CERT_REQUIRED, enabledSslProtocols, false);
                    }
                    else
                    {
                        var collection = new X509CertificateCollection();

                        if (_cert != null)
                        {
                            collection.Add(_cert);
                        }
                        _sslStream.AuthenticateAsClient(_serverHostName ?? _socket._hostName, collection, enabledSslProtocols, false);
                    }
                } catch (AuthenticationException e) {
                    ((IDisposable)_socket._socket).Dispose();
                    throw PythonExceptions.CreateThrowable(PythonSsl.SSLError(_context), "errors while performing handshake: ", e.ToString());
                }

                if (_validationFailure != null)
                {
                    throw _validationFailure;
                }
            }
예제 #6
0
파일: winreg.cs 프로젝트: zuvys/ironpython3
        public static PythonTuple EnumValue(object key, int index)
        {
            HKEYType rootKey = GetRootKey(key);

            if (index >= rootKey.GetKey().ValueCount)
            {
                throw PythonExceptions.CreateThrowable(PythonExceptions.OSError, PythonExceptions._OSError.ERROR_BAD_COMMAND, "No more data is available", null, PythonExceptions._OSError.ERROR_BAD_COMMAND);
            }

            var    nativeRootKey = rootKey.GetKey();
            string valueName     = nativeRootKey.GetValueNames()[index];

            // it looks like nativeRootKey.Handle fails on HKEY_PERFORMANCE_DATA so manually create the handle instead
            var handle = rootKey.hkey == HKEY_PERFORMANCE_DATA ? new SafeRegistryHandle(new IntPtr(unchecked ((int)0x80000004)), true) : nativeRootKey.Handle;

            int    valueKind;
            object value;

            QueryValueExImpl(handle, valueName, out valueKind, out value);
            return(PythonTuple.MakeTuple(valueName, value, valueKind));
        }
예제 #7
0
        public static Bytes byteswap(CodeContext /*!*/ context, [NotNone] IBufferProtocol fragment, int width)
        {
            if (width < 1 || width > 4)
            {
                throw PythonExceptions.CreateThrowable(error(context), "Size should be 1, 2, 3 or 4");
            }

            using var buffer = fragment.GetBuffer();
            if (buffer.NumBytes() % width != 0)
            {
                throw PythonExceptions.CreateThrowable(error(context), "not a whole number of frames");
            }

            var array = buffer.ToArray();

            if (width == 2)
            {
                for (var i = 0; i < array.Length; i += width)
                {
                    array.ByteSwap(i, i + 1);
                }
            }
            else if (width == 3)
            {
                for (var i = 0; i < array.Length; i += width)
                {
                    array.ByteSwap(i, i + 2);
                }
            }
            else if (width == 4)
            {
                for (var i = 0; i < array.Length; i += width)
                {
                    array.ByteSwap(i, i + 3);
                    array.ByteSwap(i + 1, i + 2);
                }
            }
            return(Bytes.Make(array));
        }
예제 #8
0
            public string GetLocale(CodeContext /*!*/ context, int category)
            {
                switch ((LocaleCategories)category)
                {
                case LocaleCategories.All:
                    if (Collate == CType &&
                        Collate == Time &&
                        Collate == Monetary &&
                        Collate == Numeric)
                    {
                        // they're all the same, return only 1 name
                        goto case LocaleCategories.Collate;
                    }

                    // return them all...
                    return(String.Format("LC_COLLATE={0};LC_CTYPE={1};LC_MONETARY={2};LC_NUMERIC={3};LC_TIME={4}",
                                         GetLocale(context, LC_COLLATE),
                                         GetLocale(context, LC_CTYPE),
                                         GetLocale(context, LC_MONETARY),
                                         GetLocale(context, LC_NUMERIC),
                                         GetLocale(context, LC_TIME)));

                case LocaleCategories.Collate: return(CultureToName(Collate));

                case LocaleCategories.CType: return(CultureToName(CType));

                case LocaleCategories.Time: return(CultureToName(Time));

                case LocaleCategories.Monetary: return(CultureToName(Monetary));

                case LocaleCategories.Numeric: return(CultureToName(Numeric));

                default:
                    throw PythonExceptions.CreateThrowable(_localeerror(context), "unknown locale category");
                }
            }
예제 #9
0
 private void ValidationError(object reason)
 {
     _validationFailure = PythonExceptions.CreateThrowable(PythonSsl.SSLError(_context), "errors while validating certificate chain: ", reason.ToString());
 }
예제 #10
0
 private static Exception Incomplete(CodeContext /*!*/ context, params object[] args)
 {
     return(PythonExceptions.CreateThrowable((PythonType)context.LanguageContext.GetModuleState(_IncompleteKey), args));
 }
예제 #11
0
        public static PythonTuple CreateProcess(
            CodeContext context,
            string applicationName,
            string commandLineArgs,
            object pSec /*subprocess.py passes None*/,
            object tSec /*subprocess.py passes None*/,
            int?bInheritHandles,
            uint?dwCreationFlags,
            object lpEnvironment,
            string lpCurrentDirectory,
            object lpStartupInfo /* subprocess.py passes STARTUPINFO*/)
        {
            object dwFlags     = PythonOps.GetBoundAttr(context, lpStartupInfo, "dwFlags");     //public Int32 dwFlags;
            object hStdInput   = PythonOps.GetBoundAttr(context, lpStartupInfo, "hStdInput");   //public IntPtr hStdInput;
            object hStdOutput  = PythonOps.GetBoundAttr(context, lpStartupInfo, "hStdOutput");  //public IntPtr hStdOutput;
            object hStdError   = PythonOps.GetBoundAttr(context, lpStartupInfo, "hStdError");   //public IntPtr hStdError;
            object wShowWindow = PythonOps.GetBoundAttr(context, lpStartupInfo, "wShowWindow"); //Int16 wShowWindow;

            Int32 dwFlagsInt32 = dwFlags != null?Converter.ConvertToInt32(dwFlags) : 0;

            IntPtr hStdInputIntPtr  = hStdInput != null ? new IntPtr(Converter.ConvertToInt32(hStdInput)) : IntPtr.Zero;
            IntPtr hStdOutputIntPtr = hStdOutput != null ? new IntPtr(Converter.ConvertToInt32(hStdOutput)) : IntPtr.Zero;
            IntPtr hStdErrorIntPtr  = hStdError != null ? new IntPtr(Converter.ConvertToInt32(hStdError)) : IntPtr.Zero;
            Int16  wShowWindowInt16 = wShowWindow != null?Converter.ConvertToInt16(wShowWindow) : (short)0;

            STARTUPINFO startupInfo = new STARTUPINFO();

            startupInfo.dwFlags     = dwFlagsInt32;
            startupInfo.hStdInput   = hStdInputIntPtr;
            startupInfo.hStdOutput  = hStdOutputIntPtr;
            startupInfo.hStdError   = hStdErrorIntPtr;
            startupInfo.wShowWindow = wShowWindowInt16;

            // No special security
            SECURITY_ATTRIBUTES pSecSA = new SECURITY_ATTRIBUTES();

            pSecSA.nLength = Marshal.SizeOf(pSecSA);

            SECURITY_ATTRIBUTES tSecSA = new SECURITY_ATTRIBUTES();

            tSecSA.nLength = Marshal.SizeOf(tSecSA);

            if (pSec != null)
            {
                /* If pSec paseed in from Python is not NULL
                 * there needs to be some conversion done here...*/
            }
            if (tSec != null)
            {
                /* If tSec paseed in from Python is not NULL
                 * there needs to be some conversion done here...*/
            }

            // If needed convert lpEnvironment Dictionary to lpEnvironmentIntPtr
            string lpEnvironmentStr = EnvironmentToNative(context, lpEnvironment);

            PROCESS_INFORMATION lpProcessInformation = new PROCESS_INFORMATION();
            bool result = CreateProcessPI(
                String.IsNullOrEmpty(applicationName) ? null : applicationName /*applicationNameHelper*//*processStartInfo.FileName*/,
                String.IsNullOrEmpty(commandLineArgs) ? null : commandLineArgs /*commandLineArgsHelper*//*processStartInfo.Arguments*/,
                ref pSecSA, ref tSecSA,
                bInheritHandles.HasValue && bInheritHandles.Value > 0 ? true : false,
                dwCreationFlags.HasValue ? dwCreationFlags.Value : 0,
                lpEnvironmentStr,
                lpCurrentDirectory,
                ref startupInfo,
                out lpProcessInformation);

            if (!result)
            {
                int error = Marshal.GetLastWin32Error();
                throw PythonExceptions.CreateThrowable(PythonExceptions.WindowsError, error, FormatError(error));
            }

            IntPtr hp  = lpProcessInformation.hProcess;
            IntPtr ht  = lpProcessInformation.hThread;
            int    pid = lpProcessInformation.dwProcessId;
            int    tid = lpProcessInformation.dwThreadId;

            return(PythonTuple.MakeTuple(
                       new PythonSubprocessHandle(hp, true),
                       new PythonSubprocessHandle(ht),
                       pid, tid));
        }
예제 #12
0
파일: mmap.cs 프로젝트: ife/IronLanguages
        private static Exception WindowsError(int code)
        {
            string message = CTypes.FormatError(code);

            return(PythonExceptions.CreateThrowable(PythonExceptions.WindowsError, code, message));
        }
예제 #13
0
파일: winreg.cs 프로젝트: zuvys/ironpython3
        private static void QueryValueExImpl(SafeRegistryHandle handle, string valueName, out int valueKind, out object value)
        {
            valueName = valueName ?? ""; // it looks like RegQueryValueEx can fail with null, use empty string instead
            valueKind = 0;
            int dwRet;

            byte[] data   = new byte[128];
            uint   length = (uint)data.Length;

            // query the size first, reading the data as we query...
            dwRet = RegQueryValueEx(handle, valueName, IntPtr.Zero, out valueKind, data, ref length);
            while (dwRet == ERROR_MORE_DATA)
            {
                data   = new byte[data.Length * 2];
                length = (uint)data.Length;
                dwRet  = RegQueryValueEx(handle, valueName, IntPtr.Zero, out valueKind, data, ref length);
            }

            if (dwRet == PythonExceptions._OSError.ERROR_FILE_NOT_FOUND)
            {
                throw PythonExceptions.CreateThrowable(PythonExceptions.OSError, PythonExceptions._OSError.ERROR_FILE_NOT_FOUND, "The system cannot find the file specified", null, PythonExceptions._OSError.ERROR_FILE_NOT_FOUND);
            }
            if (dwRet != ERROR_SUCCESS)
            {
                throw PythonExceptions.CreateThrowable(PythonExceptions.OSError, dwRet);
            }

            // convert the result into a Python object

            switch (valueKind)
            {
            case REG_MULTI_SZ:
                PythonList list     = new PythonList();
                int        curIndex = 0;
                while (curIndex < length)
                {
                    for (int dataIndex = curIndex; dataIndex < length; dataIndex += 2)
                    {
                        if (data[dataIndex] == 0 && data[dataIndex + 1] == 0)
                        {
                            // got a full string
                            list.Add(ExtractString(data, curIndex, dataIndex));
                            curIndex = dataIndex + 2;

                            if (curIndex + 2 <= length && data[curIndex] == 0 && data[curIndex + 1] == 0)
                            {
                                // double null terminated
                                curIndex = data.Length;
                                break;
                            }
                        }
                    }

                    if (curIndex != data.Length)
                    {
                        // not null terminated
                        list.Add(ExtractString(data, curIndex, data.Length));
                    }
                }
                value = list;
                break;

            case REG_BINARY:
                var tight_fit_data = new byte[length];
                for (int i = 0; i < length; i++)
                {
                    tight_fit_data[i] = data[i];
                }
                value = length == 0 ? null : new Bytes(tight_fit_data);
                break;

            case REG_EXPAND_SZ:
            case REG_SZ:
                if (length >= 2 && data[length - 1] == 0 && data[length - 2] == 0)
                {
                    value = ExtractString(data, 0, (int)length - 2);
                }
                else
                {
                    value = ExtractString(data, 0, (int)length);
                }
                break;

            case REG_DWORD:
                if (BitConverter.IsLittleEndian)
                {
                    value = (uint)((data[3] << 24) | (data[2] << 16) | (data[1] << 8) | data[0]);
                }
                else
                {
                    value = (uint)((data[0] << 24) | (data[1] << 16) | (data[2] << 8) | data[3]);
                }
                break;

            default:
                value = null;
                break;
            }
        }
예제 #14
0
 private static Exception ErrorDecoding(CodeContext context, params object[] args)
 {
     return(PythonExceptions.CreateThrowable(SSLError(context), ArrayUtils.Insert("Error decoding PEM-encoded file ", args)));
 }
예제 #15
0
 private static Exception Error(CodeContext /*!*/ context, params object[] args)
 {
     return(PythonExceptions.CreateThrowable((PythonType)PythonContext.GetContext(context).GetModuleState(_ErrorKey), args));
 }
예제 #16
0
파일: mmap.cs 프로젝트: yuhan0/ironpython3
 private static Exception WindowsError(int code)
 {
     return(PythonExceptions.CreateThrowable(PythonExceptions.OSError, code, FormatError(code)));
 }
예제 #17
0
 private static Exception MakeException(CodeContext /*!*/ context, object value)
 {
     return(PythonExceptions.CreateThrowable((PythonType)PythonContext.GetContext(context).GetModuleState("selecterror"), value));
 }
예제 #18
0
        public static HKEYType OpenKey(object key, string subKeyName, [DefaultParameterValue(0)] int res, [DefaultParameterValue(KEY_READ)] int sam)
        {
            HKEYType    rootKey = GetRootKey(key);
            RegistryKey newKey  = null;

            // I'm assuming that the masks that CPy uses are the same as the Win32 API one mentioned here-
            // http://msdn2.microsoft.com/en-us/library/ms724878(VS.85).aspx

            // KEY_WRITE is a combination of KEY_SET_VALUE and KEY_CREATE_SUB_KEY. We'll open with write access
            // if any of this is set.
            // KEY_READ is a combination of KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS and KEY_NOTIFY. We'll open
            // with read access for all of these.

            var nativeRootKey = rootKey.GetKey();

            try {
                if ((sam & KEY_SET_VALUE) == KEY_SET_VALUE ||
                    (sam & KEY_CREATE_SUB_KEY) == KEY_CREATE_SUB_KEY)
                {
                    if (res != 0)
                    {
#if NETSTANDARD
                        newKey = nativeRootKey.OpenSubKey(subKeyName, (RegistryRights)res);
#else
                        newKey = nativeRootKey.OpenSubKey(subKeyName, RegistryKeyPermissionCheck.Default, (RegistryRights)res);
#endif
                    }
                    else
                    {
                        newKey = nativeRootKey.OpenSubKey(subKeyName, true);
                    }
                }
                else if ((sam & KEY_QUERY_VALUE) == KEY_QUERY_VALUE ||
                         (sam & KEY_ENUMERATE_SUB_KEYS) == KEY_ENUMERATE_SUB_KEYS ||
                         (sam & KEY_NOTIFY) == KEY_NOTIFY)
                {
                    if (res != 0)
                    {
#if NETSTANDARD
                        newKey = nativeRootKey.OpenSubKey(subKeyName, (RegistryRights)res);
#else
                        newKey = nativeRootKey.OpenSubKey(subKeyName, RegistryKeyPermissionCheck.ReadSubTree, (RegistryRights)res);
#endif
                    }
                    else
                    {
                        newKey = nativeRootKey.OpenSubKey(subKeyName, false);
                    }
                }
                else
                {
                    throw new Win32Exception("Unexpected mode");
                }
            } catch (SecurityException) {
                throw PythonExceptions.CreateThrowable(PythonExceptions.WindowsError, PythonExceptions._WindowsError.ERROR_ACCESS_DENIED, "Access is denied");
            }


            if (newKey == null)
            {
                throw PythonExceptions.CreateThrowable(PythonExceptions.WindowsError, PythonExceptions._WindowsError.ERROR_FILE_NOT_FOUND, "The system cannot find the file specified");
            }

            return(new HKEYType(newKey));
        }