示例#1
0
 MakeFloat(CodeContext ctx, object obj)
 {
     try
     {
         return Converter.ConvertToDouble(obj);
     }
     catch
     {
         // one of the following fallbacks *might* work
     }
     
     if ((!Builtin.isinstance(obj, TypeCache.PythonType)) &&
         Builtin.hasattr(ctx, obj, "__int__"))
     {
         object probablyInt = PythonCalls.Call(TypeCache.Int32, new object[] {obj});
         return MakeFloat(ctx, probablyInt);
     }
     
     if ((!Builtin.isinstance(obj, TypeCache.PythonType)) &&
         Builtin.hasattr(ctx, obj, "__long__"))
     {
         object probablyLong = PythonCalls.Call(TypeCache.BigInteger, new object[] {obj});
         return MakeFloat(ctx, probablyLong);
     }
     
     throw PythonOps.TypeError("could not make number sufficiently floatesque");
 }
        /// <summary>
        /// Initializes the module for it's first usage.  By default this calls PerformModuleReload with the
        /// the dictionary.
        /// </summary>
        /// <param name="codeContext">The CodeContext for the module.</param>
        /// <param name="optimizedGlobals">A list of globals which have optimize access.  Contains at least all of the global variables reutrned by GetGlobalVariableNames.</param>
        protected internal virtual void Initialize(CodeContext/*!*/ codeContext, Dictionary<string/*!*/, PythonGlobal/*!*/>/*!*/ optimizedGlobals) {
            ContractUtils.RequiresNotNull(codeContext, "codeContext");
            ContractUtils.RequiresNotNull(optimizedGlobals, "globals");

            _codeContext = codeContext;

            PerformModuleReload();
        }
示例#3
0
        public static object get_osfhandle(CodeContext context, int fd) {
            PythonFile pfile = context.LanguageContext.FileManager.GetFileFromId(context.LanguageContext, fd);

            FileStream stream = pfile._stream as FileStream;
            if (stream != null) {
                return stream.Handle.ToPython();
            }
            return -1;
        }
示例#4
0
 MakeUnsignedBigInteger(CodeContext ctx, object obj)
 {
     BigInteger result = MakeBigInteger(ctx, obj);
     
     if (result < 0)
     {
         throw PythonOps.TypeError("cannot make {0} unsigned", result);
     }
     
     return result;
 }
示例#5
0
 public static int setmode(CodeContext context, int fd, int flags) {
     PythonFile pfile = context.LanguageContext.FileManager.GetFileFromId(context.LanguageContext, fd);
     int oldMode;
     if (flags == PythonNT.O_TEXT) {
         oldMode = pfile.SetMode(context, true) ? PythonNT.O_TEXT : PythonNT.O_BINARY;
     } else if (flags == PythonNT.O_BINARY) {
         oldMode = pfile.SetMode(context, false) ? PythonNT.O_TEXT : PythonNT.O_BINARY;
     } else {
         throw PythonOps.ValueError("unknown mode: {0}", flags);
     }
     return oldMode;
 }
示例#6
0
        public string __repr__(CodeContext context) {
            var attrs = from attr in PythonOps.GetAttrNames(context, this)
                        where !attr.ToString().StartsWith("_")
                        select string.Format("{0}={1}",
                            attr,
                            PythonOps.Repr(context, PythonOps.GetBoundAttr(context, this, attr.ToString()))
                        );

            return string.Format("{0}({1})",
                PythonOps.GetPythonTypeName(this),
                string.Join(",", attrs.ToArray())
            );
        }
示例#7
0
 public static PythonSocket.ssl sslwrap(
     CodeContext context,
     PythonSocket.socket socket, 
     bool server_side, 
     [DefaultParameterValue(null)] string keyfile, 
     [DefaultParameterValue(null)] string certfile,
     [DefaultParameterValue(PythonSsl.CERT_NONE)]int certs_mode,
     [DefaultParameterValue(-1)]int protocol,
     [DefaultParameterValue(null)]string cacertsfile) {
     return new PythonSocket.ssl(
         context,
         socket,
         server_side,
         keyfile,
         certfile,
         certs_mode,
         protocol,
         cacertsfile
     );
 }
