-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathNativeMessagingClient.cs
197 lines (167 loc) · 6.84 KB
/
NativeMessagingClient.cs
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace sttz.expresso
{
/// <summary>
/// C# client to communicate with native browser extension helpers,
/// using Firefox/Chrome's messaging protocol.
/// </summary>
public class NativeMessagingClient
{
protected ILogger Log;
/// <summary>
/// Paths where the native messaging manifests are stored.
/// </summary>
static readonly string[] manifestBasePaths =
RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? new string[] {
"~/Library/Application Support/Mozilla/NativeMessagingHosts",
"/Library/Application Support/Mozilla/NativeMessagingHosts",
} :
RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? new string[] {
"/usr/lib/mozilla/native-messaging-hosts",
"/usr/lib64/mozilla/native-messaging-hosts",
"~/.mozilla/native-messaging-hosts",
} :
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? new string[] {
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + "/ExpressVPN/expressvpnd",
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "/ExpressVPN/expressvpnd",
} : new string[] { // If we can't detect the OS, try all the folders
"~/Library/Application Support/Mozilla/NativeMessagingHosts",
"/Library/Application Support/Mozilla/NativeMessagingHosts",
"/usr/lib/mozilla/native-messaging-hosts",
"/usr/lib64/mozilla/native-messaging-hosts",
"~/.mozilla/native-messaging-hosts",
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + "/ExpressVPN/expressvpnd",
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "/ExpressVPN/expressvpnd",
};
/// <summary>
/// Extension of the native messaging manifest file.
/// </summary>
const string manifestExtension = ".json";
#pragma warning disable CS0649
/// <summary>
/// Contents of the JSON-formatted native messaging manifest.
/// </summary>
[Serializable]
struct NativeMessagingManifest
{
public string name;
public string description;
public string path;
public string type;
public string[] allowed_extensions;
}
#pragma warning restore CS0649
string manifestPath;
NativeMessagingManifest manifest;
Process helper;
ConcurrentQueue<string> outputQueue = new ConcurrentQueue<string>();
/// <summary>
/// Create a new client with the given application name.
/// A native messaging manifest with a matching name must be installed.
/// </summary>
/// <param name="name">Name of the application or manifest</param>
public NativeMessagingClient(string name, ILogger logger)
{
Log = logger;
foreach (var basePath in manifestBasePaths) {
var path = Path.Combine(basePath, name + manifestExtension);
if (path.StartsWith("~/")) {
path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), path.Substring(2));
}
if (File.Exists(path)) {
manifestPath = path;
break;
}
}
if (manifestPath == null) {
throw new Exception($"No manifest found with name: {name}");
}
var json = File.ReadAllText(manifestPath);
manifest = JsonConvert.DeserializeObject<NativeMessagingManifest>(json);
if (manifest.type != "stdio") {
throw new Exception($"Unsupported native message type '{manifest.type}', only stdio is supported.");
}
if (!File.Exists(manifest.path)) {
throw new Exception($"Helper specified in '{manifestPath}' does not exist: {manifest.path}");
}
Log.LogInformation($"Manifest loaded for {manifest.name} with helper at: {manifest.path}");
Task.Run(ReceiveLoop);
}
/// <summary>
/// Send a message to the native helper.
/// </summary>
/// <param name="json">Serialized JSON message</param>
public async void Send(string json)
{
Log.LogDebug($"-> {json}");
var bytes = System.Text.Encoding.UTF8.GetBytes(json);
var lengthBuf = BitConverter.GetBytes((uint)bytes.Length);
var stdin = helper.StandardInput.BaseStream;
await stdin.WriteAsync(lengthBuf, 0, lengthBuf.Length);
await stdin.WriteAsync(bytes, 0, bytes.Length);
await stdin.FlushAsync();
}
/// <summary>
/// Receive the latest message from the helper.
/// This methods needs to be called multiple times for each received message.
/// </summary>
/// <returns>The JSON message or null if there are no pending messages</returns>
public string Receive()
{
if (outputQueue.TryDequeue(out var json)) {
return json;
}
return null;
}
async Task ReadOutput(byte[] buffer, int offset, int length)
{
var total = 0;
var stdout = helper.StandardOutput.BaseStream;
while (total < length) {
var read = await stdout.ReadAsync(buffer, total, length - total);
if (read == 0) {
throw new EndOfStreamException($"Reached end of stream but expected {length - total} more bytes.");
}
total += read;
}
}
async void ReceiveLoop()
{
helper = new Process();
helper.StartInfo = new ProcessStartInfo() {
FileName = manifest.path,
Arguments = $"\"{manifestPath}\" \"${manifest.allowed_extensions[0]}\"", // TODO: Escape values
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
};
helper.Start();
var lengthBuf = new byte[4];
var dataBuf = new byte[262144]; // TODO: Flexible buffer?
while (!helper.HasExited) {
await ReadOutput(lengthBuf, 0, 4);
var length = BitConverter.ToUInt32(lengthBuf, 0);
if (length > dataBuf.Length) {
throw new Exception($"Output buffer is too small to receive message: {dataBuf.Length} < {length}");
}
await ReadOutput(dataBuf, 0, (int)length);
var json = Encoding.UTF8.GetString(dataBuf, 0, (int)length);
Log.LogDebug($"<- {json}");
outputQueue.Enqueue(json);
}
if (helper.ExitCode != 0) {
Log.LogError($"Helper has exited with code {helper.ExitCode}");
} else {
Log.LogInformation($"Helper has exited with code {helper.ExitCode}");
}
}
}
}