Exemplo n.º 1
0
        ///////////////////////////////////////////////////////////////////////

        private ReturnCode MaybeUnloadModule(
            IModule module,
            ref Result error
            )
        {
            lock (syncRoot) /* TRANSACTIONAL */
            {
                if (this.module == null)
                {
                    return(ReturnCode.Ok);
                }

                if (Object.ReferenceEquals(module, this.module))
                {
                    return(ReturnCode.Ok);
                }

                if (moduleLoaded > 0)
                {
                    if (RuntimeOps.UnloadNativeModule(
                            this.module, ref moduleLoaded,
                            ref error) != ReturnCode.Ok)
                    {
                        return(ReturnCode.Error);
                    }
                }

                this.module = null;
            }

            return(ReturnCode.Ok);
        }
Exemplo n.º 2
0
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if ((arguments.Count == 1) || (arguments.Count == 2))
                    {
                        if (arguments.Count == 2)
                        {
                            string  channelId = arguments[1];
                            Channel channel   = interpreter.GetChannel(channelId, ref result);

                            if (channel != null)
                            {
                                //
                                // STUB: This does not actually work.
                                //
                                result = String.Empty;
                                code   = ReturnCode.Ok;
                            }
                            else
                            {
                                code = ReturnCode.Error;
                            }
                        }
                        else
                        {
                            result = RuntimeOps.GetCurrentProcessId();
                            code   = ReturnCode.Ok;
                        }
                    }
                    else
                    {
                        result = "wrong # args: should be \"pid ?channelId?\"";
                        code   = ReturnCode.Error;
                    }
                }
                else
                {
                    result = "invalid argument list";
                    code   = ReturnCode.Error;
                }
            }
            else
            {
                result = "invalid interpreter";
                code   = ReturnCode.Error;
            }

            return(code);
        }
Exemplo n.º 3
0
        ///////////////////////////////////////////////////////////////////////

        #region Private Methods
        //
        // NOTE: This method assumes the lock is held.
        //
        private ReturnCode UnloadModule(
            ref int loaded,
            ref Result error
            )
        {
            return(RuntimeOps.UnloadNativeModule(
                       module, ref loaded, ref error));
        }
Exemplo n.º 4
0
        ///////////////////////////////////////////////////////////////////////

        #region Callback Methods
        private ReturnCode InterruptCallback(
            Interpreter interpreter, /* NOTE: Parent interpreter. */
            InterruptType interruptType,
            IClientData clientData,
            ref Result error
            ) /* throw */
        {
            //
            // NOTE: If the are no callback arguments configured, just skip it
            //       and return success.
            //
            StringList arguments = CallbackArguments;

            if (arguments == null) /* NOTE: Disabled? */
            {
                return(ReturnCode.Ok);
            }

            Interpreter debugInterpreter = this.interpreter;

            if (debugInterpreter == null)
            {
                error = "debugger interpreter not available";
                return(ReturnCode.Error);
            }

            //
            // NOTE: *WARNING* This is a cross-interpreter call, do NOT dispose
            //       the parent interpreter because we do not own it.  This is
            //       guaranteed by using the NoDispose object flag (indirectly)
            //       here.
            //
            ICallback callback = CommandCallback.Create(
                MarshalFlags.Default, CallbackFlags.Default,
                ObjectFlags.Callback, ByRefArgumentFlags.None,
                debugInterpreter, clientData, null, new StringList(
                    arguments), ref error);

            if (callback == null)
            {
                return(ReturnCode.Error);
            }

            try
            {
                callback.FireEventHandler(this,
                                          RuntimeOps.GetInterruptEventArgs(interpreter,
                                                                           interruptType, clientData) as EventArgs);

                return(ReturnCode.Ok);
            }
            catch (Exception e)
            {
                error = e;
            }

            return(ReturnCode.Error);
        }
Exemplo n.º 5
0
        ///////////////////////////////////////////////////////////////////////

        #region IExecute Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            return(RuntimeOps.GetVersion(ref result));
        }
Exemplo n.º 6
0
        ///////////////////////////////////////////////////////////////////////

        /* System.Threading.ThreadStart */
        public void ThreadStart()
        {
            CheckDisposed();

            try
            {
#if NATIVE && WINDOWS
                RuntimeOps.RefreshNativeStackPointers();
#endif

                if (threadStart != null)
                {
                    threadStart();
                }
                else if (parameterizedThreadStart != null)
                {
                    parameterizedThreadStart(null);
                }
                else
                {
                    TraceOps.DebugTrace(
                        "ThreadStart: no delegates available",
                        typeof(EngineThread).Name,
                        TracePriority.ThreadError);
                }
            }
            catch (ThreadAbortException e)
            {
                Thread.ResetAbort();

                TraceOps.DebugTrace(
                    e, typeof(EngineThread).Name,
                    TracePriority.ThreadError);
            }
            catch (ThreadInterruptedException e)
            {
                TraceOps.DebugTrace(
                    e, typeof(EngineThread).Name,
                    TracePriority.ThreadError);
            }
            catch (Exception e)
            {
                TraceOps.DebugTrace(
                    e, typeof(EngineThread).Name,
                    TracePriority.ThreadError);
            }
            finally
            {
                if (interpreter != null)
                {
                    interpreter.MaybeDisposeThread();
                }
            }
        }
Exemplo n.º 7
0
        ///////////////////////////////////////////////////////////////////////

        private static void UnsetNativeDelegates()
        {
            lock (syncRoot) /* TRANSACTIONAL */
            {
                nativeGetVersion     = null;
                nativeAllocateMemory = null;
                nativeFreeMemory     = null;
                nativeFreeElements   = null;
                nativeSplitList      = null;
                nativeJoinList       = null;

                RuntimeOps.UnsetNativeDelegates(nativeDelegates, null);
            }
        }
Exemplo n.º 8
0
        ///////////////////////////////////////////////////////////////////////

        public static ReturnCode SelectRandomValue(
            Interpreter interpreter, /* in: may be NULL. */
            Array array,             /* in */
            ref object value,        /* out */
            ref Result error         /* out */
            )
        {
            if (array == null)
            {
                error = "invalid array";
                return(ReturnCode.Error);
            }

            if (array.Rank != 1)
            {
                error = "array must be one-dimensional";
                return(ReturnCode.Error);
            }

            if (array.Length == 0)
            {
                error = "array cannot be empty";
                return(ReturnCode.Error);
            }

            try
            {
                ulong randomNumber;

                if (interpreter != null)
                {
                    randomNumber = interpreter.GetRandomNumber(); /* throw */
                }
                else
                {
                    randomNumber = RuntimeOps.GetRandomNumber(); /* throw */
                }
                int index = ConversionOps.ToInt(randomNumber %
                                                ConversionOps.ToULong(array.LongLength));

                value = array.GetValue(index); /* throw */
                return(ReturnCode.Ok);
            }
            catch (Exception e)
            {
                error = e;
            }

            return(ReturnCode.Error);
        }
Exemplo n.º 9
0
        ///////////////////////////////////////////////////////////////////////

        public bool MaybeAddOrReplace(
            FindFlags flags, /* in */
            string key,      /* in */
            TclBuild value,  /* in */
            ref Result error /* out */
            )
        {
            if (key == null)
            {
                error = String.Format(
                    "can't add Tcl build file {0}: invalid key",
                    FormatOps.TclBuildFileName(value));

                return(false);
            }

            if (FlagOps.HasFlags(flags, FindFlags.TrustedOnly, true) &&
                ((value == null) ||
                 !RuntimeOps.IsFileTrusted(value.FileName, IntPtr.Zero)))
            {
                error = String.Format(
                    "can't add Tcl build file {0}: not trusted",
                    FormatOps.TclBuildFileName(value));

                return(false);
            }

            if (!this.ContainsKey(key))
            {
                this.Add(key, value);
                return(true);
            }

            if (FlagOps.HasFlags(
                    flags, FindFlags.OverwriteBuilds, true))
            {
                this[key] = value;
                return(true);
            }

            error = String.Format(
                "can't add Tcl build file {0}: already present",
                FormatOps.TclBuildFileName(value));

            return(false);
        }