示例#8
0
        private void BindParameters(CodeContext context, IDictionary args, int num_params_needed)
        {
            for(int i = 1; i <= num_params_needed; ++i)
            {
                string binding_name = Sqlite3.sqlite3_bind_parameter_name(this.st, i);
                if(string.IsNullOrEmpty(binding_name))
                    throw PythonSQLite.MakeProgrammingError("Binding {0} has no name, but you supplied a dictionary (which has only names).".Format(i));

                // remove the leading colon
                binding_name = binding_name.Substring(1);

                if(args.Contains(binding_name))
                    BindParameter(context, i, maybeAdapt(context, args[binding_name]));
                else
                    throw PythonSQLite.MakeProgrammingError("You did not supply a value for binding {0}.".Format(i));
            }
        }
示例#9
0
        internal static PythonDictionary CertificateToPython(CodeContext context, X509Certificate cert, bool complete) {
            var dict = new CommonDictionaryStorage();

            dict.AddNoLock("notAfter", ToPythonDateFormat(cert.GetExpirationDateString()));
            dict.AddNoLock("subject", IssuerToPython(context, cert.Subject));
            if (complete) {
                dict.AddNoLock("notBefore", ToPythonDateFormat(cert.GetEffectiveDateString()));
                dict.AddNoLock("serialNumber", SerialNumberToPython(cert));
                dict.AddNoLock("version", cert.GetCertHashString());
                dict.AddNoLock("issuer", IssuerToPython(context, cert.Issuer));
            }

            return new PythonDictionary(dict);
        }
示例#10
0
 internal static PythonType SSLError(CodeContext/*!*/ context) {
     return (PythonType)PythonContext.GetContext(context).GetModuleState("SSLError");
 }
示例#11
0
 private static Exception ErrorDecoding(CodeContext context, params object[] args) {
     return PythonExceptions.CreateThrowable(SSLError(context), ArrayUtils.Insert("Error decoding PEM-encoded file ", args));
 }
示例#12
0
        internal static X509Certificate2 ReadCertificate(CodeContext context, string filename) {

            string[] lines;
            try {
                lines = File.ReadAllLines(filename);
            } catch (IOException) {
                throw PythonExceptions.CreateThrowable(SSLError(context), "Can't open file ", filename);
            }

            X509Certificate2 cert = null;
            RSACryptoServiceProvider key = null;
            try {
                for (int i = 0; i < lines.Length; i++) {
                    if (lines[i] == "-----BEGIN CERTIFICATE-----") {
                        var certStr = ReadToEnd(lines, ref i, "-----END CERTIFICATE-----");

                        try {
                            cert = new X509Certificate2(Convert.FromBase64String(certStr.ToString()));
                        } catch (Exception e) {
                            throw ErrorDecoding(context, filename, e);
                        }
                    } else if (lines[i] == "-----BEGIN RSA PRIVATE KEY-----") {
                        var keyStr = ReadToEnd(lines, ref i, "-----END RSA PRIVATE KEY-----");

                        try {
                            var keyBytes = Convert.FromBase64String(keyStr.ToString());

                            key = ParsePkcs1DerEncodedPrivateKey(context, filename, keyBytes);
                        } catch (Exception e) {
                            throw ErrorDecoding(context, filename, e);
                        }
                    }
                }
            } catch (InvalidOperationException e) {
                throw ErrorDecoding(context, filename, e.Message);
            }

            if (cert != null) {
                if (key != null) {
                    try {
                        cert.PrivateKey = key;
                    } catch(CryptographicException e) {
                        throw ErrorDecoding(context, filename, "cert and private key are incompatible", e);
                    }
                }
                return cert;
            }
            throw ErrorDecoding(context, filename, "certificate not found");
        }
示例#13
0
 public object CallParamsWithContext(CodeContext context, params object[] arg) {
     return ParamsMethodWithContext(context, arg);
 }
