-
Notifications
You must be signed in to change notification settings - Fork 846
/
config.js
249 lines (202 loc) · 7.09 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
import { join } from 'path'
import fs from 'fs-extra'
import multiaddr from 'multiaddr'
import http from 'http'
import getPort from 'get-port'
import { shell } from 'electron'
import i18n from 'i18next'
import { showDialog } from '../dialogs'
import store from '../common/store'
import logger from '../common/logger'
export function configPath (ipfsd) {
return join(ipfsd.repoPath, 'config')
}
function readConfigFile (ipfsd) {
return fs.readJsonSync(configPath(ipfsd))
}
function writeConfigFile (ipfsd, config) {
fs.writeJsonSync(configPath(ipfsd), config, { spaces: 2 })
}
// Set default mininum and maximum of connections to mantain
// by default. This must only be called for repositories created
// by IPFS Desktop. Existing ones shall remain intact.
export 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)
}
// 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.
export 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 = {
method: 'GET',
host: addr.address,
port: addr.port,
path: '/api/v0/refs?arg=/ipfs/QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn'
}
return new Promise(resolve => {
var 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 getPort({ port: getPort.makeRange(port, 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.openItem(join(ipfsd.repoPath, 'config'))
}
throw new Error('ports already being used')
}
}
}
export 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 freeGatewayPort = await getPort({ port: getPort.makeRange(gatewayPort, gatewayPort + 100) })
const freeApiPort = await getPort({ port: getPort.makeRange(apiPort, apiPort + 100) })
const busyApiPort = apiPort !== freeApiPort
const busyGatewayPort = gatewayPort !== freeGatewayPort
if (!busyApiPort && !busyGatewayPort) {
return
}
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')
}