Exemplo n.º 10
0
        ///////////////////////////////////////////////////////////////////////

        private static bool SetNativeDelegates(
            ref Result error
            )
        {
            lock (syncRoot) /* TRANSACTIONAL */
            {
                if ((RuntimeOps.SetNativeDelegates(
                         "utility API", nativeModule, nativeDelegates,
                         null, ref error) == ReturnCode.Ok) &&
                    (nativeDelegates != null))
                {
                    try
                    {
                        nativeGetVersion = (Eagle_GetVersion)
                                           nativeDelegates[typeof(Eagle_GetVersion)];

                        nativeAllocateMemory = (Eagle_AllocateMemory)
                                               nativeDelegates[typeof(Eagle_AllocateMemory)];

                        nativeFreeMemory = (Eagle_FreeMemory)
                                           nativeDelegates[typeof(Eagle_FreeMemory)];

                        nativeFreeElements = (Eagle_FreeElements)
                                             nativeDelegates[typeof(Eagle_FreeElements)];

                        nativeSplitList = (Eagle_SplitList)
                                          nativeDelegates[typeof(Eagle_SplitList)];

                        nativeJoinList = (Eagle_JoinList)
                                         nativeDelegates[typeof(Eagle_JoinList)];

                        return(true);
                    }
                    catch (Exception e)
                    {
                        error = e;
                    }
                }
            }

            return(false);
        }
Exemplo n.º 11
0
        ///////////////////////////////////////////////////////////////////////

        public void ExitLock(
            ref bool locked
            )
        {
            if (RuntimeOps.ShouldCheckDisposedOnExitLock(locked)) /* EXEMPT */
            {
                CheckDisposed();
            }

            if (syncRoot == null)
            {
                return;
            }

            if (locked)
            {
                Monitor.Exit(syncRoot);
                locked = false;
            }
        }
Exemplo n.º 12
0
        ///////////////////////////////////////////////////////////////////////

        public static IntPtr GetOutputHandle(
            ref Result error
            )
        {
            bool isMono = CommonOps.Runtime.IsMono();
            Type type   = isMono ? MonoIoType : ConsoleType;

            if (type == null)
            {
                error = "invalid system console type";
                return(IntPtr.Zero);
            }

            //
            // HACK: Because the System.Console object in the .NET Framework
            //       provides no means to query the underlying input/output
            //       handles, we must do it here by force.
            //
            try
            {
                IntPtr handle = (IntPtr)type.InvokeMember(
                    isMono ? "ConsoleOutput" : "ConsoleOutputHandle",
                    isMono ? MarshalOps.PublicStaticGetPropertyBindingFlags :
                    MarshalOps.PrivateStaticGetPropertyBindingFlags, null,
                    null, null);

                if (!RuntimeOps.IsValidHandle(handle))
                {
                    error = "invalid console output handle";
                }

                return(handle);
            }
            catch (Exception e)
            {
                error = e;
            }

            return(IntPtr.Zero);
        }
Exemplo n.º 13
0
        ///////////////////////////////////////////////////////////////////////

        private static string GetNativeLibraryFileName(
            Interpreter interpreter /* NOT USED */
            )
        {
            string path = CommonOps.Environment.GetVariable(
                EnvVars.UtilityPath);

            if (!String.IsNullOrEmpty(path))
            {
                if (File.Exists(path))
                {
                    return(path);
                }

                if (Directory.Exists(path))
                {
                    string fileName = PathOps.CombinePath(
                        null, path, DllName.Utility);

                    if (File.Exists(fileName))
                    {
                        return(fileName);
                    }

                    //
                    // TODO: Is this strictly necessary here?  It is known
                    //       at this point that this file does not exist.
                    //       Setting the path here only controls the result
                    //       returned in non-strict mode (below).
                    //
                    path = fileName;
                }

                //
                // NOTE: If the environment variable was set and the utility
                //       library could not be found, force an invalid result
                //       to be returned.  This ends up skipping the standard
                //       automatic utility library detection logic.
                //
                lock (syncRoot)
                {
                    return(strictPath ? null : path);
                }
            }

            //
            // HACK: If the processor architecture ends up being "AMD64", we
            //       want it to be "x64" instead, to match the platform name
            //       used by the native utility library project itself.
            //
            string processorName = PlatformOps.GetAlternateProcessorName(
                RuntimeOps.GetProcessorArchitecture(), true, false);

            if (processorName != null)
            {
                path = PathOps.CombinePath(
                    null, GlobalState.GetAssemblyPath(), processorName,
                    DllName.Utility);

                if (File.Exists(path))
                {
                    return(path);
                }
            }

            path = PathOps.CombinePath(
                null, GlobalState.GetAssemblyPath(), DllName.Utility);

            if (File.Exists(path))
            {
                return(path);
            }

            lock (syncRoot)
            {
                return(strictPath ? null : path);
            }
        }
Exemplo n.º 14
0
 public static object Int32ToObject(int value)
 {
     return(RuntimeOps.Int32ToObject(value));
 }
Exemplo n.º 15
0
        /// <summary>
        ///   This is the constructor used by the core library to create an
        ///   instance of the plugin, passing the necessary data to be used
        ///   for initializing the plugin.
        /// </summary>
        ///
        /// <param name="pluginData">
        ///   An instance of the plugin data component used to hold the data
        ///   necessary to fully initialize the plugin instance.  This
        ///   parameter may be null.  Derived plugins are free to override
        ///   this constructor; however, they are very strongly encouraged to
        ///   call this constructor (i.e. the base class constructor) in that
        ///   case.
        /// </param>
        public Default(
            IPluginData pluginData
            )
        {
            kind = IdentifierKind.Plugin;

            //
            // VIRTUAL: Id of the deepest derived class.
            //
            id = AttributeOps.GetObjectId(this);

            //
            // VIRTUAL: Group of the deepest derived class.
            //
            group = AttributeOps.GetObjectGroup(this);

            //
            // NOTE: Is the supplied plugin data valid?
            //
            if (pluginData != null)
            {
                EntityOps.MaybeSetGroup(
                    this, pluginData.Group);

                name         = pluginData.Name;
                description  = pluginData.Description;
                flags        = pluginData.Flags;
                clientData   = pluginData.ClientData;
                version      = pluginData.Version;
                uri          = pluginData.Uri;
                appDomain    = pluginData.AppDomain;
                assembly     = pluginData.Assembly;
                assemblyName = pluginData.AssemblyName;
                fileName     = pluginData.FileName;
                typeName     = pluginData.TypeName;
            }

            //
            // NOTE: Are we going to use their command list or create an
            //       entirely new list?
            //
            if ((pluginData != null) && (pluginData.Commands != null))
            {
                commands = pluginData.Commands;
            }
            else
            {
                commands = new CommandDataList();
            }

            //
            // NOTE: Are we going to use their policy list or create an
            //       entirely new list?
            //
            if ((pluginData != null) && (pluginData.Policies != null))
            {
                policies = pluginData.Policies;
            }
            else
            {
                policies = new PolicyDataList();
            }

            //
            // NOTE: Are we going to use their command tokens or create an
            //       entirely new list?
            //
            if ((pluginData != null) && (pluginData.CommandTokens != null))
            {
                commandTokens = pluginData.CommandTokens;
            }
            else
            {
                commandTokens = new LongList();
            }

            //
            // NOTE: Are we going to use their command tokens or create an
            //       entirely new list?
            //
            if ((pluginData != null) && (pluginData.FunctionTokens != null))
            {
                functionTokens = pluginData.FunctionTokens;
            }
            else
            {
                functionTokens = new LongList();
            }

            //
            // NOTE: Are we going to use their policy tokens or create an
            //       entirely new list?
            //
            if ((pluginData != null) && (pluginData.PolicyTokens != null))
            {
                policyTokens = pluginData.PolicyTokens;
            }
            else
            {
                policyTokens = new LongList();
            }

            //
            // NOTE: Are we going to use their trace tokens or create an
            //       entirely new list?
            //
            if ((pluginData != null) && (pluginData.TraceTokens != null))
            {
                traceTokens = pluginData.TraceTokens;
            }
            else
            {
                traceTokens = new LongList();
            }

            //
            // NOTE: Are we going to use the resource manager they specified or
            //       create a new one based on the plugin name and assembly?
            //
            if ((pluginData != null) && (pluginData.ResourceManager != null))
            {
                resourceManager = pluginData.ResourceManager;
            }
            else
            {
                //
                // NOTE: If the assembly is null we are probably loaded into an
                //       isolated application domain.  Therefore, in that case,
                //       and only in that case, since we are executing in the
                //       target application domain, load the assembly based on
                //       the assembly name and then use that to create the
                //       resource manager.  However, do not simply set the
                //       assembly field of this plugin to any non-null value
                //       because we do not want to cause issues with the
                //       interpreter plugin manager later.  Also, skip attempts
                //       to create a resource manager if the NoResources flag
                //       has been set on the plugin.
                //
                if (!FlagOps.HasFlags(flags, PluginFlags.NoResources, true))
                {
                    if (assembly != null)
                    {
                        resourceManager = RuntimeOps.NewResourceManager(
                            assembly);
                    }
                    else if (assemblyName != null)
                    {
                        resourceManager = RuntimeOps.NewResourceManager(
                            assemblyName);
                    }
                }
            }

            //
            // NOTE: Are we going to use the auxiliary data they specified or
            //       create a new one?
            //
            if ((pluginData != null) && (pluginData.AuxiliaryData != null))
            {
                auxiliaryData = pluginData.AuxiliaryData;
            }
            else
            {
                if (!FlagOps.HasFlags(
                        flags, PluginFlags.NoAuxiliaryData, true))
                {
                    auxiliaryData = new ObjectDictionary();
                }
            }

            //
            // NOTE: Also store the plugin token (which may be zero at this
            //       point).
            //
            if (pluginData != null)
            {
                token = pluginData.Token;
            }
        }