示例#14
0
        internal int Recompile(CodeContext context, object parameters)
        {
            sqlite3_stmt new_st = null;
            string tail = null;

            int rc = Sqlite3.sqlite3_prepare(this.db, this.sql, -1, ref new_st, ref tail);
            if(rc == Sqlite3.SQLITE_OK)
            {
                Statement new_stmt = new Statement(this.st.db, new_st, this.sql, tail);
                new_stmt.BindParameters(context, parameters);

                Sqlite3.sqlite3_finalize(this.st);
                this.st = new_st;
            }

            return rc;
        }
示例#15
0
 public object __le__(CodeContext context, [NotNull] ClosureCell other)
 => PythonOps.RichCompare(context, Value, other.Value, PythonOperationKind.LessThanOrEqual);
示例#16
0
 public string /*!*/ __repr__(CodeContext /*!*/ context)
 => $"<cell at 0x{IdDispenser.GetId(this):X}: {GetContentsRepr()}>";
示例#17
0
 public string /*!*/ __repr__(CodeContext /*!*/ context)
 {
     return(string.Format("<function {0} at {1}>", __name__, PythonOps.HexId(this)));
 }
示例#18
0
 internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value)
 {
     value = instance == null ? (object)this : new Method(this, instance, owner);
     return(true);
 }
示例#19
0
 public object __call__(CodeContext /*!*/ context, [ParamDictionary] IDictionary <object, object> dict, params object[] args)
 {
     return(PythonCalls.CallWithKeywordArgs(context, this, args, dict));
 }
示例#20
0
 public object __call__(CodeContext /*!*/ context, params object[] args)
 {
     return(PythonCalls.Call(context, this, args));
 }
示例#21
0
 public string /*!*/ __repr__(CodeContext /*!*/ context)
 {
     return(string.Format("slice({0}, {1}, {2})", PythonOps.Repr(context, start), PythonOps.Repr(context, stop), PythonOps.Repr(context, step)));
 }
示例#22
0
        private void BindParameter(CodeContext context, int index, object arg)
        {
            int rc;
            if(arg == null)
                rc = Sqlite3.sqlite3_bind_null(st, index);
            else if(arg is int)
                rc = Sqlite3.sqlite3_bind_int(st, index, (int)arg);
            else if(arg is bool)
                rc = Sqlite3.sqlite3_bind_int(st, index, (bool)arg ? 1 : 0);
            else if(arg is long)
                rc = Sqlite3.sqlite3_bind_int64(st, index, (long)arg);
            else if(arg is Microsoft.Scripting.Math.BigInteger)
                rc = Sqlite3.sqlite3_bind_int64(st, index, ((Microsoft.Scripting.Math.BigInteger)arg).ToInt64());
#if FEATURE_NUMERICS
            else if (arg is System.Numerics.BigInteger)
                rc = Sqlite3.sqlite3_bind_int64(st, index, (long)((System.Numerics.BigInteger)arg));
#endif
            else if(arg is float)
                rc = Sqlite3.sqlite3_bind_double(st, index, (float)arg);
            else if(arg is double)
                rc = Sqlite3.sqlite3_bind_double(st, index, (double)arg);
            else if(arg is string)
                rc = Sqlite3.sqlite3_bind_text(st, index, (string)arg, -1, Sqlite3.SQLITE_TRANSIENT);
            else if(arg is byte[])
                rc = Sqlite3.sqlite3_bind_blob(this.st, index, (byte[])arg, -1, Sqlite3.SQLITE_TRANSIENT);
            else if(arg is PythonBuffer)
            {
                //TODO: see if there is a better way to do this
                PythonBuffer buffer = (PythonBuffer)arg;
                string s = buffer.__getslice__(0, null).ToString();
                byte[] bytes = PythonSQLite.Latin1.GetBytes(s);

                rc = Sqlite3.sqlite3_bind_blob(this.st, index, bytes, -1, Sqlite3.SQLITE_TRANSIENT);
            }
            else
                throw PythonSQLite.MakeInterfaceError("Unable to bind parameter {0} - unsupported type {1}".Format(index, arg.GetType()));

            if(rc != Sqlite3.SQLITE_OK)
                throw PythonSQLite.MakeInterfaceError("Unable to bind parameter {0}: {1}".Format(index, Sqlite3.sqlite3_errmsg(db)));
        }
