insomnia/app/common/network.js

291 lines
9.8 KiB
JavaScript
Raw Normal View History

import networkRequest from 'request';
import {parse as urlParse} from 'url';
import mime from 'mime-types';
import {basename as pathBasename} from 'path';
2016-11-10 05:56:23 +00:00
import * as models from '../models';
import * as querystring from './querystring';
import {buildFromParams} from './querystring';
2016-11-10 05:56:23 +00:00
import * as util from './misc.js';
import {DEBOUNCE_MILLIS, STATUS_CODE_RENDER_FAILED, CONTENT_TYPE_FORM_DATA, CONTENT_TYPE_FORM_URLENCODED, CONTENT_TYPE_FILE} from './constants';
import {jarFromCookies, cookiesFromJar, cookieHeaderValueForUri} from './cookies';
2016-11-10 05:56:23 +00:00
import {setDefaultProtocol} from './misc';
import {getRenderedRequest} from './render';
import {swapHost} from './dns';
2016-11-22 22:26:52 +00:00
import * as fs from 'fs';
import * as db from './database';
2016-04-09 21:08:55 +00:00
2016-09-13 18:31:07 +00:00
let cancelRequestFunction = null;
export function cancelCurrentRequest () {
2016-09-13 18:31:07 +00:00
if (typeof cancelRequestFunction === 'function') {
cancelRequestFunction();
}
}
export function _buildRequestConfig (renderedRequest, patch = {}) {
2016-04-09 21:08:55 +00:00
const config = {
2016-04-28 07:30:26 +00:00
// Setup redirect rules
followAllRedirects: true,
2016-10-11 17:40:17 +00:00
followRedirect: true,
maxRedirects: 50, // Arbitrary (large) number
2016-07-29 00:24:05 +00:00
timeout: 0,
2016-04-28 07:30:26 +00:00
// Unzip gzipped responses
gzip: true,
// Time the request
time: true,
// SSL Checking
rejectUnauthorized: true,
// Proxy
2016-10-10 18:21:26 +00:00
proxy: null,
// Use keep-alive by default
forever: true,
2016-10-26 23:22:15 +00:00
// Force request to return response body as a Buffer instead of string
encoding: null,
2016-04-09 21:08:55 +00:00
};
// Set the body
if (renderedRequest.body.mimeType === CONTENT_TYPE_FORM_URLENCODED) {
config.body = buildFromParams(renderedRequest.body.params || [], true);
} else if (renderedRequest.body.mimeType === CONTENT_TYPE_FORM_DATA) {
const formData = {};
for (const param of renderedRequest.body.params) {
if (param.type === 'file' && param.fileName) {
formData[param.name] = {
value: fs.readFileSync(param.fileName),
options: {
fileName: pathBasename(param.fileName),
contentType: mime.lookup(param.fileName) // Guess the mime-type
}
}
} else {
formData[param.name] = param.value || '';
}
}
config.formData = formData;
2016-11-23 23:57:34 +00:00
} else if (renderedRequest.body.fileName) {
2016-11-22 22:26:52 +00:00
config.body = fs.readFileSync(renderedRequest.body.fileName);
} else {
config.body = renderedRequest.body.text || '';
}
2016-08-31 20:50:27 +00:00
// Set the method
config.method = renderedRequest.method;
// Set the headers
const headers = {};
2016-08-31 20:50:27 +00:00
for (let i = 0; i < renderedRequest.headers.length; i++) {
let header = renderedRequest.headers[i];
2016-04-12 00:39:49 +00:00
if (header.name) {
headers[header.name] = header.value;
2016-04-12 00:39:49 +00:00
}
2016-04-09 21:08:55 +00:00
}
config.headers = headers;
// Set the URL, including the query parameters
const qs = querystring.buildFromParams(renderedRequest.parameters);
const url = querystring.joinUrl(renderedRequest.url, qs);
config.url = util.prepareUrlForSending(url);
config.headers.host = urlParse(config.url).host;
2016-04-28 07:30:26 +00:00
return Object.assign(config, patch);
}
2016-04-28 07:30:26 +00:00
export function _actuallySend (renderedRequest, workspace, settings, forceIPv4 = false) {
return new Promise(async (resolve, reject) => {
// Detect and set the proxy based on the request protocol
// NOTE: request does not have a separate settings for http/https proxies
const {protocol} = urlParse(renderedRequest.url);
2016-09-22 19:44:28 +00:00
const {httpProxy, httpsProxy} = settings;
const proxyHost = protocol === 'https:' ? httpsProxy : httpProxy;
const proxy = proxyHost ? setDefaultProtocol(proxyHost) : null;
2016-11-22 22:26:52 +00:00
let config;
try {
config = _buildRequestConfig(renderedRequest, {
jar: null, // We're doing our own cookies
proxy: proxy,
followAllRedirects: settings.followRedirects,
followRedirect: settings.followRedirects,
timeout: settings.timeout > 0 ? settings.timeout : null,
rejectUnauthorized: settings.validateSSL
}, true);
} catch (e) {
const response = await models.response.create({
url: renderedRequest.url,
2016-11-22 22:26:52 +00:00
parentId: renderedRequest._id,
elapsedTime: 0,
statusMessage: 'Error',
error: e.message
});
return resolve(response);
}
2016-07-20 21:15:11 +00:00
// Add certs if needed
// https://vanjakom.wordpress.com/2011/08/11/client-and-server-side-ssl-with-nodejs/
const {hostname, port} = urlParse(config.url);
const certificate = workspace.certificates.find(certificate => {
const cHostWithProtocol = setDefaultProtocol(certificate.host, 'https:');
const {hostname: cHostname, port: cPort} = urlParse(cHostWithProtocol);
const assumedPort = parseInt(port) || 443;
const assumedCPort = parseInt(cPort) || 443;
// Exact host match (includes port)
return cHostname === hostname && assumedCPort === assumedPort;
});
if (certificate && !certificate.disabled) {
const {passphrase, cert, key, pfx} = certificate;
config.cert = cert ? Buffer.from(cert, 'base64') : null;
config.key = key ? Buffer.from(key, 'base64') : null;
config.pfx = pfx ? Buffer.from(pfx, 'base64') : null;
config.passphrase = passphrase || null;
}
2016-10-05 04:43:48 +00:00
// Add the cookie header to the request
const cookieJar = renderedRequest.cookieJar;
const jar = jarFromCookies(cookieJar.cookies);
const existingCookieHeaderName = Object.keys(config.headers).find(k => k.toLowerCase() === 'cookie');
const cookieString = await cookieHeaderValueForUri(jar, config.url);
2016-10-05 04:43:48 +00:00
if (cookieString && existingCookieHeaderName) {
config.headers[existingCookieHeaderName] += `; ${cookieString}`;
} else if (cookieString) {
config.headers['Cookie'] = cookieString;
2016-10-05 04:43:48 +00:00
}
// Do DNS lookup ourselves
// We don't want to let NodeJS do DNS, because it doesn't use
// getaddrinfo by default. Instead, it first tries to reach out
// to the network.
2016-10-05 04:43:48 +00:00
const originalUrl = config.url;
2016-10-26 22:13:16 +00:00
config.url = await swapHost(config.url, forceIPv4);
// TODO: Handle redirects ourselves
2016-10-02 22:10:43 +00:00
const requestStartTime = Date.now();
const req = networkRequest(config, async (err, networkResponse) => {
2016-07-20 21:15:11 +00:00
if (err) {
2016-09-28 21:17:57 +00:00
const isShittyParseError = err.toString() === 'Error: Parse Error';
2016-10-26 22:13:16 +00:00
// Failed to connect while prioritizing IPv6 address, fallback to IPv4
const isNetworkRelatedError = (
err.code === 'ECONNREFUSED' || // Could not talk to server
2016-11-19 08:38:26 +00:00
err.code === 'EHOSTUNREACH' || // Could not reach host
err.code === 'ENETUNREACH' // Could not access the network
);
if (!forceIPv4 && isNetworkRelatedError) {
2016-10-26 22:13:16 +00:00
console.log('-- Falling back to IPv4 --');
_actuallySend(renderedRequest, workspace, settings, true).then(resolve, reject);
2016-10-26 22:13:16 +00:00
return;
}
2016-09-28 21:17:57 +00:00
let message = err.toString();
if (isShittyParseError) {
2016-10-06 16:52:26 +00:00
message = `Error parsing response after ${err.bytesParsed} bytes.\n\n`;
message += `Code: ${err.code}`;
2016-09-28 21:17:57 +00:00
}
2016-11-10 01:15:27 +00:00
await models.response.create({
url: originalUrl,
parentId: renderedRequest._id,
statusMessage: 'Error',
2016-09-28 21:17:57 +00:00
error: message
2016-07-20 21:15:11 +00:00
});
2016-09-28 21:17:57 +00:00
2016-07-20 21:15:11 +00:00
return reject(err);
}
// Format the headers into Insomnia format
// TODO: Move this to a better place
const headers = [];
for (const name of Object.keys(networkResponse.headers)) {
const tmp = networkResponse.headers[name];
const values = Array.isArray(tmp) ? tmp : [tmp];
for (const value of values) {
headers.push({name, value});
}
}
2016-10-05 04:43:48 +00:00
// Update the cookie jar
// NOTE: Since we're doing own DNS, we can't rely on Request to do this
const setCookieHeaders = util.getSetCookieHeaders(headers);
if (setCookieHeaders.length) {
for (const h of setCookieHeaders) {
try {
jar.setCookieSync(h.value, originalUrl);
} catch (e) {
console.warn('Failed to parse set-cookie', h.value);
}
2016-10-05 16:34:13 +00:00
}
const cookies = await cookiesFromJar(jar);
await models.cookieJar.update(cookieJar, {cookies});
2016-10-05 04:43:48 +00:00
}
2016-07-20 21:15:11 +00:00
const responsePatch = {
parentId: renderedRequest._id,
statusCode: networkResponse.statusCode,
statusMessage: networkResponse.statusMessage,
2016-10-05 04:43:48 +00:00
url: originalUrl, // TODO: Handle redirects somehow
2016-10-27 16:45:44 +00:00
contentType: networkResponse.headers['content-type'] || '',
elapsedTime: networkResponse.elapsedTime,
bytesRead: networkResponse.body ? networkResponse.body.length : 0,
2016-10-26 23:22:15 +00:00
body: networkResponse.body.toString('base64'),
encoding: 'base64',
headers: headers
2016-07-20 21:15:11 +00:00
};
2016-04-28 07:30:26 +00:00
2016-11-10 01:15:27 +00:00
models.response.create(responsePatch).then(resolve, reject);
2016-09-13 18:31:07 +00:00
});
// Kind of hacky, but this is how we cancel a request.
cancelRequestFunction = async () => {
2016-09-13 18:31:07 +00:00
req.abort();
2016-11-10 01:15:27 +00:00
await models.response.create({
url: originalUrl,
2016-09-13 18:31:07 +00:00
parentId: renderedRequest._id,
elapsedTime: Date.now() - requestStartTime,
2016-09-13 18:31:07 +00:00
statusMessage: 'Cancelled',
error: 'The request was cancelled'
});
return reject(new Error('Cancelled'));
2016-09-13 18:31:07 +00:00
}
2016-07-20 21:15:11 +00:00
})
}
export async function send (requestId, environmentId) {
// First, lets wait for all debounces to finish
await util.delay(DEBOUNCE_MILLIS * 2);
2016-11-10 01:15:27 +00:00
const request = await models.request.getById(requestId);
const settings = await models.settings.getOrCreate();
let renderedRequest;
try {
renderedRequest = await getRenderedRequest(request, environmentId);
} catch (e) {
// Failed to render. Must be the user's fault
2016-11-10 01:15:27 +00:00
return await models.response.create({
parentId: request._id,
statusCode: STATUS_CODE_RENDER_FAILED,
error: e.message
});
}
// Get the workspace for the request
const ancestors = await db.withAncestors(request);
const workspace = ancestors.find(doc => doc.type === models.workspace.type);
// Render succeeded so we're good to go!
return await _actuallySend(renderedRequest, workspace, settings);
}