Exemplo n.º 1
0
        private void DownloadPatches(UpdateSession session, List <IUpdate5> updates, Stream output)
        {
            Bender.WriteLine("Downloading " + updates.Count + " patches...", output);

            foreach (IUpdate5 update in updates.OrderBy(u => u.Title))
            {
                if (update.IsDownloaded)
                {
                    Bender.WriteLine("Patch is already downloaded: " + update.Title, output);
                    continue;
                }


                UpdateCollection updateCollection = new UpdateCollection();
                updateCollection.Add(update);

                UpdateDownloader downloader = session.CreateUpdateDownloader();
                downloader.Updates = updateCollection;

                bool downloaded = false;

                for (int tries = 0; tries < 3 && !downloaded; tries++)
                {
                    try
                    {
                        string printtry = tries > 0 ? " (try " + (tries + 1) + ")" : string.Empty;

                        Bender.WriteLine("Downloading" + printtry + ": " + update.Title + ": " + GetPrintSize(update.MaxDownloadSize) + " MB.", output);

                        IDownloadResult downloadresult = downloader.Download();
                        if (downloadresult.ResultCode == OperationResultCode.orcSucceeded)
                        {
                            downloaded = true;
                        }
                        else
                        {
                            Bender.WriteLine("Couldn't download patch: " + downloadresult.ResultCode + ": 0x" + downloadresult.HResult.ToString("X"), output);
                        }
                    }
                    catch (COMException ex)
                    {
                        Bender.WriteLine("Couldn't download patch: 0x" + ex.HResult.ToString("X"), output);
                    }
                }
            }
        }
Exemplo n.º 2
0
        private static Socket Connect(string remote)
        {
            var    remoteServers = Bender.ReadServers();
            string remoteServer;

            if (remoteServers.TryGetValue(remote, out remoteServer))
            {
                var s    = remoteServer.Split(':');
                var ip   = IPAddress.Parse(s[0]);
                var port = int.Parse(s.Length == 2 ? s[1] : Bender.ListenPort);
                var sock = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                sock.Connect(ip, port);
                sock.ReceiveTimeout = 10000;
                return(sock);
            }

            return(null);
        }
