2016-10-02 20:57:00 +00:00
|
|
|
import networkRequest from 'request';
|
|
|
|
import {parse as urlParse} from 'url';
|
2016-11-23 19:33:24 +00:00
|
|
|
import mime from 'mime-types';
|
|
|
|
import {basename as pathBasename} from 'path';
|
2016-11-10 05:56:23 +00:00
|
|
|
import * as models from '../models';
|
2016-10-02 20:57:00 +00:00
|
|
|
import * as querystring from './querystring';
|
2016-11-10 05:56:23 +00:00
|
|
|
import * as util from './misc.js';
|
2016-12-08 20:29:40 +00:00
|
|
|
import {DEBOUNCE_MILLIS, STATUS_CODE_RENDER_FAILED, CONTENT_TYPE_FORM_DATA, CONTENT_TYPE_FORM_URLENCODED, getAppVersion} from './constants';
|
2016-12-08 18:19:18 +00:00
|
|
|
import {jarFromCookies, cookiesFromJar} from './cookies';
|
2017-02-27 21:00:13 +00:00
|
|
|
import {setDefaultProtocol, hasAcceptHeader, hasUserAgentHeader} from './misc';
|
2016-10-02 20:57:00 +00:00
|
|
|
import {getRenderedRequest} from './render';
|
2016-11-22 22:26:52 +00:00
|
|
|
import * as fs from 'fs';
|
2016-11-29 20:55:31 +00:00
|
|
|
import * as db from './database';
|
2016-04-09 21:08:55 +00:00
|
|
|
|
2016-12-30 23:06:27 +00:00
|
|
|
// Defined fallback strategies for DNS lookup. By default, request uses Node's
|
|
|
|
// default dns.resolve which uses c-ares to do lookups. This doesn't work for
|
|
|
|
// some people, so we also fallback to IPv6 then IPv4 to force it to use
|
|
|
|
// getaddrinfo (OS lookup) instead of c-ares (external lookup).
|
2016-12-23 19:31:38 +00:00
|
|
|
const FAMILY_FALLBACKS = [
|
2016-12-30 23:06:27 +00:00
|
|
|
null, // Use the request library default lookup
|
2016-12-23 19:31:38 +00:00
|
|
|
6, // IPv6
|
2017-03-03 20:09:08 +00:00
|
|
|
4 // IPv4
|
2016-12-23 19:31:38 +00:00
|
|
|
];
|
|
|
|
|
2016-09-13 18:31:07 +00:00
|
|
|
let cancelRequestFunction = null;
|
|
|
|
|
2016-10-02 20:57:00 +00:00
|
|
|
export function cancelCurrentRequest () {
|
2016-09-13 18:31:07 +00:00
|
|
|
if (typeof cancelRequestFunction === 'function') {
|
|
|
|
cancelRequestFunction();
|
|
|
|
}
|
2016-10-02 20:57:00 +00:00
|
|
|
}
|
2016-07-28 20:10:26 +00:00
|
|
|
|
2016-10-02 20:57:00 +00:00
|
|
|
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
|
2016-07-28 20:10:26 +00:00
|
|
|
followAllRedirects: true,
|
2016-10-11 17:40:17 +00:00
|
|
|
followRedirect: true,
|
2016-11-22 19:42:10 +00:00
|
|
|
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
|
2016-07-22 21:35:49 +00:00
|
|
|
gzip: true,
|
|
|
|
|
|
|
|
// Time the request
|
2016-07-28 20:10:26 +00:00
|
|
|
time: true,
|
|
|
|
|
|
|
|
// SSL Checking
|
2016-08-15 17:04:36 +00:00
|
|
|
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
|
2017-03-03 20:09:08 +00:00
|
|
|
encoding: null
|
2016-04-09 21:08:55 +00:00
|
|
|
};
|
|
|
|
|
2016-11-22 19:42:10 +00:00
|
|
|
// Set the body
|
|
|
|
if (renderedRequest.body.mimeType === CONTENT_TYPE_FORM_URLENCODED) {
|
2017-03-03 20:09:08 +00:00
|
|
|
config.body = querystring.buildFromParams(renderedRequest.body.params || [], true);
|
2016-11-22 19:42:10 +00:00
|
|
|
} else if (renderedRequest.body.mimeType === CONTENT_TYPE_FORM_DATA) {
|
2016-11-23 19:33:24 +00:00
|
|
|
const formData = {};
|
|
|
|
for (const param of renderedRequest.body.params) {
|
|
|
|
if (param.type === 'file' && param.fileName) {
|
2017-01-27 01:00:27 +00:00
|
|
|
// Check if file exists first (read stream won't right away)
|
|
|
|
fs.statSync(param.fileName);
|
2016-11-23 19:33:24 +00:00
|
|
|
formData[param.name] = {
|
2017-01-27 01:00:27 +00:00
|
|
|
value: fs.createReadStream(param.fileName),
|
2016-11-23 19:33:24 +00:00
|
|
|
options: {
|
2016-12-30 23:06:27 +00:00
|
|
|
filename: pathBasename(param.fileName),
|
2016-11-23 19:33:24 +00:00
|
|
|
contentType: mime.lookup(param.fileName) // Guess the mime-type
|
|
|
|
}
|
2017-03-03 20:09:08 +00:00
|
|
|
};
|
2016-11-23 19:33:24 +00:00
|
|
|
} else {
|
|
|
|
formData[param.name] = param.value || '';
|
|
|
|
}
|
|
|
|
}
|
|
|
|
config.formData = formData;
|
2016-11-23 23:57:34 +00:00
|
|
|
} else if (renderedRequest.body.fileName) {
|
2017-01-27 01:00:27 +00:00
|
|
|
// Check if file exists first (read stream won't right away)
|
2017-02-01 03:01:27 +00:00
|
|
|
config.body = fs.readFileSync(renderedRequest.body.fileName);
|
2016-11-22 19:42:10 +00:00
|
|
|
} else {
|
|
|
|
config.body = renderedRequest.body.text || '';
|
|
|
|
}
|
2016-08-31 20:50:27 +00:00
|
|
|
|
2016-11-22 19:42:10 +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) {
|
2016-11-22 19:42:10 +00:00
|
|
|
headers[header.name] = header.value;
|
2016-04-12 00:39:49 +00:00
|
|
|
}
|
2016-04-09 21:08:55 +00:00
|
|
|
}
|
2016-11-22 19:42:10 +00:00
|
|
|
config.headers = headers;
|
|
|
|
|
2016-12-08 20:29:40 +00:00
|
|
|
// Set the Accept header if it doesn't exist
|
|
|
|
if (!hasAcceptHeader(renderedRequest.headers)) {
|
|
|
|
config.headers['Accept'] = '*/*';
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set UserAgent if it doesn't exist
|
|
|
|
if (!hasUserAgentHeader(renderedRequest.headers)) {
|
2017-03-03 20:09:08 +00:00
|
|
|
config.headers['User-Agent'] = `insomnia/${getAppVersion()}`;
|
2016-12-08 20:29:40 +00:00
|
|
|
}
|
|
|
|
|
2016-11-22 19:42:10 +00:00
|
|
|
// Set the URL, including the query parameters
|
|
|
|
const qs = querystring.buildFromParams(renderedRequest.parameters);
|
2016-11-23 19:33:24 +00:00
|
|
|
const url = querystring.joinUrl(renderedRequest.url, qs);
|
2016-11-22 19:42:10 +00:00
|
|
|
config.url = util.prepareUrlForSending(url);
|
2016-04-17 01:52:10 +00:00
|
|
|
|
2016-04-28 07:30:26 +00:00
|
|
|
return Object.assign(config, patch);
|
2016-10-02 20:57:00 +00:00
|
|
|
}
|
2016-04-28 07:30:26 +00:00
|
|
|
|
2016-12-23 19:31:38 +00:00
|
|
|
export function _actuallySend (renderedRequest, workspace, settings, familyIndex = 0) {
|
2017-02-01 20:21:14 +00:00
|
|
|
return new Promise(async resolve => {
|
2016-12-08 23:29:45 +00:00
|
|
|
async function handleError (err, prefix = '') {
|
2017-02-01 20:21:14 +00:00
|
|
|
resolve({
|
2016-12-08 23:29:45 +00:00
|
|
|
url: renderedRequest.url,
|
|
|
|
parentId: renderedRequest._id,
|
|
|
|
elapsedTime: 0,
|
|
|
|
statusMessage: 'Error',
|
|
|
|
error: prefix ? `${prefix}: ${err.message}` : err.message
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2016-08-15 17:04:36 +00:00
|
|
|
// 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;
|
2016-09-12 20:04:15 +00:00
|
|
|
const proxy = proxyHost ? setDefaultProtocol(proxyHost) : null;
|
2016-08-15 17:04:36 +00:00
|
|
|
|
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);
|
2016-12-08 23:29:45 +00:00
|
|
|
} catch (err) {
|
|
|
|
return handleError(err, 'Failed to setup request');
|
2016-11-22 22:26:52 +00:00
|
|
|
}
|
2016-07-20 21:15:11 +00:00
|
|
|
|
2016-12-08 23:29:45 +00:00
|
|
|
try {
|
|
|
|
// 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;
|
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
return handleError(err, 'Failed to set certificate');
|
2016-11-29 20:55:31 +00:00
|
|
|
}
|
|
|
|
|
2016-12-08 23:29:45 +00:00
|
|
|
try {
|
|
|
|
// Add the cookie header to the request
|
|
|
|
config.jar = networkRequest.jar();
|
|
|
|
config.jar._jar = jarFromCookies(renderedRequest.cookieJar.cookies);
|
|
|
|
} catch (err) {
|
|
|
|
return handleError(err, 'Failed to set cookie jar');
|
|
|
|
}
|
2016-10-02 20:57:00 +00:00
|
|
|
|
2016-12-08 18:42:45 +00:00
|
|
|
// Set the IP family. This fallback behaviour is copied from Curl
|
2016-12-08 23:29:45 +00:00
|
|
|
try {
|
2016-12-23 19:31:38 +00:00
|
|
|
const family = FAMILY_FALLBACKS[familyIndex];
|
|
|
|
if (family) {
|
|
|
|
config.family = family;
|
|
|
|
}
|
2016-12-08 23:29:45 +00:00
|
|
|
} catch (err) {
|
|
|
|
return handleError(err, 'Failed to set IP family');
|
|
|
|
}
|
2016-12-08 18:42:45 +00:00
|
|
|
|
2016-12-08 18:19:18 +00:00
|
|
|
config.callback = 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
|
2016-10-31 17:35:15 +00:00
|
|
|
const isNetworkRelatedError = (
|
2016-12-30 23:06:27 +00:00
|
|
|
err.code === 'EAI_AGAIN' || // No entry
|
2016-12-23 19:31:38 +00:00
|
|
|
err.code === 'ENOENT' || // No entry
|
2016-12-08 20:29:40 +00:00
|
|
|
err.code === 'ENODATA' || // DNS resolve failed
|
|
|
|
err.code === 'ENOTFOUND' || // Could not resolve DNS
|
2016-10-31 17:35:15 +00:00
|
|
|
err.code === 'ECONNREFUSED' || // Could not talk to server
|
2016-11-19 08:38:26 +00:00
|
|
|
err.code === 'EHOSTUNREACH' || // Could not reach host
|
2016-10-31 17:35:15 +00:00
|
|
|
err.code === 'ENETUNREACH' // Could not access the network
|
|
|
|
);
|
|
|
|
|
2016-12-23 19:31:38 +00:00
|
|
|
const nextFamilyIndex = familyIndex + 1;
|
|
|
|
if (isNetworkRelatedError && nextFamilyIndex < FAMILY_FALLBACKS.length) {
|
|
|
|
const family = FAMILY_FALLBACKS[nextFamilyIndex];
|
|
|
|
console.log(`-- Falling back to family ${family} --`);
|
2017-02-01 20:21:14 +00:00
|
|
|
|
|
|
|
return _actuallySend(
|
2016-12-30 23:06:27 +00:00
|
|
|
renderedRequest, workspace, settings, nextFamilyIndex
|
2017-02-02 15:04:51 +00:00
|
|
|
).then(resolve);
|
2016-10-26 22:13:16 +00:00
|
|
|
}
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
2017-02-01 20:21:14 +00:00
|
|
|
return resolve({
|
2016-12-08 18:19:18 +00:00
|
|
|
url: config.url,
|
2016-08-15 17:04:36 +00:00
|
|
|
parentId: renderedRequest._id,
|
2016-11-27 21:42:38 +00:00
|
|
|
statusMessage: 'Error',
|
2016-09-28 21:17:57 +00:00
|
|
|
error: message
|
2016-07-20 21:15:11 +00:00
|
|
|
});
|
|
|
|
}
|
2016-07-22 20:38:28 +00:00
|
|
|
|
2016-12-08 23:29:45 +00:00
|
|
|
// handle response headers
|
2016-08-15 17:04:36 +00:00
|
|
|
const headers = [];
|
2016-12-08 23:29:45 +00:00
|
|
|
try {
|
|
|
|
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-08-15 17:04:36 +00:00
|
|
|
}
|
2016-12-08 23:29:45 +00:00
|
|
|
} catch (err) {
|
|
|
|
return handleError(err, 'Failed to parse response headers');
|
2016-08-15 17:04:36 +00:00
|
|
|
}
|
|
|
|
|
2017-02-16 17:38:59 +00:00
|
|
|
try {
|
|
|
|
const cookies = await cookiesFromJar(config.jar._jar);
|
|
|
|
await models.cookieJar.update(renderedRequest.cookieJar, {cookies});
|
|
|
|
} catch (err) {
|
|
|
|
return handleError(err, 'Failed to update cookie jar');
|
2016-12-08 23:29:45 +00:00
|
|
|
}
|
2016-10-05 04:43:48 +00:00
|
|
|
|
2016-12-08 23:47:24 +00:00
|
|
|
let contentType = '';
|
|
|
|
if (networkResponse.headers) {
|
2017-03-03 20:09:08 +00:00
|
|
|
contentType = networkResponse.headers['content-type'] || '';
|
2016-12-08 23:47:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
let bytesRead = 0;
|
|
|
|
if (networkResponse.body) {
|
|
|
|
bytesRead = networkResponse.body.length;
|
|
|
|
}
|
|
|
|
|
|
|
|
const bodyEncoding = 'base64';
|
2017-02-01 20:21:14 +00:00
|
|
|
return resolve({
|
2016-08-15 17:04:36 +00:00
|
|
|
parentId: renderedRequest._id,
|
2016-07-22 20:38:28 +00:00
|
|
|
statusCode: networkResponse.statusCode,
|
|
|
|
statusMessage: networkResponse.statusMessage,
|
2016-12-08 18:19:18 +00:00
|
|
|
url: config.url,
|
2016-12-08 23:47:24 +00:00
|
|
|
contentType: contentType,
|
2016-07-22 20:38:28 +00:00
|
|
|
elapsedTime: networkResponse.elapsedTime,
|
2016-12-08 23:47:24 +00:00
|
|
|
bytesRead: bytesRead,
|
|
|
|
body: networkResponse.body.toString(bodyEncoding),
|
|
|
|
encoding: bodyEncoding,
|
2016-08-15 17:04:36 +00:00
|
|
|
headers: headers
|
2017-02-01 20:21:14 +00:00
|
|
|
});
|
2016-12-08 18:19:18 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
const requestStartTime = Date.now();
|
|
|
|
const req = new networkRequest.Request(config);
|
2016-09-13 18:31:07 +00:00
|
|
|
|
|
|
|
// Kind of hacky, but this is how we cancel a request.
|
2016-10-02 20:57:00 +00:00
|
|
|
cancelRequestFunction = async () => {
|
2016-09-13 18:31:07 +00:00
|
|
|
req.abort();
|
|
|
|
|
2017-02-01 20:21:14 +00:00
|
|
|
resolve({
|
2016-12-08 18:19:18 +00:00
|
|
|
url: config.url,
|
2016-09-13 18:31:07 +00:00
|
|
|
parentId: renderedRequest._id,
|
2016-10-02 20:57:00 +00:00
|
|
|
elapsedTime: Date.now() - requestStartTime,
|
2016-09-13 18:31:07 +00:00
|
|
|
statusMessage: 'Cancelled',
|
|
|
|
error: 'The request was cancelled'
|
|
|
|
});
|
2017-03-03 20:09:08 +00:00
|
|
|
};
|
|
|
|
});
|
2016-10-02 20:57:00 +00:00
|
|
|
}
|
|
|
|
|
2016-11-10 00:01:10 +00:00
|
|
|
export async function send (requestId, environmentId) {
|
2016-10-02 20:57:00 +00:00
|
|
|
// First, lets wait for all debounces to finish
|
2016-11-29 20:55:31 +00:00
|
|
|
await util.delay(DEBOUNCE_MILLIS * 2);
|
2016-10-02 20:57:00 +00:00
|
|
|
|
2016-11-10 01:15:27 +00:00
|
|
|
const request = await models.request.getById(requestId);
|
|
|
|
const settings = await models.settings.getOrCreate();
|
2016-10-02 20:57:00 +00:00
|
|
|
|
|
|
|
let renderedRequest;
|
|
|
|
|
|
|
|
try {
|
2016-11-10 00:01:10 +00:00
|
|
|
renderedRequest = await getRenderedRequest(request, environmentId);
|
2016-10-02 20:57:00 +00:00
|
|
|
} catch (e) {
|
|
|
|
// Failed to render. Must be the user's fault
|
2017-02-08 02:39:28 +00:00
|
|
|
return {
|
2016-10-02 20:57:00 +00:00
|
|
|
parentId: request._id,
|
2016-11-29 20:55:31 +00:00
|
|
|
statusCode: STATUS_CODE_RENDER_FAILED,
|
2016-10-02 20:57:00 +00:00
|
|
|
error: e.message
|
2017-02-08 02:39:28 +00:00
|
|
|
};
|
2016-10-02 20:57:00 +00:00
|
|
|
}
|
|
|
|
|
2016-11-29 20:55:31 +00:00
|
|
|
// Get the workspace for the request
|
|
|
|
const ancestors = await db.withAncestors(request);
|
|
|
|
const workspace = ancestors.find(doc => doc.type === models.workspace.type);
|
|
|
|
|
2016-10-02 20:57:00 +00:00
|
|
|
// Render succeeded so we're good to go!
|
2017-02-01 20:21:14 +00:00
|
|
|
return _actuallySend(renderedRequest, workspace, settings);
|
2016-10-02 20:57:00 +00:00
|
|
|
}
|