-
Notifications
You must be signed in to change notification settings - Fork 39.3k
Expand file tree
/
Copy pathprotocolMainService.ts
More file actions
237 lines (185 loc) · 8.73 KB
/
protocolMainService.ts
File metadata and controls
237 lines (185 loc) · 8.73 KB
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { session } from 'electron';
import { Disposable, IDisposable, toDisposable } from '../../../base/common/lifecycle.js';
import { COI, FileAccess, Schemas, CacheControlheaders, DocumentPolicyheaders } from '../../../base/common/network.js';
import { basename, extname, normalize } from '../../../base/common/path.js';
import { isLinux, isWindows } from '../../../base/common/platform.js';
import { TernarySearchTree } from '../../../base/common/ternarySearchTree.js';
import { URI } from '../../../base/common/uri.js';
import { generateUuid } from '../../../base/common/uuid.js';
import { validatedIpcMain } from '../../../base/parts/ipc/electron-main/ipcMain.js';
import { INativeEnvironmentService } from '../../environment/common/environment.js';
import { ILogService } from '../../log/common/log.js';
import { IIPCObjectUrl, IProtocolMainService } from './protocol.js';
import { IUserDataProfilesService } from '../../userDataProfile/common/userDataProfile.js';
type ProtocolCallback = { (result: string | Electron.FilePathWithHeaders | { error: number }): void };
/**
* On Windows, the default Win32 file APIs enforce a `MAX_PATH` limit of 259
* characters. When a resource path exceeds this limit, Electron's
* `registerFileProtocol` handler fails to load the file (see
* https://github.com/microsoft/vscode/issues/261880 and
* https://github.com/electron/electron/issues/49101).
*
* Prefixing an absolute path with `\\?\` (or `\\?\UNC\` for UNC paths)
* opts the Win32 APIs into extended-length path mode which bypasses
* `MAX_PATH`.
*/
const WINDOWS_LONG_PATH_THRESHOLD = 248; // conservative: Win32 directory limit is 248 while file limit is 259
const WINDOWS_EXTENDED_PATH_PREFIX = '\\\\?\\';
const WINDOWS_EXTENDED_UNC_PREFIX = '\\\\?\\UNC\\';
function toWindowsLongPathIfNeeded(path: string): string {
if (!isWindows) {
return path;
}
if (path.length < WINDOWS_LONG_PATH_THRESHOLD) {
return path;
}
// Already using the extended-length prefix
if (path.startsWith(WINDOWS_EXTENDED_PATH_PREFIX)) {
return path;
}
// UNC path: \\server\share\... -> \\?\UNC\server\share\...
if (path.length >= 2 && path.charCodeAt(0) === 92 /* \ */ && path.charCodeAt(1) === 92 /* \ */) {
return WINDOWS_EXTENDED_UNC_PREFIX + path.substring(2);
}
// Drive-letter absolute path: C:\... -> \\?\C:\...
if (path.length >= 3 && path.charCodeAt(1) === 58 /* : */) {
return WINDOWS_EXTENDED_PATH_PREFIX + path;
}
return path;
}
export class ProtocolMainService extends Disposable implements IProtocolMainService {
declare readonly _serviceBrand: undefined;
private readonly validRoots = TernarySearchTree.forPaths<boolean>(!isLinux);
private readonly validExtensions = new Set(['.svg', '.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp', '.mp4', '.otf', '.ttf']); // https://github.com/microsoft/vscode/issues/119384
constructor(
@INativeEnvironmentService private readonly environmentService: INativeEnvironmentService,
@IUserDataProfilesService userDataProfilesService: IUserDataProfilesService,
@ILogService private readonly logService: ILogService
) {
super();
// Define an initial set of roots we allow loading from
// - appRoot : all files installed as part of the app
// - extensions : all files shipped from extensions
// - storage : all files in global and workspace storage (https://github.com/microsoft/vscode/issues/116735)
this.addValidFileRoot(environmentService.appRoot);
this.addValidFileRoot(environmentService.extensionsPath);
this.addValidFileRoot(userDataProfilesService.defaultProfile.globalStorageHome.with({ scheme: Schemas.file }).fsPath);
this.addValidFileRoot(environmentService.workspaceStorageHome.with({ scheme: Schemas.file }).fsPath);
// Handle protocols
this.handleProtocols();
}
private handleProtocols(): void {
const { defaultSession } = session;
// Register vscode-file:// handler
defaultSession.protocol.registerFileProtocol(Schemas.vscodeFileResource, (request, callback) => this.handleResourceRequest(request, callback));
// Block any file:// access
defaultSession.protocol.interceptFileProtocol(Schemas.file, (request, callback) => this.handleFileRequest(request, callback));
// Cleanup
this._register(toDisposable(() => {
defaultSession.protocol.unregisterProtocol(Schemas.vscodeFileResource);
defaultSession.protocol.uninterceptProtocol(Schemas.file);
}));
}
addValidFileRoot(root: string): IDisposable {
// Pass to `normalize` because we later also do the
// same for all paths to check against.
const normalizedRoot = normalize(root);
if (!this.validRoots.get(normalizedRoot)) {
this.validRoots.set(normalizedRoot, true);
return toDisposable(() => this.validRoots.delete(normalizedRoot));
}
return Disposable.None;
}
//#region file://
private handleFileRequest(request: Electron.ProtocolRequest, callback: ProtocolCallback) {
const uri = URI.parse(request.url);
this.logService.error(`Refused to load resource ${uri.fsPath} from ${Schemas.file}: protocol (original URL: ${request.url})`);
return callback({ error: -3 /* ABORTED */ });
}
//#endregion
//#region vscode-file://
private handleResourceRequest(request: Electron.ProtocolRequest, callback: ProtocolCallback): void {
const path = this.requestToNormalizedFilePath(request);
const pathBasename = basename(path);
let headers: Record<string, string> | undefined;
if (this.environmentService.crossOriginIsolated) {
if (pathBasename === 'workbench.html' || pathBasename === 'workbench-dev.html') {
headers = COI.CoopAndCoep;
} else {
headers = COI.getHeadersFromQuery(request.url);
}
}
// In OSS, evict resources from the memory cache in the renderer process
// Refs https://github.com/microsoft/vscode/issues/148541#issuecomment-2670891511
if (!this.environmentService.isBuilt) {
headers = {
...headers,
...CacheControlheaders
};
}
// Document-policy header is needed for collecting
// JavaScript callstacks via https://www.electronjs.org/docs/latest/api/web-frame-main#framecollectjavascriptcallstack-experimental
// until https://github.com/electron/electron/issues/45356 is resolved.
if (pathBasename === 'workbench.html' || pathBasename === 'workbench-dev.html') {
headers = {
...headers,
...DocumentPolicyheaders
};
}
// On Windows, paths longer than MAX_PATH (259) cause Electron's file
// protocol handler to fail. Apply the `\\?\` extended-length prefix so
// Win32 APIs bypass the limit (e.g. markdown image hover previews for
// deeply nested files). See https://github.com/microsoft/vscode/issues/261880.
const resolvedPath = toWindowsLongPathIfNeeded(path);
// first check by validRoots
if (this.validRoots.findSubstr(path)) {
return callback({ path: resolvedPath, headers });
}
// then check by validExtensions
if (this.validExtensions.has(extname(path).toLowerCase())) {
return callback({ path: resolvedPath, headers });
}
// finally block to load the resource
this.logService.error(`${Schemas.vscodeFileResource}: Refused to load resource ${path} from ${Schemas.vscodeFileResource}: protocol (original URL: ${request.url})`);
return callback({ error: -3 /* ABORTED */ });
}
private requestToNormalizedFilePath(request: Electron.ProtocolRequest): string {
// 1.) Use `URI.parse()` util from us to convert the raw
// URL into our URI.
const requestUri = URI.parse(request.url);
// 2.) Use `FileAccess.asFileUri` to convert back from a
// `vscode-file:` URI to a `file:` URI.
const unnormalizedFileUri = FileAccess.uriToFileUri(requestUri);
// 3.) Strip anything from the URI that could result in
// relative paths (such as "..") by using `normalize`
return normalize(unnormalizedFileUri.fsPath);
}
//#endregion
//#region IPC Object URLs
createIPCObjectUrl<T>(): IIPCObjectUrl<T> {
let obj: T | undefined = undefined;
// Create unique URI
const resource = URI.from({
scheme: 'vscode', // used for all our IPC communication (vscode:<channel>)
path: generateUuid()
});
// Install IPC handler
const channel = resource.toString();
const handler = async (): Promise<T | undefined> => obj;
validatedIpcMain.handle(channel, handler);
this.logService.trace(`IPC Object URL: Registered new channel ${channel}.`);
return {
resource,
update: updatedObj => obj = updatedObj,
dispose: () => {
this.logService.trace(`IPC Object URL: Removed channel ${channel}.`);
validatedIpcMain.removeHandler(channel);
}
};
}
//#endregion
}