Exemplo n.º 16
0
        ///////////////////////////////////////////////////////////////////////

        private static bool LoadNativeLibrary(
            Interpreter interpreter
            )
        {
            lock (syncRoot) /* TRANSACTIONAL */
            {
                if (nativeModule != IntPtr.Zero)
                {
                    return(true);
                }

                try
                {
                    string fileName = GetNativeLibraryFileName(interpreter);

                    if (!String.IsNullOrEmpty(fileName))
                    {
                        TraceOps.DebugTrace(String.Format(
                                                "LoadNativeLibrary: using file name {0}",
                                                FormatOps.WrapOrNull(fileName)),
                                            typeof(NativeUtility).Name,
                                            TracePriority.NativeDebug);
                    }
                    else
                    {
                        TraceOps.DebugTrace(String.Format(
                                                "LoadNativeLibrary: file name {0} is invalid",
                                                FormatOps.WrapOrNull(fileName)),
                                            typeof(NativeUtility).Name,
                                            TracePriority.NativeError);

                        return(false);
                    }

                    //
                    // NOTE: Check if the native library file name actually
                    //       exists.  If not, do nothing and return failure
                    //       after tracing the issue.
                    //
                    if (!File.Exists(fileName))
                    {
                        TraceOps.DebugTrace(String.Format(
                                                "LoadNativeLibrary: file name {0} does not exist",
                                                FormatOps.WrapOrNull(fileName)),
                                            typeof(NativeUtility).Name,
                                            TracePriority.NativeError);

                        return(false);
                    }

                    //
                    // BUGFIX: Stop loading "untrusted" native libraries
                    //         when running with a "trusted" core library.
                    //
                    if (!RuntimeOps.ShouldLoadNativeLibrary(fileName))
                    {
                        TraceOps.DebugTrace(String.Format(
                                                "LoadNativeLibrary: file name {0} is untrusted",
                                                FormatOps.WrapOrNull(fileName)),
                                            typeof(NativeUtility).Name,
                                            TracePriority.NativeError);

                        return(false);
                    }

                    int lastError;

                    nativeModule = NativeOps.LoadLibrary(
                        fileName, out lastError); /* throw */

                    if (nativeModule != IntPtr.Zero)
                    {
                        InitializeNativeDelegates(true);

                        Result error = null;

                        if (SetNativeDelegates(ref error))
                        {
                            nativeFileName = fileName;

                            TraceOps.DebugTrace(
                                "LoadNativeLibrary: successfully loaded",
                                typeof(NativeUtility).Name,
                                TracePriority.NativeDebug);

                            return(true);
                        }
                        else
                        {
                            TraceOps.DebugTrace(String.Format(
                                                    "LoadNativeLibrary: file name {0} delegate " +
                                                    "setup error: {1}",
                                                    FormatOps.WrapOrNull(fileName), error),
                                                typeof(NativeUtility).Name,
                                                TracePriority.NativeError);

                            /* IGNORED */
                            UnloadNativeLibrary(interpreter);
                        }
                    }
                    else
                    {
                        TraceOps.DebugTrace(String.Format(
                                                "LoadLibrary({1}) failed with error {0}: {2}",
                                                lastError, FormatOps.WrapOrNull(fileName),
                                                NativeOps.GetDynamicLoadingError(lastError).Trim()),
                                            typeof(NativeUtility).Name,
                                            TracePriority.NativeError);
                    }
                }
                catch (Exception e)
                {
                    TraceOps.DebugTrace(
                        e, typeof(NativeUtility).Name,
                        TracePriority.NativeError);
                }

                return(false);
            }
        }
Exemplo n.º 17
0
        public object ToObject()
        {
            // Check the simple case upfront
            if (IsEmpty)
            {
                return(null);
            }

            switch (VariantType)
            {
            case VarEnum.VT_NULL: return(DBNull.Value);

                #region Generated Variant ToObject

            // *** BEGIN GENERATED CODE ***
            // generated by function: gen_ToObject from: generate_comdispatch.py

            case VarEnum.VT_I1: return(AsI1);

            case VarEnum.VT_I2: return(AsI2);

            case VarEnum.VT_I4: return(RuntimeOps.Int32ToObject(AsI4));

            case VarEnum.VT_I8: return(AsI8);

            case VarEnum.VT_UI1: return(AsUi1);

            case VarEnum.VT_UI2: return(AsUi2);

            case VarEnum.VT_UI4: return(AsUi4);

            case VarEnum.VT_UI8: return(AsUi8);

            case VarEnum.VT_INT: return(AsInt);

            case VarEnum.VT_UINT: return(AsUint);

            case VarEnum.VT_BOOL: return(AsBool ? RuntimeOps.True : RuntimeOps.False);

            case VarEnum.VT_ERROR: return(AsError);

            case VarEnum.VT_R4: return(AsR4);

            case VarEnum.VT_R8: return(AsR8);

            case VarEnum.VT_DECIMAL: return(AsDecimal);

            case VarEnum.VT_CY: return(AsCy);

            case VarEnum.VT_DATE: return(AsDate);

            case VarEnum.VT_BSTR: return(AsBstr);

            case VarEnum.VT_UNKNOWN: return(AsUnknown);

            case VarEnum.VT_DISPATCH: return(AsDispatch);

            case VarEnum.VT_VARIANT: return(AsVariant);

                // *** END GENERATED CODE ***

                #endregion

            default:
                return(AsVariant);
            }
        }
