~ruther/NosSmooth.Comms

ref: 2023.6 NosSmooth.Comms/src/Local/NosSmooth.Comms.Inject/DllMain.cs -rw-r--r-- 5.7 KiB
edcd26a2 — Rutherther feat: move to new injection supporting passing in data and returning integer 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
//
//  DllMain.cs
//
//  Copyright (c) František Boháček. All rights reserved.
//  Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NosSmooth.Comms.Core;
using NosSmooth.Comms.Core.Extensions;
using NosSmooth.Comms.Data;
using NosSmooth.Comms.Inject.Extensions;
using NosSmooth.Comms.Inject.MessageResponders;
using NosSmooth.Comms.Inject.PacketResponders;
using NosSmooth.Core.Extensions;
using NosSmooth.Extensions.SharedBinding.Extensions;
using NosSmooth.LocalBinding.Options;
using NosSmooth.LocalClient.Extensions;
using Remora.Results;

namespace NosSmooth.Comms.Inject;

/// <summary>
/// A main entrypoint to NosSmooth local communications.
/// </summary>
public class DllMain
{
    private static bool _consoleAllocated;
    private static IHost? _host;

    /// <summary>
    /// Enable named pipes server.
    /// </summary>
    /// <param name="data">Should be zero, is not used.</param>
    /// <returns>The result, 0 success, 1 failure.</returns>
    [UnmanagedCallersOnly(EntryPoint = "EnableNamedPipes")]
    public static int EnableNamedPipes(nuint data)
        => Main
        (
            host =>
            {
                var manager = host.Services.GetRequiredService<ServerManager>();
                return manager.RunManagerAsync
                    (host.Services.GetRequiredService<IHostApplicationLifetime>().ApplicationStopping);
            }
        );

    /// <summary>
    /// Open a console.
    /// </summary>
    /// <param name="data">Should be zero, is not used.</param>
    /// <returns>The result, 0 success, 1 failure.</returns>
    [UnmanagedCallersOnly(EntryPoint = "OpenConsole")]
    public static int OpenConsole(nuint data)
    {
        WinConsole.Initialize(false);
        return 0;
    }

    /// <summary>
    /// Close a console.
    /// </summary>
    /// <param name="data">Should be zero, is not used.</param>
    /// <returns>The result, 0 success, 1 failure.</returns>
    [UnmanagedCallersOnly(EntryPoint = "CloseConsole")]
    public static int CloseConsole(nuint data)
    {
        WinConsole.Close();
        return 0;
    }

    private static int Main(Func<IHost, Task<Result>> host)
    {
        try
        {
            new Thread
            (
                () =>
                {
                    try
                    {
                        MainEntry(host).GetAwaiter().GetResult();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                    }
                }
            ).Start();

            return 0;
        }
        catch (Exception)
        {
            return 1;
        }
    }

    /// <summary>
    /// The entrypoint method.
    /// </summary>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    private static async Task MainEntry(Func<IHost, Task<Result>> host)
    {
        if (_host is not null)
        {
            var result = await host(_host);
            if (!result.IsSuccess)
            {
                _host.Services.GetRequiredService<ILogger<DllMain>>().LogResultError(result);
            }
            return;
        }

        var clientState = new ClientState();
        _host = Host.CreateDefaultBuilder()
            .UseConsoleLifetime()
            .ConfigureLogging
            (
                b =>
                {
                    b
                        .ClearProviders()
                        .AddConsole();
                }
            )
            .ConfigureServices
            (
                s =>
                {
                    s
                        .AddSingleton<ClientState>(_ => clientState)
                        .AddSingleton<CallbackConfigRepository>()
                        .AddManagedNostaleCore()
                        .AddLocalClient()
                        .ShareNosSmooth()
                        .AddNamedPipeServer(p => $"NosSmooth_{Process.GetCurrentProcess().Id}")
                        .AddPacketResponder<EveryPacketResponder>()
                        .AddServerHandling()
                        .AddMessageResponder<CommandResponder>()
                        .AddMessageResponder<FocusResponder>()
                        .AddMessageResponder<FollowResponder>()
                        .AddMessageResponder<HandshakeResponder>()
                        .AddMessageResponder<ConsoleResponder>()
                        .AddMessageResponder<PacketResponder>()
                        .AddMessageResponder<RunClientResponder>()
                        .Configure<HookManagerOptions>(clientState.HookOptions.CopyProperties)
                        .Configure<PlayerManagerOptions>(clientState.PlayerManagerOptions.CopyProperties)
                        .Configure<NetworkManagerOptions>(opts => clientState.NetworkManagerOptions.CopyProperties(opts))
                        .Configure<SceneManagerOptions>(clientState.SceneManagerOptions.CopyProperties)
                        .Configure<UnitManagerOptions>(clientState.UnitManagerOptions.CopyProperties)
                        .Configure<NtClientOptions>(clientState.NtClientOptions.CopyProperties)
                        .Configure<PetManagerOptions>(clientState.PetManagerOptions.CopyProperties);
                    s.AddHostedService<NosSmoothService>();
                }
            ).Build();

        await _host.StartAsync();
        var hostTask = _host.WaitForShutdownAsync();
        var serverTask = host(_host);

        await Task.WhenAll(hostTask, serverTask);
    }
}