示例#23
0
        private bool needsAdaptation(CodeContext context, object value)
        {
            // TODO The check for primitive types could probably be cached like pysqlite does
            if(value == null ||
                value is int ||
                value is bool ||
                value is long ||
                value is Microsoft.Scripting.Math.BigInteger ||
                value is float ||
                value is double ||
                value is string ||
                value is byte[] ||
                value is PythonBuffer)
            {
                object proto = DynamicHelpers.GetPythonTypeFromType(typeof(PythonSQLite.PrepareProtocol));
                object type = DynamicHelpers.GetPythonType(value);

                object key = new PythonTuple(new[] { type, proto });

                return PythonSQLite.adapters.ContainsKey(key);
            }
            else
            {
                return true;
            }
        }
示例#24
0
 public object __gt__(CodeContext context, [NotNull] ClosureCell other)
 => PythonOps.RichCompare(context, Value, other.Value, PythonOperationKind.GreaterThan);
示例#25
0
 public virtual object ParamsIntMethodWithContext(CodeContext context, params int[] args) {
     Debug.Assert(this != null && this is StrangeOverrides);
     return args;
 }
示例#26
0
 public object Call(CodeContext /*!*/ context, [ParamDictionary] IDictionary <object, object> kwArgs, params object[] args)
 {
     return(context.LanguageContext.CallWithKeywords(this, args, kwArgs));
 }
示例#27
0
 public string __repr__(CodeContext context)
 {
     return(String.Format("<memory at {0}>", PythonOps.Id(this)));
 }
示例#28
0
 public void SetMemberAfter(CodeContext context, string name, object value)
 {
     TypeCache.Method.SetMember(context, this, name, value);
 }
示例#29
0
        private static RSACryptoServiceProvider ParsePkcs1DerEncodedPrivateKey(CodeContext context, string filename, byte[] x) {
            // http://tools.ietf.org/html/rfc3447#appendix-A.1.2
            // RSAPrivateKey ::= SEQUENCE {
            //   version           Version,
            //   modulus           INTEGER,  -- n
            //   publicExponent    INTEGER,  -- e
            //   privateExponent   INTEGER,  -- d
            //   prime1            INTEGER,  -- p
            //   prime2            INTEGER,  -- q
            //   exponent1         INTEGER,  -- d mod (p-1)
            //   exponent2         INTEGER,  -- d mod (q-1)
            //   coefficient       INTEGER,  -- (inverse of q) mod p
            //   otherPrimeInfos   OtherPrimeInfos OPTIONAL
            // }

            // read header for sequence
            if ((x[0] & ClassMask) != ClassUniversal) {
                throw ErrorDecoding(context, filename, "failed to find universal class");
            } else if ((x[0] & NumberMask) != UnivesalSequence) {
                throw ErrorDecoding(context, filename, "failed to read sequence header");
            }

            // read length of sequence
            int offset = 1;
            int len = ReadLength(x, ref offset);

            // read version
            int version = ReadUnivesalInt(x, ref offset);
            if (version != 0) {
                // unsupported version
                throw new InvalidOperationException(String.Format("bad vesion: {0}", version));
            }

            // read in parameters and initialize provider
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
            RSAParameters parameters = new RSAParameters();

            parameters.Modulus = ReadUnivesalIntAsBytes(x, ref offset);
            parameters.Exponent = ReadUnivesalIntAsBytes(x, ref offset);
            parameters.D = ReadUnivesalIntAsBytes(x, ref offset);
            parameters.P = ReadUnivesalIntAsBytes(x, ref offset);
            parameters.Q = ReadUnivesalIntAsBytes(x, ref offset);
            parameters.DP = ReadUnivesalIntAsBytes(x, ref offset);
            parameters.DQ = ReadUnivesalIntAsBytes(x, ref offset);
            parameters.InverseQ = ReadUnivesalIntAsBytes(x, ref offset);
            
            provider.ImportParameters(parameters);            
            return provider;
        }