Exemplo n.º 18
0
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if (arguments.Count >= 2)
                    {
                        OptionDictionary options = new OptionDictionary(
                            new IOption[] {
                            new Option(null, OptionFlags.None, Index.Invalid,
                                       Index.Invalid, "-debug", null),                  // simple switch
                            new Option(null, OptionFlags.None, Index.Invalid,
                                       Index.Invalid, "-commandline", null),            // simple switch
                            new Option(null, OptionFlags.None, Index.Invalid,
                                       Index.Invalid, "-dequote", null),                // simple switch
                            new Option(null, OptionFlags.None, Index.Invalid,
                                       Index.Invalid, "-quoteall", null),               // simple switch
                            new Option(null, OptionFlags.None, Index.Invalid,
                                       Index.Invalid, "-unicode", null),                // simple switch
                            new Option(null, OptionFlags.None, Index.Invalid,
                                       Index.Invalid, "-ignorestderr", null),           // simple switch
                            new Option(null, OptionFlags.None, Index.Invalid,
                                       Index.Invalid, "-killonerror", null),            // simple switch
                            new Option(null, OptionFlags.None, Index.Invalid,
                                       Index.Invalid, "-keepnewline", null),            // simple switch
                            new Option(null, OptionFlags.None, Index.Invalid,
                                       Index.Invalid, "-noexitcode", null),             // simple switch
                            new Option(null, OptionFlags.None, Index.Invalid,
                                       Index.Invalid, "-nocapture", null),              // simple switch
                            new Option(null, OptionFlags.None, Index.Invalid,
                                       Index.Invalid, "-shell", null),                  // simple switch
                            new Option(null, OptionFlags.None, Index.Invalid,
                                       Index.Invalid, "-nocarriagereturns", null),      // simple switch
                            new Option(null, OptionFlags.None, Index.Invalid,
                                       Index.Invalid, "-trimall", null),                // simple switch
                            new Option(typeof(ExitCode), OptionFlags.MustHaveEnumValue,
                                       Index.Invalid, Index.Invalid, "-success", null), // success exit code
                            new Option(null, OptionFlags.MustHaveValue, Index.Invalid,
                                       Index.Invalid, "-domainname", null),
                            new Option(null, OptionFlags.MustHaveValue, Index.Invalid,
                                       Index.Invalid, "-username", null),
                            new Option(null, OptionFlags.MustHaveSecureStringValue, Index.Invalid,
                                       Index.Invalid, "-password", null),
                            new Option(null, OptionFlags.MustHaveListValue, Index.Invalid,
                                       Index.Invalid, "-preprocessarguments", null), // command
                            new Option(null, OptionFlags.MustHaveValue, Index.Invalid,
                                       Index.Invalid, "-directory", null),           // directory name
                            new Option(null, OptionFlags.MustHaveValue, Index.Invalid,
                                       Index.Invalid, "-processid", null),           // varName for processId
                            new Option(null, OptionFlags.MustHaveValue, Index.Invalid,
                                       Index.Invalid, "-exitcode", null),            // varName for exitCode
                            new Option(null, OptionFlags.MustHaveValue, Index.Invalid,
                                       Index.Invalid, "-stdin", null),               // varName for StdIn input
                            new Option(null, OptionFlags.MustHaveValue, Index.Invalid,
                                       Index.Invalid, "-stdout", null),              // varName for StdOut output
                            new Option(null, OptionFlags.MustHaveValue, Index.Invalid,
                                       Index.Invalid, "-stderr", null),              // varName for StdErr output
                            new Option(typeof(EventFlags), OptionFlags.MustHaveEnumValue,
                                       Index.Invalid, Index.Invalid, "-eventflags",
                                       new Variant(interpreter.EngineEventFlags)),
                            new Option(null, OptionFlags.None, Index.Invalid,
                                       Index.Invalid, Option.EndOfOptions, null)
                        });

                        int argumentIndex = Index.Invalid;

                        code = interpreter.GetOptions(options, arguments, 0, 1,
                                                      Index.Invalid, true, ref argumentIndex, ref result);

                        if (code == ReturnCode.Ok)
                        {
                            if (argumentIndex != Index.Invalid)
                            {
                                bool debug = false;

                                if (options.IsPresent("-debug"))
                                {
                                    debug = true;
                                }

                                bool commandLine = false;

                                if (options.IsPresent("-commandline"))
                                {
                                    commandLine = true;
                                }

                                bool dequote = false;

                                if (options.IsPresent("-dequote"))
                                {
                                    dequote = true;
                                }

                                bool quoteAll = false;

                                if (options.IsPresent("-quoteall"))
                                {
                                    quoteAll = true;
                                }

                                bool captureExitCode = true;

                                if (options.IsPresent("-noexitcode"))
                                {
                                    captureExitCode = false;
                                }

                                bool captureInput  = true;
                                bool captureOutput = true;

                                if (options.IsPresent("-nocapture"))
                                {
                                    captureInput  = false;
                                    captureOutput = false;
                                }

                                bool useUnicode = false;

                                if (options.IsPresent("-unicode"))
                                {
                                    useUnicode = true;
                                }

                                bool ignoreStdErr = false;

                                if (options.IsPresent("-ignorestderr"))
                                {
                                    ignoreStdErr = true;
                                }

                                bool killOnError = false;

                                if (options.IsPresent("-killonerror"))
                                {
                                    killOnError = true;
                                }

                                bool keepNewLine = false;

                                if (options.IsPresent("-keepnewline"))
                                {
                                    keepNewLine = true;
                                }

                                bool carriageReturns = true;

                                if (options.IsPresent("-nocarriagereturns"))
                                {
                                    carriageReturns = false;
                                }

                                bool trimAll = false;

                                if (options.IsPresent("-trimall"))
                                {
                                    trimAll = true;
                                }

                                bool useShellExecute = false;

                                if (options.IsPresent("-shell"))
                                {
                                    useShellExecute = true;
                                }

                                Variant  value           = null;
                                ExitCode?successExitCode = null;

                                if (options.IsPresent("-success", ref value))
                                {
                                    successExitCode = (ExitCode)value.Value;
                                }

                                string domainName = null;

                                if (options.IsPresent("-domainname", ref value))
                                {
                                    domainName = value.ToString();
                                }

                                string userName = null;

                                if (options.IsPresent("-username", ref value))
                                {
                                    userName = value.ToString();
                                }

                                SecureString password = null;

                                if (options.IsPresent("-password", ref value))
                                {
                                    password = (SecureString)value.Value;
                                }

                                string directory = null;

                                if (options.IsPresent("-directory", ref value))
                                {
                                    directory = value.ToString();
                                }

                                string processIdVarName = null;

                                if (options.IsPresent("-processid", ref value))
                                {
                                    processIdVarName = value.ToString();
                                }

                                string exitCodeVarName = null;

                                if (options.IsPresent("-exitcode", ref value))
                                {
                                    exitCodeVarName = value.ToString();
                                }

                                string stdInVarName = null;

                                if (options.IsPresent("-stdin", ref value))
                                {
                                    stdInVarName = value.ToString();
                                }

                                string stdOutVarName = null;

                                if (options.IsPresent("-stdout", ref value))
                                {
                                    stdOutVarName = value.ToString();
                                }

                                string stdErrVarName = null;

                                if (options.IsPresent("-stderr", ref value))
                                {
                                    stdErrVarName = value.ToString();
                                }

                                EventFlags eventFlags = interpreter.EngineEventFlags;

                                if (options.IsPresent("-eventflags", ref value))
                                {
                                    eventFlags = (EventFlags)value.Value;
                                }

                                StringList list = null;

                                if (options.IsPresent("-preprocessarguments", ref value))
                                {
                                    list = (StringList)value.Value;
                                }

                                int  argumentStopIndex = arguments.Count - 1;
                                bool background        = false;

                                if (arguments[arguments.Count - 1] ==
                                    Characters.Ampersand.ToString())
                                {
                                    argumentStopIndex--;
                                    background = true;
                                }

                                string execFileName = arguments[argumentIndex];

                                if (!PathOps.IsRemoteUri(execFileName))
                                {
                                    execFileName = PathOps.GetNativePath(execFileName);
                                }

                                string execArguments = null;

                                if ((argumentIndex + 1) < arguments.Count)
                                {
                                    if (commandLine)
                                    {
                                        execArguments = RuntimeOps.BuildCommandLine(
                                            ArgumentList.GetRangeAsStringList(arguments,
                                                                              argumentIndex + 1, argumentStopIndex,
                                                                              dequote),
                                            quoteAll);
                                    }
                                    else
                                    {
                                        execArguments = ListOps.Concat(arguments,
                                                                       argumentIndex + 1, argumentStopIndex);
                                    }
                                }

                                Result input = null;

                                if ((code == ReturnCode.Ok) && !useShellExecute &&
                                    captureInput && (stdInVarName != null))
                                {
                                    code = interpreter.GetVariableValue(VariableFlags.None,
                                                                        stdInVarName, ref input, ref result);
                                }

                                if (debug)
                                {
                                    TraceOps.DebugTrace(String.Format(
                                                            "Execute: interpreter = {0}, domainName = {1}, userName = {2}, " +
                                                            "password = {3}, execFileName = {4}, execArguments = {5}, " +
                                                            "directory = {6}, input = {7}, eventFlags = {8}, debug = {9}, " +
                                                            "commandLine = {10}, dequote = {11}, quoteAll = {12}, " +
                                                            "useShellExecute = {13}, captureExitCode = {14}, " +
                                                            "captureInput = {15}, captureOutput = {16}, useUnicode = {17}, " +
                                                            "ignoreStdErr = {18}, killOnError = {19}, keepNewLine = {20}, " +
                                                            "carriageReturns = {21}, trimAll = {22}, background = {23}, " +
                                                            "successExitCode = {24}, processIdVarName = {25}, exitCodeVarName = {26}, " +
                                                            "stdInVarName = {27}, stdOutVarName = {28}, stdErrVarName = {29}",
                                                            FormatOps.InterpreterNoThrow(interpreter), FormatOps.WrapOrNull(domainName),
                                                            FormatOps.WrapOrNull(userName), FormatOps.WrapOrNull(password),
                                                            FormatOps.WrapOrNull(execFileName), FormatOps.WrapOrNull(execArguments),
                                                            FormatOps.WrapOrNull(directory), FormatOps.WrapOrNull(input),
                                                            FormatOps.WrapOrNull(eventFlags), debug, commandLine, dequote, quoteAll,
                                                            useShellExecute, captureExitCode, captureInput, captureOutput, useUnicode,
                                                            ignoreStdErr, killOnError, keepNewLine, carriageReturns, trimAll, background,
                                                            FormatOps.WrapOrNull(successExitCode), FormatOps.WrapOrNull(processIdVarName),
                                                            FormatOps.WrapOrNull(exitCodeVarName), FormatOps.WrapOrNull(stdInVarName),
                                                            FormatOps.WrapOrNull(stdOutVarName), FormatOps.WrapOrNull(stdErrVarName)),
                                                        typeof(Exec).Name, TracePriority.Command);
                                }

                                int      processId = 0;
                                ExitCode exitCode  = ResultOps.SuccessExitCode();
                                Result   error     = null;

                                if (code == ReturnCode.Ok)
                                {
                                    if (list != null)
                                    {
                                        list.Add(execFileName);
                                        list.Add(directory);
                                        list.Add(execArguments);

                                        code = interpreter.EvaluateScript(list.ToString(), ref result);

                                        if (code == ReturnCode.Return)
                                        {
                                            execArguments = result;
                                            code          = ReturnCode.Ok;
                                        }
                                        else if (code == ReturnCode.Continue)
                                        {
                                            code = ReturnCode.Ok;
                                            goto done;
                                        }
                                    }

                                    if (code == ReturnCode.Ok)
                                    {
                                        code = ProcessOps.ExecuteProcess(
                                            interpreter, domainName, userName, password, execFileName,
                                            execArguments, directory, input, eventFlags, useShellExecute,
                                            captureExitCode, captureOutput, useUnicode, ignoreStdErr,
                                            killOnError, keepNewLine, background, !background,
                                            ref processId, ref exitCode, ref result, ref error);
                                    }
                                }

done:

                                if (debug)
                                {
                                    TraceOps.DebugTrace(String.Format(
                                                            "Execute: interpreter = {0}, domainName = {1}, userName = {2}, " +
                                                            "password = {3}, execFileName = {4}, execArguments = {5}, " +
                                                            "directory = {6}, input = {7}, eventFlags = {8}, debug = {9}, " +
                                                            "commandLine = {10}, dequote = {11}, quoteAll = {12}, " +
                                                            "useShellExecute = {13}, captureExitCode = {14}, " +
                                                            "captureInput = {15}, captureOutput = {16}, useUnicode = {17}, " +
                                                            "ignoreStdErr = {18}, killOnError = {19}, keepNewLine = {20}, " +
                                                            "carriageReturns = {21}, trimAll = {22}, background = {23}, " +
                                                            "successExitCode = {24}, processIdVarName = {25}, exitCodeVarName = {26}, " +
                                                            "stdInVarName = {27}, stdOutVarName = {28}, stdErrVarName = {29}, " +
                                                            "processId = {30}, exitCode = {31}, result = {32}, error = {33}",
                                                            FormatOps.InterpreterNoThrow(interpreter), FormatOps.WrapOrNull(domainName),
                                                            FormatOps.WrapOrNull(userName), FormatOps.WrapOrNull(password),
                                                            FormatOps.WrapOrNull(execFileName), FormatOps.WrapOrNull(execArguments),
                                                            FormatOps.WrapOrNull(directory), FormatOps.WrapOrNull(input),
                                                            FormatOps.WrapOrNull(eventFlags), debug, commandLine, dequote, quoteAll,
                                                            useShellExecute, captureExitCode, captureInput, captureOutput, useUnicode,
                                                            ignoreStdErr, killOnError, keepNewLine, carriageReturns, trimAll, background,
                                                            FormatOps.WrapOrNull(successExitCode), FormatOps.WrapOrNull(processIdVarName),
                                                            FormatOps.WrapOrNull(exitCodeVarName), FormatOps.WrapOrNull(stdInVarName),
                                                            FormatOps.WrapOrNull(stdOutVarName), FormatOps.WrapOrNull(stdErrVarName),
                                                            processId, exitCode, FormatOps.WrapOrNull(true, true, result),
                                                            FormatOps.WrapOrNull(true, true, error)), typeof(Exec).Name,
                                                        TracePriority.Command);
                                }

                                //
                                // NOTE: Even upon failure, always set the variable to contain
                                //       process Id, if applicable.
                                //
                                if (processIdVarName != null)
                                {
                                    /* IGNORED */
                                    interpreter.SetVariableValue( /* EXEMPT */
                                        VariableFlags.NoReady, processIdVarName,
                                        processId.ToString(), null);
                                }

                                if (code == ReturnCode.Ok)
                                {
                                    //
                                    // NOTE: Remove all carriage returns from output (leaving
                                    //       only line feeds as line separators)?
                                    //
                                    if (!carriageReturns)
                                    {
                                        if (!String.IsNullOrEmpty(result))
                                        {
                                            result = result.Replace(
                                                Characters.CarriageReturnString,
                                                String.Empty);
                                        }

                                        if (!String.IsNullOrEmpty(error))
                                        {
                                            error = error.Replace(
                                                Characters.CarriageReturnString,
                                                String.Empty);
                                        }
                                    }

                                    //
                                    // NOTE: Remove all surrounding whitespace from the output?
                                    //
                                    if (trimAll)
                                    {
                                        if (!String.IsNullOrEmpty(result))
                                        {
                                            result = result.Trim();
                                        }

                                        if (!String.IsNullOrEmpty(error))
                                        {
                                            error = error.Trim();
                                        }
                                    }

                                    //
                                    // NOTE: Now, "result" contains any StdOut output and "error"
                                    //        contains any StdErr output.
                                    //
                                    if ((code == ReturnCode.Ok) && !background &&
                                        captureExitCode && (exitCodeVarName != null))
                                    {
                                        code = interpreter.SetVariableValue(VariableFlags.None,
                                                                            exitCodeVarName, exitCode.ToString(), null, ref error);
                                    }

                                    if ((code == ReturnCode.Ok) && !useShellExecute &&
                                        !background && captureOutput && (stdOutVarName != null))
                                    {
                                        code = interpreter.SetVariableValue(VariableFlags.None,
                                                                            stdOutVarName, result, null, ref error);
                                    }

                                    if ((code == ReturnCode.Ok) && !useShellExecute &&
                                        !background && captureOutput && (stdErrVarName != null))
                                    {
                                        code = interpreter.SetVariableValue(VariableFlags.None,
                                                                            stdErrVarName, error, null, ref error);
                                    }

                                    //
                                    // NOTE: If they specified a "success" exit code, make sure
                                    //       that is the same as the exit code we actually got
                                    //       from the process.
                                    //
                                    if ((code == ReturnCode.Ok) && !background && captureExitCode &&
                                        (successExitCode != null) && (exitCode != successExitCode))
                                    {
                                        /* IGNORED */
                                        interpreter.SetVariableValue( /* EXEMPT */
                                            Engine.ErrorCodeVariableFlags, TclVars.ErrorCode,
                                            StringList.MakeList(
                                                "CHILDSTATUS", processId, exitCode),
                                            null);

                                        Engine.SetErrorCodeSet(interpreter, true);

                                        error = "child process exited abnormally";
                                        code  = ReturnCode.Error;
                                    }

                                    if (code != ReturnCode.Ok)
                                    {
                                        //
                                        // NOTE: Transfer error to command result.
                                        //
                                        result = error;
                                    }
                                }
                                else
                                {
                                    //
                                    // NOTE: Transfer error to command result.
                                    //
                                    result = error;
                                }
                            }
                            else
                            {
                                result = "wrong # args: should be \"exec ?options? arg ?arg ...?\"";
                                code   = ReturnCode.Error;
                            }
                        }
                    }
                    else
                    {
                        result = "wrong # args: should be \"exec ?options? arg ?arg ...?\"";
                        code   = ReturnCode.Error;
                    }
                }
                else
                {
                    result = "invalid argument list";
                    code   = ReturnCode.Error;
                }
            }
            else
            {
                result = "invalid interpreter";
                code   = ReturnCode.Error;
            }

            return(code);
        }
