Добавьте файлы проекта.

This commit is contained in:
User
2021-07-19 21:25:07 +03:00
parent 93934555f6
commit 99ba577733
272 changed files with 19884 additions and 0 deletions

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
</configuration>

View File

@@ -0,0 +1,221 @@
using DTLib;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using static DTLib.NetWork;
namespace dtlauncher_server
{
class DtlauncherServer
{
static readonly string logfile = $"logs\\dtlauncher-server-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_');
static readonly Socket mainSocket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
static Dtsod config;
//static readonly Dictionary<Socket, Thread> users = new();
static void Main()
{
try
{
Console.Title = "dtlauncher server";
Console.InputEncoding = Encoding.Unicode;
Console.OutputEncoding = Encoding.Unicode;
PublicLog.LogDel += Log;
/*var outBuilder = new StringBuilder();
string time = DateTime.Now.ToString().Replace(':', '-').Replace(' ', '_');
foreach (var _file in Directory.GetFiles(@"D:\!dtlauncher-server\share\public\Conan_Exiles"))
{
var file = _file.Remove(0, 35);
outBuilder.Append("Download(\"");
outBuilder.Append(file);
outBuilder.Append("\", \"downloads\\");
outBuilder.Append(file);
outBuilder.Append("\");\n");
outBuilder.Append("Run(\"cmd\", \"/c unarc.exe x -dpinstalled downloads\\");
outBuilder.Append(file);
outBuilder.Append(" >> logs\\installation-Conan_Exiles-");
outBuilder.Append(time);
outBuilder.Append(".log\");\n");
outBuilder.Append("FileDelete(\"downloads\\");
outBuilder.Append(file);
outBuilder.Append("\");\n");
}
Log("c", "\n\n" + outBuilder.ToString() + "\n\n");*/
config = config = new(File.ReadAllText("server.dtsod"));
int f = (int)config["server_port"];
Log("b", "local address: <", "c", config["server_ip"], "b",
">\npublic address: <", "c", GetPublicIP(), "b",
">\nport: <", "c", config["server_port"].ToString(), "b", ">\n");
mainSocket.Bind(new IPEndPoint(IPAddress.Parse(config["server_ip"]), (int)config["server_port"]));
mainSocket.Listen(1000);
Log("g", "server started succesfully\n");
//
/*DTLib.Timer userCkeckTimer = new(true, 3000, () =>
{
foreach (Socket usr in users.Keys)
{
if (usr.)
{
Log("y", $"closing unused user <{usr.RemoteEndPoint.Serialize()[0]}> thread\n");
users[usr].Abort();
users.Remove(usr);
}
}
});*/
// запуск отдельного потока для каждого юзера
while (true)
{
var userSocket = mainSocket.Accept();
var userThread = new Thread(new ParameterizedThreadStart((obj) => UserHandle((Socket)obj)));
//users.Add(userSocket, userThread);
userThread.Start(userSocket);
}
}
catch (Exception ex)
{
Log("r", $"dtlauncher_server.Main() error:\n{ex.Message}\n{ex.StackTrace}\n");
mainSocket.Close();
}
Log("press any key to close... ");
Console.ReadKey();
Log("gray", "\n");
}
// вывод лога в консоль и файл
public static void Log(params string[] msg)
{
if (msg.Length == 1) msg[0] = "[" + DateTime.Now.ToString() + "]: " + msg[0];
else msg[1] = "[" + DateTime.Now.ToString() + "]: " + msg[1];
LogNoTime(msg);
}
public static void LogNoTime(params string[] msg)
{
lock (new object())
{
if (msg.Length == 1) FileWork.Log(logfile, msg[0]);
else if (msg.Length % 2 != 0) throw new Exception("incorrect array to log\n");
else FileWork.Log(logfile, SimpleConverter.AutoBuild(msg));
ColoredConsole.Write(msg);
}
}
// запускается для каждого юзера в отдельном потоке
static void UserHandle(Socket handlerSocket)
{
Log("b", "user connecting... ");
//Socket fspSocket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//fspSocket.Bind()
try
{
handlerSocket.SendPackage("requesting hash".ToBytes());
var hash = handlerSocket.GetPackage();
// запрос от апдейтера
if (hash.HashToString() == "ffffffffffffffff")
{
LogNoTime("c", "client is updater\n");
CreateManifest("share\\client\\");
Log("g", "client files manifest created\n");
handlerSocket.SendPackage("updater".ToBytes());
while (true)
{
if (handlerSocket.Available >= 2)
{
var request = handlerSocket.GetPackage().ToStr();
string recieved, filepath;
switch (request)
{
case "requesting file download":
filepath = "share\\client\\" + handlerSocket.GetPackage().ToStr();
handlerSocket.FSP_Upload(filepath);
break;
case "register new user":
Log("b", "new user registration requested\n");
handlerSocket.SendPackage("ok".ToBytes());
//filepath = handlerSocket.GetPackage().ToStr();
//if (!filePath.EndsWith(".req")) throw new Exception($"wrong registration request file: <{filepath}>");
//Log("b", $"downloading file registration_requests\\{filepath}\n");
//handlerSocket.FSP_Download($"registration_requests\\{filepath}");
recieved = handlerSocket.GetPackage().ToStr();
filepath = $"registration_requests\\{recieved.Remove(0, recieved.IndexOf(':') + 2)}.req";
File.WriteAllText(filepath, recieved);
Log("b", $"text wrote to file <","c","registration_requests\\{filepath}","b",">\n");
break;
default:
throw new Exception("unknown request: " + request);
}
}
else Thread.Sleep(10);
}
}
// запрос от лаунчера
else
{
LogNoTime("c", "client is launcher\n");
string login;
lock (new object())
{
login = FileWork.ReadFromConfig("users.db", hash.HashToString());
}
handlerSocket.SendPackage("success".ToBytes());
Log("g", "user <", "c", login, "g", "> succesfully logined\n");
while (true)
{
if (handlerSocket.Available >= 64)
{
var request = handlerSocket.GetPackage().ToStr();
switch (request)
{
// ответ на NetWork.Ping()
/*case "ping":
handlerSocket.Send("pong".ToBytes());
break;*/
// отправка списка активных серверов
/*case "requesting servers list":
break;*/
case "requesting file download":
handlerSocket.FSP_Upload("share\\public\\" + handlerSocket.GetPackage().ToStr());
break;
default:
throw new Exception("unknown request: " + request);
}
}
else Thread.Sleep(10);
}
}
}
catch (Exception ex)
{
Log("y", $"UserStart() error:\n message:\n {ex.Message}\n{ex.StackTrace}\n");
handlerSocket.Shutdown(SocketShutdown.Both);
handlerSocket.Close();
Thread.CurrentThread.Abort();
}
}
// вычисляет и записывает в manifest.dtsod хеши файлов из files_list.dtsod
public static void CreateManifest(string dir)
{
if (!dir.EndsWith("\\")) dir += "\\";
var files = FileWork.GetAllFiles(dir);
if (files.Contains(dir + "manifest.dtsod")) files.Remove(dir + "manifest.dtsod");
StringBuilder manifestBuilder = new();
Hasher hasher = new();
for (int i = 0; i < files.Count; i++)
{
files[i] = files[i].Remove(0, dir.Length);
manifestBuilder.Append(files[i]);
manifestBuilder.Append(": \"");
byte[] hash = hasher.HashFile(dir + files[i]);
manifestBuilder.Append(hash.HashToString());
manifestBuilder.Append("\";\n");
}
File.WriteAllText(dir + "manifest.dtsod", manifestBuilder.ToString());
}
}
}