示例#30
0
 public void DeleteMember(CodeContext context, string name)
 {
     TypeCache.Method.DeleteMember(context, this, name);
 }
示例#31
0
 public object Call(CodeContext /*!*/ context, params object[] args)
 {
     return(context.LanguageContext.CallSplat(this, args));
 }
示例#32
0
 private static PythonInvokeBinder GetSelfBinder(Binding.PythonInvokeBinder binder, CodeContext context)
 {
     return(context.LanguageContext.Invoke(
                new CallSignature(ArrayUtils.Insert(new Argument(ArgumentType.Simple), binder.Signature.GetArgumentInfos()))
                ));
 }
示例#33
0
        public static PythonDictionary _test_decode_cert(CodeContext context, string filename, [DefaultParameterValue(false)]bool complete) {
            var cert = ReadCertificate(context, filename);

            return CertificateToPython(context, cert, complete);
        }
示例#34
0
 public static PythonModule /*!*/ __new__(CodeContext /*!*/ context, PythonType /*!*/ cls, [ParamDictionary] IDictionary <object, object> kwDict0, params object[] /*!*/ args\u00F8)
 {
     return(__new__(context, cls, args\u00F8));
 }
示例#35
0
        public void BindParameters(CodeContext context, object parameters)
        {
            if(bound)
                this.ClearParameters();

            int num_params_needed = Sqlite3.sqlite3_bind_parameter_count(this.st);

            if(parameters == null)
            {
                if(num_params_needed > 0)
                    throw PythonSQLite.MakeProgrammingError("parameters are required but not specified.");
                else
                    return;
            }

            if(parameters is IDictionary)
                BindParameters(context, (IDictionary)parameters, num_params_needed);
            else if(parameters is IList)
                BindParameters(context, (IList)parameters, num_params_needed);
            else
                throw PythonSQLite.MakeProgrammingError("unknown parameter type");

            bound = true;
        }
示例#36
0
 IList <object> IPythonMembersList.GetMemberNames(CodeContext context)
 {
     return(new List <object>(__dict__.Keys));
 }
示例#37
0
        private void BindParameters(CodeContext context, IList args, int num_params_needed)
        {
            if(num_params_needed != args.Count)
                throw PythonSQLite.MakeProgrammingError("Incorrect number of bindings supplied.");

            for(int i = 0; i < args.Count; ++i)
            {
                BindParameter(context, i + 1, maybeAdapt(context, args[i]));
            }
        }
示例#38
0
 public static object __new__(CodeContext context, PythonType type, [NotNull] IReversible o)
 {
     return(o.__reversed__());
 }
示例#39
0
 private object maybeAdapt(CodeContext context, object value)
 {
     return needsAdaptation(context, value) ? adaptValue(context, value) : value;
 }
 public object view(CodeContext context, string view_name, object model)
 {
     var view = View(view_name, model);
     return view;
 }
示例#41
0
        private object adaptValue(CodeContext context, object value)
        {
            object proto = DynamicHelpers.GetPythonTypeFromType(typeof(PythonSQLite.PrepareProtocol));
            object type = DynamicHelpers.GetPythonType(value);

            object key = new PythonTuple(new[] { type, proto });

            object adapter;
            if(PythonSQLite.adapters.TryGetValue(key, out adapter))
            {
                object adapted = PythonCalls.Call(context, adapter, value);
                return adapted;
            }

            // TODO: Use proto? Any value whatsoever?

            object conform;
            if(context.LanguageContext.Operations.TryGetMember(value, "__conform__", out conform))
            {
                object adapted = PythonCalls.Call(context, conform, proto);
                if(adapted != null)
                {
                    return adapted;
                }
            }

            return value;
        }
