-
Notifications
You must be signed in to change notification settings - Fork 874
/
Copy pathconfig.js
325 lines (266 loc) · 9.2 KB
/
config.js
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
const { join } = require('path')
const fs = require('fs-extra')
const { multiaddr } = require('multiaddr')
const http = require('http')
const portfinder = require('portfinder')
const { shell } = require('electron')
const i18n = require('i18next')
const { showDialog } = require('../dialogs')
const store = require('../common/store')
const logger = require('../common/logger')
function configExists (ipfsd) {
return fs.pathExistsSync(join(ipfsd.path, 'config'))
}
function apiFileExists (ipfsd) {
return fs.pathExistsSync(join(ipfsd.path, 'api'))
}
function rmApiFile (ipfsd) {
return fs.removeSync(join(ipfsd.path, 'api'))
}
function configPath (ipfsd) {
return join(ipfsd.path, 'config')
}
function readConfigFile (ipfsd) {
return fs.readJsonSync(configPath(ipfsd))
}
function writeConfigFile (ipfsd, config) {
fs.writeJsonSync(configPath(ipfsd), config, { spaces: 2 })
}
// Set default minimum and maximum of connections to maintain
// by default. This must only be called for repositories created
// by IPFS Desktop. Existing ones shall remain intact.
function applyDefaults (ipfsd) {
const config = readConfigFile(ipfsd)
// Ensure strict CORS checking
// See: https://github.com/ipfs/js-ipfsd-ctl/issues/333
config.API = { HTTPHeaders: {} }
config.Swarm = config.Swarm || {}
config.Swarm.DisableNatPortMap = false
config.Swarm.ConnMgr = config.Swarm.ConnMgr || {}
config.Swarm.ConnMgr.GracePeriod = '300s'
config.Swarm.ConnMgr.LowWater = 50
config.Swarm.ConnMgr.HighWater = 300
config.Discovery = config.Discovery || {}
config.Discovery.MDNS = config.Discovery.MDNS || {}
config.Discovery.MDNS.Enabled = true
writeConfigFile(ipfsd, config)
}
// Apply one-time updates to the config of IPFS node.
// This is the place where we execute fixes and performance tweaks for existing users.
function migrateConfig (ipfsd) {
// Bump revision number when new migration rule is added
const REVISION = 1
const REVISION_KEY = 'daemonConfigRevision'
// Migration is applied only once per revision
if (store.get(REVISION_KEY) >= REVISION) return
// Read config
let config = null
let changed = false
try {
config = readConfigFile(ipfsd)
} catch (err) {
// This is a best effort check, dont blow up here, that should happen else where.
logger.error(`[daemon] migrateConfig: error reading config file: ${err.message || err}`)
return
}
// Cleanup https://github.com/ipfs-shipyard/ipfs-desktop/issues/1631
if (config.Discovery && config.Discovery.MDNS && config.Discovery.MDNS.enabled) {
config.Discovery.MDNS.Enabled = config.Discovery.MDNS.Enabled || true
delete config.Discovery.MDNS.enabled
changed = true
}
// TODO: update config.Swarm.ConnMgr.*
if (changed) {
try {
writeConfigFile(ipfsd, config)
store.set(REVISION_KEY, REVISION)
} catch (err) {
logger.error(`[daemon] migrateConfig: error writing config file: ${err.message || err}`)
return
}
}
store.set(REVISION_KEY, REVISION)
}
// Check for * and webui://- in allowed origins on API headers.
// The wildcard was a ipfsd-ctl default, that we don't want, and
// webui://- was an earlier experiement that should be cleared out.
//
// We remove them the first time we find them. If we find it again on subsequent
// runs then we leave them in, under the assumption that you really want it.
// TODO: show warning in UI when wildcard is in the allowed origins.
function checkCorsConfig (ipfsd) {
if (store.get('checkedCorsConfig')) {
// We've already checked so skip it.
return
}
let config = null
try {
config = readConfigFile(ipfsd)
} catch (err) {
// This is a best effort check, dont blow up here, that should happen else where.
// TODO: gracefully handle config errors elsewhere!
logger.error(`[daemon] checkCorsConfig: error reading config file: ${err.message || err}`)
return
}
if (config.API && config.API.HTTPHeaders && config.API.HTTPHeaders['Access-Control-Allow-Origin']) {
const allowedOrigins = config.API.HTTPHeaders['Access-Control-Allow-Origin']
const originsToRemove = ['*', 'webui://-']
if (Array.isArray(allowedOrigins)) {
const specificOrigins = allowedOrigins.filter(origin => !originsToRemove.includes(origin))
if (specificOrigins.length !== allowedOrigins.length) {
config.API.HTTPHeaders['Access-Control-Allow-Origin'] = specificOrigins
try {
writeConfigFile(ipfsd, config)
store.set('updatedCorsConfig', Date.now())
} catch (err) {
logger.error(`[daemon] checkCorsConfig: error writing config file: ${err.message || err}`)
// don't skip setting checkedCorsConfig so we try again next time time.
return
}
}
}
}
store.set('checkedCorsConfig', true)
}
const parseCfgMultiaddr = (addr) => (addr.includes('/http')
? multiaddr(addr)
: multiaddr(addr).encapsulate('/http')
)
async function checkIfAddrIsDaemon (addr) {
const options = {
timeout: 3000, // 3s is plenty for localhost request
method: 'POST',
host: addr.address,
port: addr.port,
path: '/api/v0/refs?arg=/ipfs/QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn'
}
return new Promise(resolve => {
const req = http.request(options, function (r) {
resolve(r.statusCode === 200)
})
req.on('error', () => {
resolve(false)
})
req.end()
})
}
async function checkPortsArray (ipfsd, addrs) {
addrs = addrs.filter(Boolean)
for (const addr of addrs) {
const ma = parseCfgMultiaddr(addr)
const port = parseInt(ma.nodeAddress().port, 10)
if (port === 0) {
continue
}
const isDaemon = await checkIfAddrIsDaemon(ma.nodeAddress())
if (isDaemon) {
continue
}
const freePort = await portfinder.getPortPromise({ port: port, stopPort: port + 100 })
if (port !== freePort) {
const opt = showDialog({
title: i18n.t('multipleBusyPortsDialog.title'),
message: i18n.t('multipleBusyPortsDialog.message'),
type: 'error',
buttons: [
i18n.t('multipleBusyPortsDialog.action'),
i18n.t('close')
]
})
if (opt === 0) {
shell.openPath(join(ipfsd.path, 'config'))
}
throw new Error('ports already being used')
}
}
}
async function checkPorts (ipfsd) {
const config = readConfigFile(ipfsd)
const apiIsArr = Array.isArray(config.Addresses.API)
const gatewayIsArr = Array.isArray(config.Addresses.Gateway)
if (apiIsArr || gatewayIsArr) {
logger.info('[daemon] custom configuration with array of API or Gateway addrs')
return checkPortsArray(ipfsd, [].concat(config.Addresses.API, config.Addresses.Gateway))
}
const configApiMa = parseCfgMultiaddr(config.Addresses.API)
const configGatewayMa = parseCfgMultiaddr(config.Addresses.Gateway)
const isApiMaDaemon = await checkIfAddrIsDaemon(configApiMa.nodeAddress())
const isGatewayMaDaemon = await checkIfAddrIsDaemon(configGatewayMa.nodeAddress())
if (isApiMaDaemon && isGatewayMaDaemon) {
logger.info('[daemon] ports busy by a daemon')
return
}
const apiPort = parseInt(configApiMa.nodeAddress().port, 10)
const gatewayPort = parseInt(configGatewayMa.nodeAddress().port, 10)
const findFreePort = async (port, from) => {
port = Math.max(port, from, 1024)
return portfinder.getPortPromise({ port, stopPort: port + 100 })
}
const freeGatewayPort = await findFreePort(gatewayPort, 8080)
const freeApiPort = await findFreePort(apiPort, 5001)
const busyApiPort = apiPort !== freeApiPort
const busyGatewayPort = gatewayPort !== freeGatewayPort
if (!busyApiPort && !busyGatewayPort) {
return
}
// two "0" in config mean "pick free ports without any prompt"
const promptUser = (apiPort !== 0 || gatewayPort !== 0)
if (promptUser) {
let message = null
let options = null
if (busyApiPort && busyGatewayPort) {
logger.info('[daemon] api and gateway ports busy')
message = 'busyPortsDialog'
options = {
port1: apiPort,
alt1: freeApiPort,
port2: gatewayPort,
alt2: freeGatewayPort
}
} else if (busyApiPort) {
logger.info('[daemon] api port busy')
message = 'busyPortDialog'
options = {
port: apiPort,
alt: freeApiPort
}
} else {
logger.info('[daemon] gateway port busy')
message = 'busyPortDialog'
options = {
port: gatewayPort,
alt: freeGatewayPort
}
}
const opt = showDialog({
title: i18n.t(`${message}.title`),
message: i18n.t(`${message}.message`, options),
type: 'error',
buttons: [
i18n.t(`${message}.action`, options),
i18n.t('close')
]
})
if (opt !== 0) {
throw new Error('ports already being used')
}
}
if (busyApiPort) {
config.Addresses.API = config.Addresses.API.replace(apiPort.toString(), freeApiPort.toString())
}
if (busyGatewayPort) {
config.Addresses.Gateway = config.Addresses.Gateway.replace(gatewayPort.toString(), freeGatewayPort.toString())
}
writeConfigFile(ipfsd, config)
logger.info('[daemon] ports updated')
}
module.exports = Object.freeze({
configPath,
configExists,
apiFileExists,
rmApiFile,
applyDefaults,
migrateConfig,
checkCorsConfig,
checkPorts
})