Skip to content

Commit

Permalink
added elevated fast file creation
Browse files Browse the repository at this point in the history
  • Loading branch information
JohnnyFFM committed May 2, 2018
1 parent 655f481 commit 6c8f246
Show file tree
Hide file tree
Showing 3 changed files with 149 additions and 7 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -286,3 +286,4 @@ __pycache__/
*.btm.cs
*.odx.cs
*.xsd.cs
/Thumbs.db
13 changes: 8 additions & 5 deletions MainForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ private void InitializeComponent()
this.MaximizeBox = false;
this.Name = "MainForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Johnny\'s POC1->POC2 Plot Converter v.1.3";
this.Text = "Johnny\'s POC1->POC2 Plot Converter v.1.4";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing);
this.grpConverter.ResumeLayout(false);
this.grpConverter.PerformLayout();
Expand Down Expand Up @@ -578,15 +578,12 @@ private void button4_Click(object sender, EventArgs e)
return;
}
}
else
{
DialogResult dialogResult = MessageBox.Show("Programm will shortly freeze to allocate disk space...", "Freeze Warning", MessageBoxButtons.OK);
}

btnConversion.Enabled = false;
outputDir.Enabled = false;
btnBrowse.Enabled = false;
memoryLimit.Enabled = false;

//create status tasks
statusList.Items.Clear();
foreach (ListViewItem x in plotFileList.Items) {
Expand Down Expand Up @@ -655,6 +652,12 @@ private void Conversion(int[] index, string[] filename, int[] nonces)
scoopReadWriter = new ScoopReadWriter(filename[i], outputDir.Text + "\\" + Path.GetFileName(filename[i]).Replace(nonces.ToString() + "_" + nonces.ToString(), nonces.ToString()));
}
scoopReadWriter.Open();

//prealloc disk space
if (outputDir.Text != "")
{
scoopReadWriter.PreAlloc(nonces[i]);
}

//loop scoop pairs
for (int y = 0; y < 2048; y++)
Expand Down
142 changes: 140 additions & 2 deletions ScoopReadWriter.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Win32.SafeHandles;
namespace poc1poc2Conv
{
/// <summary>
/// Summary description for ScoopReadWriter.
/// </summary>
public class ScoopReadWriter
{
private BinaryReader _br;
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetFileValidData(SafeFileHandle hFile, long ValidDataLength);
private BinaryReader _br;
protected string _sFileName;
protected string _tFileName;
private long _lLength = -1;
Expand All @@ -32,6 +38,21 @@ public ScoopReadWriter(string sFileName, string tFileName)
_tFileName = tFileName;
_inline = false;
}

public void PreAlloc(long totalNonces)
{
_fs2.SetLength(totalNonces * (2 << 17));
bool test = SetFileValidData(_fs2.SafeFileHandle, totalNonces * (2 << 17));
if (!test)
{
DialogResult dialogResult = MessageBox.Show("Elevated file creation failed. File creation will be very slow. Continue?", "Freeze Warning", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.No)
{
Application.Exit();
}
}
}

public void Close()
{
_bOpen = false;
Expand All @@ -57,7 +78,15 @@ public void Open()
}
else
{
_fs = new FileStream(_sFileName, FileMode.Open, FileAccess.Read, FileShare.Read, 1048576, FileOptions.SequentialScan);
if (!Privileges.HasAdminPrivileges)
{
DialogResult dialogResult = MessageBox.Show("No elevated file creation possible. File creation will be very slow. Continue?", "Freeze Warning", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.No)
{
Application.Exit();
}
}
_fs = new FileStream(_sFileName, FileMode.Open, FileAccess.Read, FileShare.Read, 1048576, FileOptions.SequentialScan);
_fs2 = new FileStream(_tFileName, FileMode.Create, FileAccess.Write, FileShare.None, 1048576, FileOptions.WriteThrough);
_br = new BinaryReader(_fs);
}
Expand All @@ -83,4 +112,113 @@ public void WriteScoop(int scoop, long totalNonces, long startNonce, Scoop sourc
_lPosition += limit * 64;
}
}
public static class Privileges
{
private static int asserted = 0;
private static bool hasBackupPrivileges = false;

public static bool HasAdminPrivileges
{
get { return AssertPriveleges(); }
}

private static bool AssertPriveleges()
{
bool success = false;
var wasAsserted = Interlocked.CompareExchange(ref asserted, 1, 0);
if (wasAsserted == 0)
{

success = AssertPrivelege(NativeMethods.SE_MANAGE_VOLUME_NAME);

hasBackupPrivileges = success;

}
return hasBackupPrivileges;
}

private static bool AssertPrivelege(string privelege)
{
IntPtr token;
var tokenPrivileges = new NativeMethods.TOKEN_PRIVILEGES();
tokenPrivileges.Privileges = new NativeMethods.LUID_AND_ATTRIBUTES[1];

var success =
NativeMethods.OpenProcessToken(NativeMethods.GetCurrentProcess(), NativeMethods.TOKEN_ADJUST_PRIVILEGES, out token)
&&
NativeMethods.LookupPrivilegeValue(null, privelege, out tokenPrivileges.Privileges[0].Luid);

try
{
if (success)
{
tokenPrivileges.PrivilegeCount = 1;
tokenPrivileges.Privileges[0].Attributes = NativeMethods.SE_PRIVILEGE_ENABLED;
success =
NativeMethods.AdjustTokenPrivileges(token, false, ref tokenPrivileges, Marshal.SizeOf(tokenPrivileges), IntPtr.Zero, IntPtr.Zero)
&&
(Marshal.GetLastWin32Error() == 0);
}

if (!success)
{
Console.WriteLine("Could not assert privilege: " + privelege);
}
}
finally
{
NativeMethods.CloseHandle(token);
}

return success;
}
}

internal class NativeMethods
{
internal const int ERROR_HANDLE_EOF = 38;

//--> Privilege constants....
internal const UInt32 SE_PRIVILEGE_ENABLED = 0x00000002;
internal const string SE_MANAGE_VOLUME_NAME = "SeManageVolumePrivilege";

//--> For starting a process in session 1 from session 0...
internal const uint TOKEN_ADJUST_PRIVILEGES = 0x0020;

[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);
[DllImport("kernel32.dll")]
internal static extern IntPtr GetCurrentProcess();
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, out LUID lpLuid);
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, [MarshalAs(UnmanagedType.Bool)]bool DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, Int32 BufferLength, IntPtr PreviousState, IntPtr ReturnLength);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool CloseHandle(IntPtr hObject);

[StructLayout(LayoutKind.Sequential)]
internal struct LUID
{
public UInt32 LowPart;
public Int32 HighPart;
}

[StructLayout(LayoutKind.Sequential)]
internal struct LUID_AND_ATTRIBUTES
{
public LUID Luid;
public UInt32 Attributes;
}

internal struct TOKEN_PRIVILEGES
{
public UInt32 PrivilegeCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
public LUID_AND_ATTRIBUTES[] Privileges;
}
}
}

0 comments on commit 6c8f246

Please sign in to comment.