示例#42
0
 internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value)
 {
     owner = CheckGetArgs(context, instance, owner);
     value = new Method(_func, owner, DynamicHelpers.GetPythonType(owner));
     return(true);
 }
示例#43
0
 public virtual object SomeMethodWithContext(CodeContext context, object arg) {
     Debug.Assert(this != null && this is StrangeOverrides);
     return arg;
 }
示例#44
0
 private static PythonTuple IssuerToPython(CodeContext context, string issuer) {
     var split = issuer.Split(',');
     object[] res = new object[split.Length];
     for(int i = 0; i<split.Length; i++) {
         res[i] = PythonTuple.MakeTuple(
             IssuerFieldToPython(context, split[i].Trim())
         );
         
     }
     return PythonTuple.MakeTuple(res);
 }
示例#45
0
 public object CallWithContext(CodeContext context, object arg) {
     return SomeMethodWithContext(context, arg);
 }
示例#46
0
        private static PythonTuple IssuerFieldToPython(CodeContext context, string p) {
            if (String.Compare(p, 0, "CN=", 0, 3) == 0) {
                return PythonTuple.MakeTuple("commonName", p.Substring(3));
            } else if (String.Compare(p, 0, "OU=", 0, 3) == 0) {
                return PythonTuple.MakeTuple("organizationalUnitName", p.Substring(3));
            } else if (String.Compare(p, 0, "O=", 0, 2) == 0) {
                return PythonTuple.MakeTuple("organizationName", p.Substring(2));
            } else if (String.Compare(p, 0, "L=", 0, 2) == 0) {
                return PythonTuple.MakeTuple("localityName", p.Substring(2));
            } else if (String.Compare(p, 0, "S=", 0, 2) == 0) {
                return PythonTuple.MakeTuple("stateOrProvinceName", p.Substring(2));
            } else if (String.Compare(p, 0, "C=", 0, 2) == 0) {
                return PythonTuple.MakeTuple("countryName", p.Substring(2));
            } else if (String.Compare(p, 0, "E=", 0, 2) == 0) {
                return PythonTuple.MakeTuple("email", p.Substring(2));
            }

            throw PythonExceptions.CreateThrowable(SSLError(context), "Unknown field: ", p);
        }
示例#47
0
 public object CallIntParamsWithContext(CodeContext  context, params int[] arg) {
     return ParamsIntMethodWithContext(context, arg);
 }
示例#48
0
        Binding.FastBindResult <T> Binding.IFastInvokable.MakeInvokeBinding <T>(CallSite <T> site, Binding.PythonInvokeBinder binder, CodeContext context, object[] args)
        {
            // TODO: We can process any signature that isn't * or ** args for the 1st argument
            if (binder.Signature.IsSimple)
            {
                BaseMethodBinding binding = null;

                if (__self__ == null)
                {
                    if (args.Length != 0)
                    {
                        binding = GetMethodBinding <T>(binder, GetTypeArgsSelfless <T>(), binding);

                        if (binding != null)
                        {
                            return(new FastBindResult <T>(
                                       (T)(object)binding.GetSelflessTarget(),
                                       true
                                       ));
                        }
                    }
                }
                else
                {
                    var selfBinder = GetSelfBinder(binder, context);

                    if (args.Length == 0)
                    {
                        binding = new MethodBinding(selfBinder);
                    }
                    else
                    {
                        binding = GetMethodBinding <T>(selfBinder, GetTypeArgs <T>(), binding);
                    }

                    if (binding != null)
                    {
                        return(new FastBindResult <T>(
                                   (T)(object)binding.GetSelfTarget(),
                                   true
                                   ));
                    }
                }
            }
            return(new Binding.FastBindResult <T>());
        }
 public object view(CodeContext context)
 {
     var view = View();
     return view;
 }
示例#50
0
 public static object __new__(CodeContext context, [NotNull] PythonType cls, [NotNull] string @string)
 {
     throw PythonOps.TypeError("string argument without an encoding");
 }