Exemplo n.º 3
0
        public override long Seek(long offset, SeekOrigin origin)
        {
            if (origin != SeekOrigin.End)
            {
                throw new InvalidOperationException();
            }

            offset = -offset;

            var strings = new List <string>();
            var written = 0;

            foreach (var log in EventLog.GetEventLogs())
            {
                if (!log.Log.Equals(_source, StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                var index = log.Entries.Count - 1;

                while (written < offset && index >= 0)
                {
                    var e = log.Entries[index--];
                    var s = $"{Bender.Date(e.TimeWritten)} {e.EntryType} {e.Source} {EscapeNl(e.Message)} {EscapeNl(Encoding.ASCII.GetString(e.Data))}\r\n";
                    written += s.Length;
                    strings.Add(s);
                }

                var ms = new MemoryStream();
                var w  = new StreamWriter(ms);
                for (var i = strings.Count - 1; i >= 0; --i)
                {
                    w.Write(strings[i]);
                }
                w.Flush();
                ms.Position = Math.Max(0, written - offset);
                _ms         = ms;
            }

            return(Position);
        }
Exemplo n.º 4
0
        private List <IUpdate5> GetPatches(UpdateSession session, Stream output)
        {
            UpdateServiceManager manager = new UpdateServiceManager();

            Bender.WriteLine("Found " + manager.Services.Count + " update services.", output);

            List <IUpdate5> updates = new List <IUpdate5>();

            foreach (IUpdateService2 service in manager.Services)
            {
                Bender.WriteLine("Retrieving patches from: " + service.Name, output);

                try
                {
                    var searcher = session.CreateUpdateSearcher();
                    searcher.ServerSelection = ServerSelection.ssWindowsUpdate;
                    searcher.ServiceID       = service.ServiceID;

                    ISearchResult searchresult = searcher.Search("");

                    UpdateCollection updatecollection = searchresult.Updates;

                    Bender.WriteLine("Found " + updatecollection.Count + " updates.", output);

                    foreach (IUpdate5 update in updatecollection)
                    {
                        if (!updates.Any(u => u.Title == update.Title))
                        {
                            updates.Add(update);
                        }
                    }
                }
                catch (COMException ex)
                {
                    Bender.WriteLine("Couldn't retrive patches: 0x" + ex.HResult.ToString("X"), output);
                    Bender.WriteLine(ex.ToString(), output);
                }
            }

            return(updates);
        }
Exemplo n.º 5
0
        private void InstallPatches(UpdateSession session, List <IUpdate5> updates, bool rebootIfNeeded, Stream output)
        {
            Bender.WriteLine("Installing " + updates.Count + " patches...", output);

            bool reboot = false;

            foreach (IUpdate5 update in updates.OrderBy(u => u.Title))
            {
                if (update.IsInstalled)
                {
                    Bender.WriteLine("Patch is already installed: " + update.Title, output);
                    continue;
                }
                else if (!update.IsDownloaded)
                {
                    Bender.WriteLine("Patch isn't downloaded yet: " + update.Title, output);
                }
                else
                {
                    try
                    {
                        Bender.WriteLine("Installing: " + update.Title, output);

                        UpdateCollection updateCollection = new UpdateCollection();
                        updateCollection.Add(update);

                        IUpdateInstaller installer = session.CreateUpdateInstaller();
                        installer.Updates = updateCollection;

                        IInstallationResult installresult = installer.Install();
                        if (installresult.ResultCode == OperationResultCode.orcSucceeded)
                        {
                            if (installresult.RebootRequired)
                            {
                                reboot = true;
                            }
                        }
                        else
                        {
                            Bender.WriteLine("Couldn't install patch: " + installresult.ResultCode + ": 0x" + installresult.HResult.ToString("X"), output);
                        }
                    }
                    catch (COMException ex)
                    {
                        Bender.WriteLine("Couldn't download patch: 0x" + ex.HResult.ToString("X"), output);
                    }
                }
            }

            string regpath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired";

            if (reboot || CheckIfLocalMachineKeyExists(regpath))
            {
                if (rebootIfNeeded)
                {
                    Bender.WriteLine("Rebooting.", output);

                    IntPtr           hToken;
                    TOKEN_PRIVILEGES tkp;

                    OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out hToken);
                    tkp.PrivilegeCount        = 1;
                    tkp.Privileges.Attributes = SE_PRIVILEGE_ENABLED;
                    LookupPrivilegeValue("", SE_SHUTDOWN_NAME, out tkp.Privileges.pLuid);
                    AdjustTokenPrivileges(hToken, false, ref tkp, 0U, IntPtr.Zero, IntPtr.Zero);

                    if (!ExitWindowsEx(6, 0))
                    {
                        Bender.WriteLine("Couldn't reboot.", output);
                    }
                }
                else
                {
                    Bender.WriteLine("Reboot required.", output);
                }
            }
        }
Exemplo n.º 6
0
        private void PrintStats(List <IUpdate5> updates, Stream output)
        {
            string printsize = GetPrintSize(updates.Sum(u => u.MaxDownloadSize));

            Bender.WriteLine("Total unique updates: " + updates.Count + ": " + printsize + " MB.", output);
        }
Exemplo n.º 7
0
        public static void Create(string path, string processname)
        {
            bool    fulldump  = true;
            Process dump      = null;
            var     processes = Process.GetProcessesByName(processname);

            if (processes.Length == 1)
            {
                dump = processes[0];
            }
            else
            {
                int pid;
                if (int.TryParse(processname, out pid))
                {
                    dump = Process.GetProcessById(pid);
                }
            }

            if (dump == null)
            {
                return;
            }

            string fname = $"{dump.ProcessName}({dump.Id})_{DateTime.Now}.{(fulldump ? "dmp" : "mdmp")}".Replace(':', '_').Replace('/', '_');

            fname = Path.Combine(path, fname);

            Bender.LogInfo($"Dumping {dump.ProcessName}({dump.Id}) to {fname}.");

            using (var f = File.Open(fname, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                // Set NTFS compression first
                int ignored = 0;
                int result  = NativeMethods.DeviceIoControl(f.SafeFileHandle.DangerousGetHandle(), NativeMethods.FSCTL_SET_COMPRESSION, ref NativeMethods.COMPRESSION_FORMAT_DEFAULT, 2 /*sizeof(short)*/, IntPtr.Zero, 0, ref ignored, IntPtr.Zero);
                if (result == 0)
                {
                    var error = Marshal.GetLastWin32Error();
                    Bender.LogWarning(string.Format("Failed to set NTFS compression for {0}.. Error {1}.", fname, error));
                }

                bool bRet = NativeMethods.MiniDumpWriteDump(
                    dump.Handle,
                    (uint)dump.Id,
                    f.SafeFileHandle.DangerousGetHandle(),
                    fulldump ? (uint)NativeMethods.Typ.MiniDumpWithFullMemory : (uint)NativeMethods.Typ.MiniDumpNormal,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    IntPtr.Zero);

                if (!bRet)
                {
                    var error = Marshal.GetLastWin32Error();
                    Bender.LogError(new InvalidOperationException(string.Format("Failed to create minidump for {0}. Error {1:X}.", fname, error)));
                    f.Close();
                    try
                    {
                        File.Delete(fname);
                    }
                    catch
                    {
                        // empty
                    }
                }
            }
        }
Exemplo n.º 8
0
        public static void Do(string getLine, Stream net, Dictionary <string, string> fileMappings, Dictionary <Regex, string> colorMappings)
        {
            var ns = net as NetworkStream;

            if (ns != null)
            {
                ns.ReadTimeout = 30 * 1000;
            }

            bool methodKnown = true;

            using (net)
            {
                while (true)
                {
                    List <string> headers = null;
                    byte[]        body;
                    int           cl           = -1;
                    bool          readAnything = methodKnown;
                    try
                    {
                        var type = string.Empty;

                        while (true)
                        {
                            var line = Bender.ReadLine(net);
                            if (string.IsNullOrEmpty(line))
                            {
                                break;
                            }
                            readAnything = true;
                            if (line.StartsWith("Get ", StringComparison.OrdinalIgnoreCase))
                            {
                                getLine     = line;
                                methodKnown = true;
                            }
                            else if (line.StartsWith("Post ", StringComparison.OrdinalIgnoreCase))
                            {
                                getLine     = null;
                                methodKnown = true;
                            }
                            if (line.StartsWith("Content-Length:", StringComparison.OrdinalIgnoreCase))
                            {
                                cl = int.Parse(line.Substring(15));
                            }
                            if (line.StartsWith("Content-Type:", StringComparison.OrdinalIgnoreCase))
                            {
                                type = line.Substring(14);
                            }
                            if (headers == null && methodKnown && !string.IsNullOrEmpty(getLine))
                            {
                                headers = new List <string> {
                                    getLine
                                };
                            }
                            else if (headers != null)
                            {
                                headers.Add(line);
                            }
                        }

                        if (!readAnything)
                        {
                            return;
                        }
                    }
                    catch (IOException)
                    {
                        return;
                    }

                    string contentType;

                    try
                    {
                        string commandString = string.Empty;
                        if (!string.IsNullOrEmpty(getLine))
                        {
                            commandString = HttpUtility.UrlDecode(getLine.Substring(4, getLine.Length - 13));
                        }
                        if (cl != -1)
                        {
                            var contents = new byte[cl];
                            var offset   = 0;
                            while (cl > 0)
                            {
                                var cl2 = net.Read(contents, offset, cl);
                                if (cl2 <= 0)
                                {
                                    throw new InvalidOperationException($"Unable to read {cl} bytes of input data. Read {cl2}.");
                                }
                                cl     -= cl2;
                                offset += cl2;
                            }
                            commandString = Encoding.UTF8.GetString(contents);
                        }

                        if (!methodKnown)
                        {
                            throw new InvalidOperationException("Illegal method");
                        }

                        if (headers == null)
                        {
                            JavaScriptSerializer ser = new JavaScriptSerializer();
                            var commands             = ser.DeserializeObject(commandString) as Dictionary <string, object>;
                            var tasks = new List <Task <Tuple <string, MemoryStream> > >();
                            foreach (var command in commands)
                            {
                                var cmds       = command.Value as object[];
                                var ms         = new MemoryStream();
                                var serializer = new StreamWriter(ms);
                                foreach (var cmd in cmds)
                                {
                                    serializer.WriteLine(cmd as string);
                                }
                                serializer.Flush();
                                ms.Position = 0;
                                var key  = command.Key;
                                var task = Task.Factory.StartNew(() =>
                                {
                                    var rs = new MemoryStream();
                                    Bender.DoCommand(null, ms, rs, fileMappings, colorMappings);
                                    return(Tuple.Create(key, rs));
                                });
                                tasks.Add(task);
                            }

                            var js     = string.Empty;
                            var result = new Dictionary <string, List <string> >();
                            foreach (var task in tasks)
                            {
                                var key = task.Result.Item1;
                                var stm = task.Result.Item2;
                                stm = new MemoryStream(stm.ToArray());
                                var lines = new List <string>();
                                using (var rdr = new StreamReader(stm))
                                {
                                    while (true)
                                    {
                                        var l = rdr.ReadLine();
                                        if (l == null)
                                        {
                                            break;
                                        }
                                        lines.Add(l);
                                    }
                                }
                                if (key.Equals("tasklistj", StringComparison.InvariantCultureIgnoreCase) && lines.Count == 1)
                                {
                                    js = lines[0];
                                }

                                result.Add(key, lines);

                                if (result.Count > 1)
                                {
                                    js = string.Empty;
                                }
                            }

                            if (string.IsNullOrEmpty(js))
                            {
                                js = ser.Serialize(result);
                            }

                            contentType = "Content-Type: application/json; charset=UTF-8";
                            body        = Encoding.UTF8.GetBytes(js);
                        }
                        else
                        {
                            body        = null;
                            contentType = null;

                            var index       = commandString.IndexOf('?');
                            var paramString = string.Empty;
                            if (index != -1)
                            {
                                paramString   = commandString.Substring(index + 1);
                                commandString = commandString.Substring(0, index);
                            }

                            if (commandString.Equals("/log", StringComparison.OrdinalIgnoreCase))
                            {
                                const string defaults       = "lines=80&tail=0&scroll=1&bw=1&newlines=1&text=0";
                                var          appendLocation = string.Empty;

                                if (!ParseParams(paramString, string.Empty).Keys.Intersect(ParseParams(defaults, string.Empty).Keys).Any())
                                {
                                    appendLocation = "&" + defaults;
                                }

                                var param  = ParseParams(paramString, defaults);
                                var bw     = param["bw"] != "0";
                                var scroll = param["scroll"] != "0";
                                var file   = param.ContainsKey("file") ? param["file"] : null;
                                var lines  = param.ContainsKey("val") ? param["val"] : param["lines"];
                                var tail   = param["tail"];
                                var text   = param["text"] != "0";

                                var newLines = param["newlines"] != "0";

                                if (lines == "-f")
                                {
                                    lines = "40";
                                    tail  = "1";
                                }

                                var serverPath = Bender.ReadServerPath(file, fileMappings);
                                var server     = param.ContainsKey("server") ? param["server"] : serverPath.Item1;
                                var path       = serverPath.Item2;
                                var logOut     = new LogOutput(net, new LogOutput.Format {
                                    AppendLocation = appendLocation, ColorMappings = bw ? null : colorMappings, Scroll = scroll, NewLine = newLines, Title = path, PlainText = text
                                });

                                FileTailer.Tail(server, path, int.Parse(lines), int.Parse(tail) > 0, (bytes, i) =>
                                {
                                    logOut.Add(bytes, 0, i);
                                });

                                logOut.End();
                            }
                            else
                            {
                                var output = new MemoryStream();
                                var title  = string.Empty;

                                var param = ParseParams(paramString, string.Empty);

                                if (commandString.Equals("/stack", StringComparison.OrdinalIgnoreCase))
                                {
                                    StackTrace.DoManaged(null, output, Bender.GetPid2(param["exe"]));
                                    title = $"Stacktrace for {param["exe"]}";
                                }
                                else if (commandString.Equals("/wer", StringComparison.OrdinalIgnoreCase))
                                {
                                    StackTrace.OpenWerDump(null, output, param["exe"]);
                                    title = $"Werstack for {param["exe"]}";
                                }
                                else if (commandString.Equals("/get", StringComparison.OrdinalIgnoreCase))
                                {
                                    var serverPath = Bender.ReadServerPath(param["uri"], fileMappings);
                                    // var server = serverPath.Item1;
                                    var path = serverPath.Item2;
                                    FetchUri.Fetch(path, output);
                                    title = $"GET {path}";
                                }

                                var arr = output.ToArray();
                                if (arr.Length > 0)
                                {
                                    var str    = Encoding.UTF8.GetString(arr);
                                    var logOut = new LogOutput(net, new LogOutput.Format {
                                        Title = title, PlainText = true
                                    });
                                    logOut.Add(str);
                                    logOut.End();
                                }
                                else
                                {
                                    contentType = "Content-Type: text/plain; charset=UTF-8";
                                    var sb = new StringBuilder();
                                    foreach (var h in headers)
                                    {
                                        sb.AppendLine(h);
                                    }
                                    body = Encoding.UTF8.GetBytes(sb.ToString());
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        Write(net, "HTTP/1.1 500 Internal server error\nConnection: Close\n\n", null);
                        throw;
                    }

                    if (contentType != null && body != null)
                    {
                        var header = $"HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: *\n{contentType}\nContent-Length: {body.Length}\n\n";
                        Write(net, header, body);
                    }
                    methodKnown = false;
                }
            }
        }
Exemplo n.º 9
0
        public static float GetValue(string counter)
        {
            // \Processor Information(_Total)\% Processor Time
            lock (Counters)
            {
                Holder pc;
                if (Counters.TryGetValue(counter, out pc))
                {
                    return(pc.Value);
                }

                Pending.Add(counter);
            }

            if (_worker == null)
            {
                _worker = new Thread(o =>
                {
                    while (true)
                    {
                        List <string> pending;
                        List <string> dead = new List <string>();
                        lock (Counters)
                        {
                            pending = Pending.ToList();
                            Pending.Clear();
                        }

                        foreach (var p in pending)
                        {
                            try
                            {
                                var split   = p.Split('\\');
                                var ctr     = split[2];
                                split       = split[1].Split('(');
                                var cat     = split[0];
                                string inst = string.Empty;

                                if (split.Length > 1)
                                {
                                    inst = split[1].Remove(split[1].Length - 1);
                                }

                                foreach (var instance in new PerformanceCounterCategory(cat).GetInstanceNames())
                                {
                                    var truncated    = instance.Length == MaxInstanceLength;
                                    var usedInstance = instance;
                                    var m            = InstanceRegex.Match(usedInstance);
                                    if (m.Success)
                                    {
                                        usedInstance = m.Groups["instance"].Value;
                                    }

                                    if (inst.Equals(usedInstance, StringComparison.OrdinalIgnoreCase) || truncated && inst.Length > usedInstance.Length && inst.StartsWith(usedInstance))
                                    {
                                        inst = instance;
                                        break;
                                    }
                                }

                                var c = new System.Diagnostics.PerformanceCounter(cat, ctr, inst);

                                lock (Counters)
                                {
                                    Counters.Add(p, new Holder {
                                        Counter = c
                                    });
                                }
                            }
                            catch (Exception e)
                            {
                                Bender.LogError(e);
                            }
                        }

                        List <KeyValuePair <string, Holder> > pcs;
                        lock (Counters)
                        {
                            pcs = Counters.ToList();
                        }

                        foreach (var pcc in pcs)
                        {
                            try
                            {
                                pcc.Value.Value = pcc.Value.Counter.NextValue();
                            }
                            catch (Exception e)
                            {
                                Bender.LogError(e);
                                dead.Add(pcc.Key);
                            }
                        }

                        lock (Counters)
                        {
                            foreach (var remove in dead)
                            {
                                Counters.Remove(remove);
                            }
                        }

                        Thread.Sleep(TimeSpan.FromSeconds(10));
                    }
                    // ReSharper disable once FunctionNeverReturns
                })
                {
                    IsBackground = true
                };
                _worker.Start();
            }

            return(float.NaN);
        }
Exemplo n.º 10
0
        public static void Do(Socket peer, Stream input, Stream output)
        {
            var host = Bender.ReadLine(input);

            using (var sock = Connect(host))
            {
                if (peer != null)
                {
                    sock.ReceiveTimeout = peer.ReceiveTimeout;
                }
                var buf = new byte[512];

                Action startRead = null;

                var locko   = new object();
                var reading = true;

                startRead = () =>
                {
                    // ReSharper disable once AccessToDisposedClosure
                    sock.BeginReceive(buf, 0, buf.Length, SocketFlags.None, ar =>
                    {
                        // ReSharper disable once AccessToDisposedClosure
                        var read = sock.EndReceive(ar);
                        if (read == 0)
                        {
                            output.Close();
                            peer?.Shutdown(SocketShutdown.Send);

                            lock (locko)
                            {
                                reading = false;
                                Monitor.PulseAll(locko);
                            }
                        }
                        else
                        {
                            output.Write(buf, 0, read);
                            // ReSharper disable once PossibleNullReferenceException
                            // ReSharper disable once AccessToModifiedClosure
                            startRead();
                        }
                    }, null);
                };

                startRead();

                var buf2 = new byte[512];
                while (true)
                {
                    var read = input.Read(buf2, 0, buf2.Length);
                    if (read == 0)
                    {
                        sock.Shutdown(SocketShutdown.Send);
                        break;
                    }
                    else
                    {
                        var data = buf2.Take(read).Where(b => b != 0xd).ToArray();
                        sock.Send(data, 0, data.Length, SocketFlags.None);
                    }
                }

                lock (locko)
                {
                    while (reading)
                    {
                        Monitor.Wait(locko);
                    }
                }
            }
        }
Exemplo n.º 11
0
        public static void JavaScript(Stream wr)
        {
            var l = new List <Dictionary <string, List <string> > >();

            var dict1    = Process.GetProcesses().ToDictionary(process => process.Id);
            var cpudict1 = BuildCpuDict(dict1.Values);

            Thread.Sleep(TimeSpan.FromMilliseconds(100));

            var cpudict2 = BuildCpuDict(dict1.Values);

            var factor = 1000.0 / Environment.ProcessorCount;

            foreach (var kvp in dict1)
            {
                var process = kvp.Value;
                var id      = kvp.Key;
                Cpu cpu1;
                Cpu cpu2;
                if (!cpudict1.TryGetValue(id, out cpu1) || !cpudict2.TryGetValue(id, out cpu2))
                {
                    continue;
                }
                try
                {
                    var dict = new Dictionary <string, List <string> >();

                    dict.Add("id", new List <string> {
                        process.Id.ToString()
                    });

                    dict.Add("name", new List <string> {
                        process.ProcessName
                    });

                    dict.Add("private", new List <string> {
                        process.PrivateMemorySize64.ToString(), Bender.BytesToStr(process.PagedMemorySize64)
                    });

                    // dict.Add("cmdline", new List<string> { process.StartInfo.Arguments });

                    dict.Add("cpu", new List <string> {
                        (factor * (cpu2.TotalProcessorTime - cpu1.TotalProcessorTime).TotalSeconds).ToString(CultureInfo.InvariantCulture)
                    });

                    dict.Add("user", new List <string> {
                        (factor * (cpu2.UserProcessorTime - cpu1.UserProcessorTime).TotalSeconds).ToString(CultureInfo.InvariantCulture)
                    });

                    dict.Add("system", new List <string> {
                        (factor * (cpu2.PrivilegedProcessorTime - cpu1.PrivilegedProcessorTime).TotalSeconds).ToString(CultureInfo.InvariantCulture)
                    });

                    dict.Add("age", Age(DateTime.UtcNow - process.StartTime.ToUniversalTime()));

                    dict.Add("handlecount", new List <string> {
                        process.HandleCount.ToString(CultureInfo.InvariantCulture)
                    });

                    dict.Add("session", new List <string> {
                        process.SessionId.ToString(CultureInfo.InvariantCulture)
                    });

                    dict.Add("elapsedcpu", Age(cpu2.TotalProcessorTime));

                    var ph = IntPtr.Zero;
                    try
                    {
                        OpenProcessToken(process.Handle, TOKEN_QUERY, out ph);
                        WindowsIdentity wi = new WindowsIdentity(ph);
                        dict.Add("username", new List <string> {
                            wi.Name
                        });
                    }
                    finally
                    {
                        if (ph != IntPtr.Zero)
                        {
                            CloseHandle(ph);
                        }
                    }

                    l.Add(dict);
                }
                catch (Exception)
                {
                }
            }

            var ser = new JavaScriptSerializer();

            var text = Encoding.UTF8.GetBytes(ser.Serialize(l));

            wr.Write(text, 0, text.Length);
        }
Exemplo n.º 12
0
        public static void Do(Socket peer, Stream input, Stream output, string filename, string arguments, bool interactive)
        {
            if (peer != null)
            {
                peer.ReceiveTimeout = 0;
            }

            using (var proc = new Process {
                StartInfo = { RedirectStandardInput = true, RedirectStandardError = true, RedirectStandardOutput = true, FileName = filename, Arguments = arguments, UseShellExecute = false }
            })
            {
                proc.Start();
                var stdIn    = proc.StandardInput;
                var open     = 2;
                var done     = false;
                var doneLock = new object();

                Sender sendOutput = delegate(string s)
                {
                    if (s == null)
                    {
                        if (Interlocked.Decrement(ref open) == 0)
                        {
                            if (peer == null)
                            {
                                output.Close();
                            }
                            else
                            {
                                output.Flush();
                                peer.Shutdown(SocketShutdown.Send);
                            }

                            lock (doneLock)
                            {
                                done = true;
                                Monitor.PulseAll(doneLock);
                            }
                        }
                    }
                    else
                    {
                        var bytes = Encoding.ASCII.GetBytes(s + "\r\n");
                        try
                        {
                            output.Write(bytes, 0, bytes.Length);
                        }
                        catch (IOException)
                        {
                            // ReSharper disable once AccessToDisposedClosure
                            SafeKillProcess(proc);
                        }
                    }
                };

                proc.OutputDataReceived += (sender, args) =>
                {
                    sendOutput(args.Data);
                };

                proc.ErrorDataReceived += (sender, args) =>
                {
                    sendOutput(args.Data);
                };

                proc.BeginErrorReadLine();
                proc.BeginOutputReadLine();

                if (input != null && interactive)
                {
                    var buf = new byte[512];
                    try
                    {
                        try
                        {
                            while (true)
                            {
                                var read = input.Read(buf, 0, buf.Length);
                                if (read == 0)
                                {
                                    break;
                                }
                                stdIn.Write(Encoding.ASCII.GetString(buf, 0, read));
                            }
                        }
                        catch (IOException)
                        {
                        }

                        // Input is lost
                        if (peer == null)
                        {
                            input.Close();
                        }
                        else
                        {
                            peer.Shutdown(SocketShutdown.Receive);
                        }

                        // Wait 1 second for process to shut down orderly, then kill
                        if (!proc.WaitForExit(1000))
                        {
                            SafeKillProcess(proc);
                        }
                    }
                    // ReSharper disable EmptyGeneralCatchClause
                    catch (Exception e)
                    // ReSharper restore EmptyGeneralCatchClause
                    {
                        Bender.LogError(e);
                        proc.Kill();
                    }
                }

                lock (doneLock)
                {
                    while (!done)
                    {
                        Monitor.Wait(doneLock);
                    }
                }

                proc.WaitForExit();

                input?.Close();

                output?.Close();
            }
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            bool          debug   = false;
            StringBuilder batchSb = null;

            if (Environment.UserInteractive || GetConsoleWindow() != IntPtr.Zero)
            {
                try
                {
                    foreach (var arg in args)
                    {
                        if (batchSb != null)
                        {
                            if (batchSb.Length > 0)
                            {
                                batchSb.AppendLine();
                            }
                            batchSb.Append(arg);
                            continue;
                        }
                        var a = arg.ToLowerInvariant();
                        switch (a)
                        {
                        case "-install":
                        case "/install":
                            CheckAdmin();
                            InstallService();
                            Console.WriteLine("Service '{0}' installed.", ServiceName);
                            break;

                        case "-uninstall":
                        case "/uninstall":
                        case "-remove":
                        case "/remove":
                            CheckAdmin();
                            UninstallService();
                            Console.WriteLine("Service '{0}' uninstalled.", ServiceName);
                            break;

                        case "-start":
                        case "/start":
                        case "-startservice":
                        case "/startservice":
                            CheckAdmin();
                            StartService();
                            Console.WriteLine("Service '{0}' started.", ServiceName);
                            break;

                        case "-stop":
                        case "/stop":
                        case "-stopservice":
                        case "/stopservice":
                            CheckAdmin();
                            StopService();
                            Console.WriteLine("Service '{0}' stopped.", ServiceName);
                            break;

                        case "-status":
                        case "/status":
                            bool installed = IsInstalled();
                            bool running   = installed && IsRunning();
                            if (installed)
                            {
                                if (running)
                                {
                                    Console.WriteLine("Service '{0}' installed and running.", ServiceName);
                                }
                                else
                                {
                                    Console.WriteLine("Service '{0}' installed but not running.", ServiceName);
                                }
                            }
                            else
                            {
                                Console.WriteLine("Service '{0}' not installed.", ServiceName);
                            }
                            break;

                        case "-debug":
                        case "/debug":
                            debug = true;
                            break;

                        case "-batch":
                        case "/batch":
                            batchSb = new StringBuilder();
                            break;

                        default:
                            Console.WriteLine("Unknown option {0}.", a);
                            return;
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine(e.ToString());
                    return;
                }

                if (debug)
                {
                    Console.WriteLine("Starting service '{0}'", ServiceName);
                    ServiceShell.Start();

                    Thread.CurrentThread.Join();
                }
                else
                {
                    ServiceShell.Start();
                    Bender.DoCommand(null, new ConsoleStream(batchSb == null ? Console.In : new StringReader(batchSb.ToString()), null), new ConsoleStream(null, Console.Out), Bender.ReadFileMappings(), Bender.ReadColorization());
                }
            }
            else
            {
                ServiceBase.Run(new ServiceShell());
            }
        }
Exemplo n.º 14
0
        protected override void OnStop()
        {
            Bender.Stop();

            base.OnStop();
        }