CollabVM-Agent-Windows/CollabVMAgent/Program.cs

124 lines
4 KiB
C#
Raw Normal View History

2023-12-04 11:50:21 -05:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using CollabVMAgent.Protocol;
using MsgPack.Serialization;
using System.Security.Principal;
using System.Diagnostics;
namespace CollabVMAgent
{
class Program
{
static readonly string UploadsFolder = Environment.GetEnvironmentVariable("USERPROFILE") + @"\Desktop";
static MessagePackSerializer serializer = MessagePackSerializer.Get<ProtocolMessage>();
2023-12-10 15:21:13 -05:00
static VirtIOSerial vio;
2023-12-04 11:50:21 -05:00
static void Main(string[] args)
{
if (!IsAdmin())
{
Process cur = Process.GetCurrentProcess();
Process prc = new Process();
prc.StartInfo.Verb = "runas";
prc.StartInfo.FileName = cur.MainModule.FileName;
prc.Start();
Environment.Exit(0);
}
#if DEBUG
Console.WriteLine("Starting CollabVM Agent in Debug mode");
#endif
2023-12-10 15:21:13 -05:00
vio = new VirtIOSerial();
2023-12-04 11:50:21 -05:00
vio.Data += OnData;
2023-12-10 15:21:13 -05:00
if (vio.WriteMsg(new ProtocolMessage{
Operation = ProtocolOperation.NOP
}))
{
#if DEBUG
Console.WriteLine("Wrote NOP");
#endif
}
2023-12-04 11:50:21 -05:00
Thread.Sleep(-1);
}
private static void OnData(object sender, TypedEventArgs<byte[]> e)
{
ProtocolMessage msg;
using (MemoryStream ms = new MemoryStream(e.Data))
{
msg = (ProtocolMessage)serializer.Unpack(ms);
}
switch (msg.Operation)
{
case ProtocolOperation.UploadFile:
{
foreach (char c in Path.GetInvalidFileNameChars())
{
if (msg.Filename.Contains(c))
{
Console.Error.WriteLine($"Invalid filename \"{msg.Filename}\"");
return;
}
}
try
{
File.WriteAllBytes(UploadsFolder + @"\" + msg.Filename, msg.FileData);
2023-12-04 12:00:59 -05:00
} catch (Exception ex)
{
#if DEBUG
2023-12-04 12:00:59 -05:00
Console.WriteLine($"Failed to save {msg.Filename}: {ex.Message}");
#endif
return;
}
2023-12-04 11:50:21 -05:00
#if DEBUG
Console.WriteLine($"Successfully wrote {msg.Filename} ({msg.FileData.Length} bytes)");
#endif
new Thread(() =>
{
try
{
Process.Start(UploadsFolder + @"\" + msg.Filename).Start();
} catch (Exception ex)
{
#if DEBUG
Console.WriteLine($"Error while starting {msg.Filename}: {ex.Message}");
#endif
}
}).Start();
2023-12-04 11:50:21 -05:00
break;
}
2023-12-10 15:21:13 -05:00
case ProtocolOperation.NOP:
{
2023-12-10 16:20:48 -05:00
#if DEBUG
Console.WriteLine("Got NOP from server");
#endif
2023-12-10 15:21:13 -05:00
if (vio.WriteMsg(new ProtocolMessage
{
Operation = ProtocolOperation.NOP
}))
{
#if DEBUG
Console.WriteLine("Wrote NOP");
#endif
}
break;
}
2023-12-04 11:50:21 -05:00
}
}
static bool IsAdmin()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
bool isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
identity.Dispose();
return isElevated;
}
}
}