Exemplo n.º 19
0
        ///////////////////////////////////////////////////////////////////////

        #region IExecute Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            if (interpreter == null)
            {
                result = "invalid interpreter";
                return(ReturnCode.Error);
            }

            if (arguments == null)
            {
                result = "invalid argument list";
                return(ReturnCode.Error);
            }

            if (arguments.Count < 2)
            {
                result = "wrong # args: should be \"hash option ?arg ...?\"";
                return(ReturnCode.Error);
            }

            ReturnCode code;
            string     subCommand = arguments[1];
            bool       tried      = false;

            code = ScriptOps.TryExecuteSubCommandFromEnsemble(
                interpreter, this, clientData, arguments, true,
                false, ref subCommand, ref tried, ref result);

            if ((code != ReturnCode.Ok) || tried)
            {
                return(code);
            }

            //
            // NOTE: These algorithms are known to be supported by the
            //       framework.
            //
            //       Normal: MD5, RIPEMD160, SHA, SHA1, SHA256, SHA384, SHA512
            //
            //        Keyed: MACTripleDES
            //
            //         HMAC: HMACMD5, HMACRIPEMD160, HMACSHA1, HMACSHA256,
            //               HMACSHA384, HMACSHA512
            //
            switch (subCommand)
            {
            case "keyed":
            {
                if (arguments.Count >= 4)
                {
                    OptionDictionary options = new OptionDictionary(
                        new IOption[] {
                            new Option(null, OptionFlags.None,
                                       Index.Invalid, Index.Invalid, "-raw",
                                       null),
                            new Option(null, OptionFlags.None,
                                       Index.Invalid, Index.Invalid, "-filename",
                                       null), /* COMPAT: Tcllib. */
                            new Option(null, OptionFlags.MustHaveEncodingValue,
                                       Index.Invalid, Index.Invalid, "-encoding",
                                       null),
                            new Option(null, OptionFlags.None,
                                       Index.Invalid, Index.Invalid,
                                       Option.EndOfOptions, null)
                        });

                    int argumentIndex = Index.Invalid;

                    code = interpreter.GetOptions(
                        options, arguments, 0, 2, Index.Invalid, false,
                        ref argumentIndex, ref result);

                    if (code == ReturnCode.Ok)
                    {
                        if ((argumentIndex != Index.Invalid) &&
                            ((argumentIndex + 2) <= arguments.Count) &&
                            ((argumentIndex + 3) >= arguments.Count))
                        {
                            Variant value = null;
                            bool    raw   = false;

                            if (options.IsPresent("-raw"))
                            {
                                raw = true;
                            }

                            bool isFileName = false;

                            if (options.IsPresent("-filename", ref value))
                            {
                                isFileName = true;
                            }

                            Encoding encoding = null;

                            if (options.IsPresent("-encoding", ref value))
                            {
                                encoding = (Encoding)value.Value;
                            }

                            if (code == ReturnCode.Ok)
                            {
                                try
                                {
                                    using (KeyedHashAlgorithm algorithm =
                                               KeyedHashAlgorithm.Create(
                                                   arguments[argumentIndex]))
                                    {
                                        if (algorithm != null)
                                        {
                                            algorithm.Initialize();

                                            if ((argumentIndex + 3) == arguments.Count)
                                            {
                                                byte[] bytes = null;

                                                code = StringOps.GetBytes(
                                                    encoding, arguments[argumentIndex + 2],
                                                    EncodingType.Binary, ref bytes, ref result);

                                                if (code == ReturnCode.Ok)
                                                {
                                                    algorithm.Key = bytes;
                                                }
                                            }

                                            if (code == ReturnCode.Ok)
                                            {
                                                if (isFileName)
                                                {
                                                    Stream stream = null;

                                                    try
                                                    {
                                                        code = RuntimeOps.NewStream(
                                                            interpreter,
                                                            arguments[argumentIndex + 1],
                                                            FileMode.Open, FileAccess.Read,
                                                            ref stream, ref result);

                                                        if (code == ReturnCode.Ok)
                                                        {
                                                            if (raw)
                                                            {
                                                                result = new ByteList(
                                                                    algorithm.ComputeHash(stream));
                                                            }
                                                            else
                                                            {
                                                                result = FormatOps.Hash(
                                                                    algorithm.ComputeHash(stream));
                                                            }
                                                        }
                                                    }
                                                    finally
                                                    {
                                                        if (stream != null)
                                                        {
                                                            stream.Close();
                                                            stream = null;
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    byte[] bytes = null;

                                                    code = StringOps.GetBytes(
                                                        encoding, arguments[argumentIndex + 1],
                                                        EncodingType.Binary, ref bytes, ref result);

                                                    if (raw)
                                                    {
                                                        result = new ByteList(
                                                            algorithm.ComputeHash(bytes));
                                                    }
                                                    else
                                                    {
                                                        result = FormatOps.Hash(
                                                            algorithm.ComputeHash(bytes));
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            result = String.Format(
                                                "unsupported keyed hash algorithm \"{0}\"",
                                                arguments[argumentIndex]);

                                            code = ReturnCode.Error;
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    Engine.SetExceptionErrorCode(interpreter, e);

                                    result = e;
                                    code   = ReturnCode.Error;
                                }
                            }
                        }
                        else
                        {
                            if ((argumentIndex != Index.Invalid) &&
                                Option.LooksLikeOption(arguments[argumentIndex]))
                            {
                                result = OptionDictionary.BadOption(
                                    options, arguments[argumentIndex]);
                            }
                            else
                            {
                                result = String.Format(
                                    "wrong # args: should be \"{0} {1} ?options? algorithm string ?key?\"",
                                    this.Name, subCommand);
                            }

                            code = ReturnCode.Error;
                        }
                    }
                }
                else
                {
                    result = String.Format(
                        "wrong # args: should be \"{0} {1} ?options? algorithm string ?key?\"",
                        this.Name, subCommand);

                    code = ReturnCode.Error;
                }
                break;
            }

            case "list":
            {
                if ((arguments.Count == 2) || (arguments.Count == 3))
                {
                    string type = null;

                    if (arguments.Count == 3)
                    {
                        type = arguments[2];
                    }

                    switch (type)
                    {
                    case null:
                    case "all":
                    {
                        StringList list = new StringList();

                        lock (syncRoot)
                        {
                            if (defaultAlgorithms != null)
                            {
                                list.AddRange(defaultAlgorithms);
                            }
                        }

                        if (keyedHashAlgorithmNames != null)
                        {
                            foreach (string hashAlgorithmName in keyedHashAlgorithmNames)
                            {
                                list.Add(StringList.MakeList("keyed", hashAlgorithmName));
                            }
                        }

                        if (macHashAlgorithmNames != null)
                        {
                            foreach (string hashAlgorithmName in macHashAlgorithmNames)
                            {
                                list.Add(StringList.MakeList("mac", hashAlgorithmName));
                            }
                        }

                        if (normalHashAlgorithmNames != null)
                        {
                            foreach (string hashAlgorithmName in normalHashAlgorithmNames)
                            {
                                list.Add(StringList.MakeList("normal", hashAlgorithmName));
                            }
                        }

                        result = list;
                        break;
                    }

                    case "default":
                    {
                        lock (syncRoot)
                        {
                            result = (defaultAlgorithms != null) ?
                                     new StringList(defaultAlgorithms) : null;
                        }
                        break;
                    }

                    case "keyed":
                    {
                        result = (keyedHashAlgorithmNames != null) ?
                                 new StringList(keyedHashAlgorithmNames) : null;

                        break;
                    }

                    case "mac":
                    {
                        result = (macHashAlgorithmNames != null) ?
                                 new StringList(macHashAlgorithmNames) : null;

                        break;
                    }

                    case "normal":
                    {
                        result = (normalHashAlgorithmNames != null) ?
                                 new StringList(normalHashAlgorithmNames) : null;

                        break;
                    }

                    default:
                    {
                        result = "unknown algorithm list, must be: all, default, keyed, mac, or normal";
                        code   = ReturnCode.Error;
                        break;
                    }
                    }
                }
                else
                {
                    result = String.Format(
                        "wrong # args: should be \"{0} {1} ?type?\"",
                        this.Name, subCommand);

                    code = ReturnCode.Error;
                }
                break;
            }

            case "mac":
            {
                if (arguments.Count >= 4)
                {
                    OptionDictionary options = new OptionDictionary(
                        new IOption[] {
                            new Option(null, OptionFlags.None,
                                       Index.Invalid, Index.Invalid, "-raw",
                                       null),
                            new Option(null, OptionFlags.None,
                                       Index.Invalid, Index.Invalid, "-filename",
                                       null), /* COMPAT: Tcllib. */
                            new Option(null, OptionFlags.MustHaveEncodingValue,
                                       Index.Invalid, Index.Invalid, "-encoding",
                                       null),
                            new Option(null, OptionFlags.None,
                                       Index.Invalid, Index.Invalid,
                                       Option.EndOfOptions, null)
                        });

                    int argumentIndex = Index.Invalid;

                    code = interpreter.GetOptions(
                        options, arguments, 0, 2, Index.Invalid, false,
                        ref argumentIndex, ref result);

                    if (code == ReturnCode.Ok)
                    {
                        if ((argumentIndex != Index.Invalid) &&
                            ((argumentIndex + 2) <= arguments.Count) &&
                            ((argumentIndex + 3) >= arguments.Count))
                        {
                            Variant value = null;
                            bool    raw   = false;

                            if (options.IsPresent("-raw"))
                            {
                                raw = true;
                            }

                            bool isFileName = false;

                            if (options.IsPresent("-filename", ref value))
                            {
                                isFileName = true;
                            }

                            Encoding encoding = null;

                            if (options.IsPresent("-encoding", ref value))
                            {
                                encoding = (Encoding)value.Value;
                            }

                            if (code == ReturnCode.Ok)
                            {
                                try
                                {
                                    using (HMAC algorithm = HMAC.Create(
                                               arguments[argumentIndex]))
                                    {
                                        if (algorithm != null)
                                        {
                                            algorithm.Initialize();

                                            if ((argumentIndex + 3) == arguments.Count)
                                            {
                                                byte[] bytes = null;

                                                code = StringOps.GetBytes(
                                                    encoding, arguments[argumentIndex + 2],
                                                    EncodingType.Binary, ref bytes, ref result);

                                                if (code == ReturnCode.Ok)
                                                {
                                                    algorithm.Key = bytes;
                                                }
                                            }

                                            if (code == ReturnCode.Ok)
                                            {
                                                if (isFileName)
                                                {
                                                    Stream stream = null;

                                                    try
                                                    {
                                                        code = RuntimeOps.NewStream(
                                                            interpreter,
                                                            arguments[argumentIndex + 1],
                                                            FileMode.Open, FileAccess.Read,
                                                            ref stream, ref result);

                                                        if (code == ReturnCode.Ok)
                                                        {
                                                            if (raw)
                                                            {
                                                                result = new ByteList(
                                                                    algorithm.ComputeHash(stream));
                                                            }
                                                            else
                                                            {
                                                                result = FormatOps.Hash(
                                                                    algorithm.ComputeHash(stream));
                                                            }
                                                        }
                                                    }
                                                    finally
                                                    {
                                                        if (stream != null)
                                                        {
                                                            stream.Close();
                                                            stream = null;
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    byte[] bytes = null;

                                                    code = StringOps.GetBytes(
                                                        encoding, arguments[argumentIndex + 1],
                                                        EncodingType.Binary, ref bytes, ref result);

                                                    if (raw)
                                                    {
                                                        result = new ByteList(
                                                            algorithm.ComputeHash(bytes));
                                                    }
                                                    else
                                                    {
                                                        result = FormatOps.Hash(
                                                            algorithm.ComputeHash(bytes));
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            result = String.Format(
                                                "unsupported hmac algorithm \"{0}\"",
                                                arguments[argumentIndex]);

                                            code = ReturnCode.Error;
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    Engine.SetExceptionErrorCode(interpreter, e);

                                    result = e;
                                    code   = ReturnCode.Error;
                                }
                            }
                        }
                        else
                        {
                            if ((argumentIndex != Index.Invalid) &&
                                Option.LooksLikeOption(arguments[argumentIndex]))
                            {
                                result = OptionDictionary.BadOption(
                                    options, arguments[argumentIndex]);
                            }
                            else
                            {
                                result = String.Format(
                                    "wrong # args: should be \"{0} {1} ?options? algorithm string ?key?\"",
                                    this.Name, subCommand);
                            }

                            code = ReturnCode.Error;
                        }
                    }
                }
                else
                {
                    result = String.Format(
                        "wrong # args: should be \"{0} {1} ?options? algorithm string ?key?\"",
                        this.Name, subCommand);

                    code = ReturnCode.Error;
                }
                break;
            }

            case "normal":
            {
                if (arguments.Count >= 4)
                {
                    OptionDictionary options = new OptionDictionary(
                        new IOption[] {
                            new Option(null, OptionFlags.None,
                                       Index.Invalid, Index.Invalid, "-raw",
                                       null),
                            new Option(null, OptionFlags.None,
                                       Index.Invalid, Index.Invalid, "-filename",
                                       null), /* COMPAT: Tcllib. */
                            new Option(null, OptionFlags.MustHaveEncodingValue,
                                       Index.Invalid, Index.Invalid, "-encoding",
                                       null),
                            new Option(null, OptionFlags.None,
                                       Index.Invalid, Index.Invalid,
                                       Option.EndOfOptions, null)
                        });

                    int argumentIndex = Index.Invalid;

                    code = interpreter.GetOptions(
                        options, arguments, 0, 2, Index.Invalid, false,
                        ref argumentIndex, ref result);

                    if (code == ReturnCode.Ok)
                    {
                        if ((argumentIndex != Index.Invalid) &&
                            ((argumentIndex + 2) == arguments.Count))
                        {
                            Variant value = null;
                            bool    raw   = false;

                            if (options.IsPresent("-raw"))
                            {
                                raw = true;
                            }

                            bool isFileName = false;

                            if (options.IsPresent("-filename", ref value))
                            {
                                isFileName = true;
                            }

                            Encoding encoding = null;

                            if (options.IsPresent("-encoding", ref value))
                            {
                                encoding = (Encoding)value.Value;
                            }

                            if (code == ReturnCode.Ok)
                            {
                                try
                                {
                                    using (HashAlgorithm algorithm =
                                               HashAlgorithm.Create(
                                                   arguments[argumentIndex]))
                                    {
                                        if (algorithm != null)
                                        {
                                            algorithm.Initialize();

                                            if (isFileName)
                                            {
                                                Stream stream = null;

                                                try
                                                {
                                                    code = RuntimeOps.NewStream(
                                                        interpreter,
                                                        arguments[argumentIndex + 1],
                                                        FileMode.Open, FileAccess.Read,
                                                        ref stream, ref result);

                                                    if (code == ReturnCode.Ok)
                                                    {
                                                        if (raw)
                                                        {
                                                            result = new ByteList(
                                                                algorithm.ComputeHash(stream));
                                                        }
                                                        else
                                                        {
                                                            result = FormatOps.Hash(
                                                                algorithm.ComputeHash(stream));
                                                        }
                                                    }
                                                }
                                                finally
                                                {
                                                    if (stream != null)
                                                    {
                                                        stream.Close();
                                                        stream = null;
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                byte[] bytes = null;

                                                code = StringOps.GetBytes(
                                                    encoding, arguments[argumentIndex + 1],
                                                    EncodingType.Binary, ref bytes, ref result);

                                                if (code == ReturnCode.Ok)
                                                {
                                                    if (raw)
                                                    {
                                                        result = new ByteList(
                                                            algorithm.ComputeHash(bytes));
                                                    }
                                                    else
                                                    {
                                                        result = FormatOps.Hash(
                                                            algorithm.ComputeHash(bytes));
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            result = String.Format(
                                                "unsupported hash algorithm \"{0}\"",
                                                arguments[argumentIndex]);

                                            code = ReturnCode.Error;
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    Engine.SetExceptionErrorCode(interpreter, e);

                                    result = e;
                                    code   = ReturnCode.Error;
                                }
                            }
                        }
                        else
                        {
                            if ((argumentIndex != Index.Invalid) &&
                                Option.LooksLikeOption(arguments[argumentIndex]))
                            {
                                result = OptionDictionary.BadOption(
                                    options, arguments[argumentIndex]);
                            }
                            else
                            {
                                result = String.Format(
                                    "wrong # args: should be \"{0} {1} ?options? algorithm string\"",
                                    this.Name, subCommand);
                            }

                            code = ReturnCode.Error;
                        }
                    }
                }
                else
                {
                    result = String.Format(
                        "wrong # args: should be \"{0} {1} ?options? algorithm string\"",
                        this.Name, subCommand);

                    code = ReturnCode.Error;
                }
                break;
            }

            default:
            {
                result = ScriptOps.BadSubCommand(
                    interpreter, null, null, subCommand, this, null, null);

                code = ReturnCode.Error;
                break;
            }
            }

            return(code);
        }
Exemplo n.º 20
0
        ///////////////////////////////////////////////////////////////////////////////////////////////

        #region IExecute Members
        public override ReturnCode Execute(
            Interpreter interpreter,
            IClientData clientData,
            ArgumentList arguments,
            ref Result result
            )
        {
            ReturnCode code = ReturnCode.Ok;

            if (interpreter != null)
            {
                if (arguments != null)
                {
                    if (arguments.Count == 4)
                    {
                        string     name = arguments[1];
                        StringList list = null;

                        code = Parser.SplitList(
                            interpreter, arguments[2], 0,
                            Length.Invalid, true, ref list,
                            ref result);

                        if (code == ReturnCode.Ok)
                        {
                            StringPairList list2 = new StringPairList();

                            for (int argumentIndex = 0; argumentIndex < list.Count; argumentIndex++)
                            {
                                StringList list3 = null;

                                code = Parser.SplitList(
                                    interpreter, list[argumentIndex], 0,
                                    Length.Invalid, true, ref list3,
                                    ref result);

                                if (code != ReturnCode.Ok)
                                {
                                    break;
                                }

                                if (list3.Count > 2)
                                {
                                    result = String.Format(
                                        "too many fields in argument specifier \"{0}\"",
                                        list[argumentIndex]);

                                    code = ReturnCode.Error;
                                    break;
                                }
                                else if ((list3.Count == 0) || String.IsNullOrEmpty(list3[0]))
                                {
                                    result = "argument with no name";
                                    code   = ReturnCode.Error;
                                    break;
                                }
                                else if (!Parser.IsSimpleScalarVariableName(list3[0],
                                                                            String.Format(Interpreter.ArgumentNotSimpleError, list3[0]),
                                                                            String.Format(Interpreter.ArgumentNotScalarError, list3[0]), ref result))
                                {
                                    code = ReturnCode.Error;
                                    break;
                                }

                                string argName    = list3[0];
                                string argDefault = (list3.Count >= 2) ? list3[1] : null;

                                list2.Add(new StringPair(argName, argDefault));
                            }

                            if (code == ReturnCode.Ok)
                            {
                                lock (interpreter.SyncRoot) /* TRANSACTIONAL */
                                {
                                    ProcedureFlags procedureFlags = interpreter.ProcedureFlags;

                                    IProcedure procedure = RuntimeOps.NewCoreProcedure(
                                        interpreter, interpreter.AreNamespacesEnabled() ?
                                        NamespaceOps.MakeQualifiedName(interpreter, name) :
                                        ScriptOps.MakeCommandName(name), null, null,
                                        procedureFlags, new ArgumentList(list2,
                                                                         ArgumentFlags.NameOnly), arguments[3],
                                        ScriptLocation.Create(arguments[3]), clientData);

                                    code = interpreter.AddOrUpdateProcedureWithReplace(
                                        procedure, clientData, ref result);

                                    if (code == ReturnCode.Ok)
                                    {
                                        result = String.Empty;
                                    }
                                }
                            }
                        }

                        if (code == ReturnCode.Error)
                        {
                            Engine.AddErrorInformation(interpreter, result,
                                                       String.Format("{0}    (creating proc \"{1}\")",
                                                                     Environment.NewLine, name));
                        }
                    }
                    else
                    {
                        result = "wrong # args: should be \"proc name args body\"";
                        code   = ReturnCode.Error;
                    }
                }
                else
                {
                    result = "invalid argument list";
                    code   = ReturnCode.Error;
                }
            }
            else
            {
                result = "invalid interpreter";
                code   = ReturnCode.Error;
            }

            return(code);
        }
Exemplo n.º 21
0
        private static bool IsSupported(
            Type type
            )
        {
            if (type == null)
            {
                return(false);
            }

            if (type == typeof(bool))
            {
                return(true);
            }
            else if (type == typeof(byte))
            {
                return(true);
            }
            else if (type == typeof(char))
            {
                return(true);
            }
            else if (type == typeof(int))
            {
                return(true);
            }
            else if (type == typeof(long))
            {
                return(true);
            }
            else if (type == typeof(double))
            {
                return(true);
            }
            else if (type == typeof(decimal))
            {
                return(true);
            }
            else if (type == typeof(string))
            {
                return(true);
            }
            else if (type == typeof(DateTime))
            {
                return(true);
            }
            else if (type == typeof(TimeSpan))
            {
                return(true);
            }
            else if (type == typeof(Guid))
            {
                return(true);
            }
            else if (type == typeof(Uri))
            {
                return(true);
            }
            else if (type == typeof(Version))
            {
                return(true);
            }
            else if (type == typeof(StringBuilder))
            {
                return(true);
            }
            else if (type == typeof(CommandBuilder))
            {
                return(true);
            }
            else if (type == typeof(Interpreter))
            {
                return(true);
            }
            else if (type == typeof(Argument))
            {
                return(true);
            }
            else if (type == typeof(ByteList))
            {
                return(true);
            }
            else if (type == typeof(ResultList))
            {
                return(true);
            }
            else if (type.IsEnum)
            {
                return(true);
            }
            else if (RuntimeOps.DoesClassTypeSupportInterface(
                         type, typeof(IStringList)))
            {
                return(true);
            }
            else if (RuntimeOps.IsClassTypeEqualOrSubClass(
                         type, typeof(Exception), true))
            {
                return(true);
            }

            return(false);
        }