View File

@@ -0,0 +1,53 @@
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// Общие сведения об этой сборке предоставляются следующим набором
// набор атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
// связанные со сборкой.
[assembly: AssemblyTitle("dtlauncher-server-win")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("dtlauncher-server-win")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
// из модели COM, установите атрибут ComVisible для этого типа в значение true.
[assembly: ComVisible(false)]
//Чтобы начать создание локализуемых приложений, задайте
//<UICulture>CultureYouAreCodingWith</UICulture> в файле .csproj
//в <PropertyGroup>. Например, при использовании английского (США)
//в своих исходных файлах установите <UICulture> в en-US. Затем отмените преобразование в комментарий
//атрибута NeutralResourceLanguage ниже. Обновите "en-US" в
//строка внизу для обеспечения соответствия настройки UICulture в файле проекта.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //где расположены словари ресурсов по конкретным тематикам
//(используется, если ресурс не найден на странице,
// или в словарях ресурсов приложения)
ResourceDictionaryLocation.SourceAssembly //где расположен словарь универсальных ресурсов
//(используется, если ресурс не найден на странице,
// в приложении или в каких-либо словарях ресурсов для конкретной темы)
)]
// Сведения о версии для сборки включают четыре следующих значения:
//
// Основной номер версии
// Дополнительный номер версии
// Номер сборки
// Номер редакции
//
// Можно задать все значения или принять номера сборки и редакции по умолчанию
// используя "*", как показано ниже:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,70 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код был создан программным средством.
// Версия среды выполнения: 4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильному поведению и будут утрачены, если
// код создан повторно.
// </auto-generated>
//------------------------------------------------------------------------------
namespace dtlauncher_server_win.Properties
{
/// <summary>
/// Класс ресурсов со строгим типом для поиска локализованных строк и пр.
/// </summary>
// Этот класс был автоматически создан при помощи StronglyTypedResourceBuilder
// класс с помощью таких средств, как ResGen или Visual Studio.
// Для добавления или удаления члена измените файл .ResX, а затем перезапустите ResGen
// с параметром /str или заново постройте свой VS-проект.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// Возврат кэшированного экземпляра ResourceManager, используемого этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("dtlauncher_server_win.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Переопределяет свойство CurrentUICulture текущего потока для всех
/// подстановки ресурсов с помощью этого класса ресурсов со строгим типом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}

View File

@@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -0,0 +1,29 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace dtlauncher_server_win.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}

View File

@@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

View File

@@ -0,0 +1,112 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{8B9889A7-93DC-4914-92D1-8209BD3BA71A}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>dtlauncher_server_win</RootNamespace>
<AssemblyName>dtlauncher-server-win</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<LangVersion>9.0</LangVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<WarningLevel>4</WarningLevel>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Build|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>none</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<StartupObject>
</StartupObject>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xaml">
<RequiredTargetFramework>4.0</RequiredTargetFramework>
</Reference>
<Reference Include="WindowsBase" />
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
</ItemGroup>
<ItemGroup>
<Compile Include="DtlauncherServer.cs" />
<Compile Include="Properties\AssemblyInfo.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\DTLib\DTLib.csproj">
<Project>{ce793497-2d5c-42d8-b311-e9b32af9cdfb}</Project>
<Name>DTLib</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.8">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4.8 %28x86 и x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>del /f /q dtlauncher-server-win.exe.config</PostBuildEvent>
</PropertyGroup>
</Project>