aboutsummaryrefslogtreecommitdiffhomepage
path: root/helpers/utils.js
diff options
context:
space:
mode:
authorChocobozzz <florian.bigard@gmail.com>2016-01-30 17:05:22 +0100
committerChocobozzz <florian.bigard@gmail.com>2016-01-30 17:05:22 +0100
commitcda021079ff455cc0fd0eb95a5395fa808ab63d1 (patch)
tree056716de7460462b74b861051a5e9da6e2633fce /helpers/utils.js
parent86435b9baedfe300a28ea4545511c1b50d4119f6 (diff)
downloadPeerTube-cda021079ff455cc0fd0eb95a5395fa808ab63d1.tar.gz
PeerTube-cda021079ff455cc0fd0eb95a5395fa808ab63d1.tar.zst
PeerTube-cda021079ff455cc0fd0eb95a5395fa808ab63d1.zip
New directory organization
Diffstat (limited to 'helpers/utils.js')
-rw-r--r--helpers/utils.js202
1 files changed, 202 insertions, 0 deletions
diff --git a/helpers/utils.js b/helpers/utils.js
new file mode 100644
index 000000000..7cdb2600d
--- /dev/null
+++ b/helpers/utils.js
@@ -0,0 +1,202 @@
1;(function () {
2 'use strict'
3
4 var async = require('async')
5 var config = require('config')
6 var crypto = require('crypto')
7 var fs = require('fs')
8 var openssl = require('openssl-wrapper')
9 var request = require('request')
10 var replay = require('request-replay')
11 var ursa = require('ursa')
12
13 var constants = require('../initializers/constants')
14 var logger = require('./logger')
15
16 var utils = {}
17
18 var http = config.get('webserver.https') ? 'https' : 'http'
19 var host = config.get('webserver.host')
20 var port = config.get('webserver.port')
21 var algorithm = 'aes-256-ctr'
22
23 // ----------- Private functions ----------
24
25 function makeRetryRequest (params, from_url, to_pod, signature, callbackEach) {
26 // Append the signature
27 if (signature) {
28 params.json.signature = {
29 url: from_url,
30 signature: signature
31 }
32 }
33
34 logger.debug('Make retry requests to %s.', to_pod.url)
35
36 replay(
37 request.post(params, function (err, response, body) {
38 callbackEach(err, response, body, params.url, to_pod)
39 }),
40 {
41 retries: constants.REQUEST_RETRIES,
42 factor: 3,
43 maxTimeout: Infinity,
44 errorCodes: [ 'EADDRINFO', 'ETIMEDOUT', 'ECONNRESET', 'ESOCKETTIMEDOUT', 'ENOTFOUND', 'ECONNREFUSED' ]
45 }
46 ).on('replay', function (replay) {
47 logger.info('Replaying request to %s. Request failed: %d %s. Replay number: #%d. Will retry in: %d ms.',
48 params.url, replay.error.code, replay.error.message, replay.number, replay.delay)
49 })
50 }
51
52 // ----------- Public attributes ----------
53 utils.certDir = __dirname + '/../' + config.get('storage.certs')
54
55 // { path, data }
56 utils.makeMultipleRetryRequest = function (all_data, pods, callbackEach, callback) {
57 if (!callback) {
58 callback = callbackEach
59 callbackEach = null
60 }
61
62 var url = http + '://' + host + ':' + port
63 var signature
64
65 // Add signature if it is specified in the params
66 if (all_data.method === 'POST' && all_data.data && all_data.sign === true) {
67 var myKey = ursa.createPrivateKey(fs.readFileSync(utils.certDir + 'peertube.key.pem'))
68 signature = myKey.hashAndSign('sha256', url, 'utf8', 'hex')
69 }
70
71 // Make a request for each pod
72 async.each(pods, function (pod, callback_each_async) {
73 function callbackEachRetryRequest (err, response, body, url, pod) {
74 if (callbackEach !== null) {
75 callbackEach(err, response, body, url, pod, function () {
76 callback_each_async()
77 })
78 } else {
79 callback_each_async()
80 }
81 }
82
83 var params = {
84 url: pod.url + all_data.path,
85 method: all_data.method
86 }
87
88 // Add data with POST requst ?
89 if (all_data.method === 'POST' && all_data.data) {
90 // Encrypt data ?
91 if (all_data.encrypt === true) {
92 var crt = ursa.createPublicKey(pod.publicKey)
93
94 // TODO: ES6 with let
95 ;(function (crt_copy, copy_params, copy_url, copy_pod, copy_signature) {
96 utils.symetricEncrypt(JSON.stringify(all_data.data), function (err, dataEncrypted) {
97 if (err) throw err
98
99 var passwordEncrypted = crt_copy.encrypt(dataEncrypted.password, 'utf8', 'hex')
100 copy_params.json = {
101 data: dataEncrypted.crypted,
102 key: passwordEncrypted
103 }
104
105 makeRetryRequest(copy_params, copy_url, copy_pod, copy_signature, callbackEachRetryRequest)
106 })
107 })(crt, params, url, pod, signature)
108 } else {
109 params.json = { data: all_data.data }
110 makeRetryRequest(params, url, pod, signature, callbackEachRetryRequest)
111 }
112 } else {
113 makeRetryRequest(params, url, pod, signature, callbackEachRetryRequest)
114 }
115 }, callback)
116 }
117
118 utils.certsExist = function (callback) {
119 fs.exists(utils.certDir + 'peertube.key.pem', function (exists) {
120 return callback(exists)
121 })
122 }
123
124 utils.createCerts = function (callback) {
125 utils.certsExist(function (exist) {
126 if (exist === true) {
127 var string = 'Certs already exist.'
128 logger.warning(string)
129 return callback(new Error(string))
130 }
131
132 logger.info('Generating a RSA key...')
133 openssl.exec('genrsa', { 'out': utils.certDir + 'peertube.key.pem', '2048': false }, function (err) {
134 if (err) {
135 logger.error('Cannot create private key on this pod.', { error: err })
136 return callback(err)
137 }
138 logger.info('RSA key generated.')
139
140 logger.info('Manage public key...')
141 openssl.exec('rsa', { 'in': utils.certDir + 'peertube.key.pem', 'pubout': true, 'out': utils.certDir + 'peertube.pub' }, function (err) {
142 if (err) {
143 logger.error('Cannot create public key on this pod .', { error: err })
144 return callback(err)
145 }
146
147 logger.info('Public key managed.')
148 return callback(null)
149 })
150 })
151 })
152 }
153
154 utils.createCertsIfNotExist = function (callback) {
155 utils.certsExist(function (exist) {
156 if (exist === true) {
157 return callback(null)
158 }
159
160 utils.createCerts(function (err) {
161 return callback(err)
162 })
163 })
164 }
165
166 utils.generatePassword = function (callback) {
167 crypto.randomBytes(32, function (err, buf) {
168 if (err) {
169 return callback(err)
170 }
171
172 callback(null, buf.toString('utf8'))
173 })
174 }
175
176 utils.symetricEncrypt = function (text, callback) {
177 utils.generatePassword(function (err, password) {
178 if (err) {
179 return callback(err)
180 }
181
182 var cipher = crypto.createCipher(algorithm, password)
183 var crypted = cipher.update(text, 'utf8', 'hex')
184 crypted += cipher.final('hex')
185 callback(null, { crypted: crypted, password: password })
186 })
187 }
188
189 utils.symetricDecrypt = function (text, password) {
190 var decipher = crypto.createDecipher(algorithm, password)
191 var dec = decipher.update(text, 'hex', 'utf8')
192 dec += decipher.final('utf8')
193 return dec
194 }
195
196 utils.cleanForExit = function (webtorrent_process) {
197 logger.info('Gracefully exiting')
198 process.kill(-webtorrent_process.pid)
199 }
200
201 module.exports = utils
202})()