Lua http request hangs - http

I am calling lua http.request with timeout. before i make http request if network is down i will get http status as network unreachable but if network is not available after Http request it just hangs. is there any way to handle this issue.
local isHttps = string.match(type(url) == "table" and url.url or url, "^https:")
local http = isHttps and require("ssl.https") or require("socket.http")
local r,s,h
if isHttps then
http.TIMEOUT = 300
r,s,h = http.request ({
url = url,
method = "GET",
sink = ltn12.sink.table(results),
headers= ["Cache-Control"]
= "no-cache"["X-Token"]=config.token
})

Related

how to route from one api to other fastapi

I am trying to redirect request from protected_api() to login() function in fastapi. but it fails with messages
Failed to fetch.
Possible Reasons:
CORS
Network Failure
URL scheme must be "http" or "https" for CORS request.
what could be the issue and how can be redirect from one api to other
#app.get("/protected_api")
async def protected_api():
resp = RedirectResponse("https://localhost:5000/token")
return resp
#app.post("/token", response_model=Token)
async def login(form_data: OAuth2PasswordRequestForm = Depends()): # login function to get access token
print('In login fun value of form_data dict.....%s' % form_data.__dict__)
user = authenticate_user(fake_users_db, form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(seconds=ACCESS_TOKEN_EXPIRE_SECONDS)
access_token = create_access_token(
data={"sub": user.username}, expires_delta=access_token_expires
)
print('Value of access_token in login fun ......%s\n' % access_token)
return {"access_token": access_token, "token_type": "bearer"}
You're having clients ping A (/protected_api) but sending a response from B (/token). They are not the same endpoint, so this involves CORS. Try using CORSMiddleware with FastAPI to resolve this issue.

post request with flask-socketio cannot connect to proxy

I've tested my code in an environment(win10) with proxy settings, I didn't have to specify proxy settings and it works with only flask, but then when I start with sockio.run, it throws me the error :
HTTPSConnectionPool(host='notify-api.line.me', port=443): Max retries exceeded with url: /api/notify?message=12345 (Caused by ProxyError('Cannot connect to proxy.', OSError(0, 'Error')))
I have no idea why is this happening, I tried adding http and https proxies into the requests parameter, setting cors_allowed_origins='*', still doesn't work.
Am I missing some headers to make it work? And why does it work without socketio?
import flask
import requests
from flask_socketio import SocketIO, emit
from engineio.async_drivers import gevent
app = flask.Flask(__name__)
app.config["DEBUG"] = True
socketio = SocketIO(app, cors_allowed_origins='*')
#app.route('/', methods=['GET'])
def home():
headers = {
"Authorization": "Bearer " + 'qajyC1fFTqsabb3cTbnk5zCqDjRspZkDQwPPmeNbJCx',
"Content-Type" : "application/x-www-form-urlencoded"
}
payload = {'message': '12345'}
r = requests.post("https://notify-api.line.me/api/notify", headers = headers, params = payload)
return "12345"
socketio.run(app,host='10.110.50.51', port=8080)
Adding proxy to request doesn't work too
http_proxy = "http://10.xx.xxx.xxx:8080"
https_proxy = "https://10.xx.xxx.xxx:8080"
proxyDict = {
"http" : http_proxy,
"https" : https_proxy,
}
headers = {
"Authorization": "Bearer " +
'qajyC1fFTqsabb3cTbnk5zCqDjRspZkDQwPPmeNbJCx',
"Content-Type" : "application/x-www-form-urlencoded"
}
payload = {'message': '12345'}
r = requests.post("https://notify-api.line.me/api/notify", headers= headers, params = payload, proxies=proxyDict)
return "12345"
seems like it's the problem with urllib3 package,
changing the proxy https to http solved my problem
http_proxy = "http://10.xx.xx.xxx:8080"
https_proxy = "http://10.xx.xx.xxx:8080"
The https_proxy goes through http instead of https and establish handshake!!
But I'm still confused why this problem only appears when using socketio running the app

NTLM requests in K6 and .NEŠ¢ Core

I wrote load testing of my API with NTLM auth (here I additionally check if NTLM authorized user is presend in Database). During resquest:
var url = 'https://login:*****#localhost:xxxx/api/authorization/logon';
var payload = { };
var params = {
headers: {
'Content-Type': 'application/json'
},
};
let response = http.post(url, params, {auth: "ntlm"});
check(response, {
'status is 200': (r) => r.status === 200
});
}
i have an error:
error="Post "https://user:*****#localhost:xxx/api/authorization/logon": stream error: stream ID 3; HTTP_1_1_REQUIRED".
Why? Kestrel serve HTTP/1.1
This is an issue in the way Go standard library's HTTP client operates, that is described here in detail, in which for HTTPS endpoints, connection is forcibly upgraded to HTTP/2.0, which is not supported by the NTLM protocol.
I'm not sure, but maybe you can disable this connection upgrade in Kestrel.
you can set in your global system environment to enable HTTP1.1

Dart Http Package request timeout

While using http package in my flutter app, I encountered a slight issue. I am testing on localhost and when I post something in database using http.post, it doesn't return response for default time (i.e. 60s I think) when server is not running. And when I start the apache and mysql services within the timeout, it posts the data in the server . Is there any way to reduce the timeout of the http requests in dart http package? Or is there any alternative solution?
This is for http package
final response = await http.post(Url).timeout(Duration(seconds: 5));
And this is for Dio package (recommend to test this package)
BaseOptions options = new BaseOptions(
baseUrl: baseUrl,
connectTimeout: 10000, //10 seconds
receiveTimeout: 10000,
);
Dio dio = new Dio(options);
Response<dynamic> response = await dio.post(url, data: mapData);
You have two options availabe.
Reduce the timeout on the HttpClient
final client = new HttpClient();
client.connectionTimeout = const Duration(seconds: 10);
This will apply to all request made by the same client. If the request exceeds this timeout, a SocketException is thrown.
Set a per request timeout
You can set a timeout on any Future using the Future.timeout method.
try {
..
final request = await client.get(...);
final response = await request.close().timeout(const Duration(seconds: 10));
// more code
} on TimeoutException catch (e) {
// handle timeout
}

Transfer UDP socket in node.js from Application to HTTP

Is it possible to transfer a Socket coming from a application to http via NodeJS?
I send my socket with a application (in c++) in UDP or TCP(if impossible in UDP...) to NodeJS.
My script from NodeJS:
var server = dgram.createSocket("udp4");
server.on("message", function (content, rinfo)
{
console.log("socket: " + content + " from " + rinfo.address + ":" + rinfo.port); });
server.on("listening", function () {
});
server.bind(7788);
Up to now does that function, but then how to transfer my socket to Socket.io for example?
I would like to send the socket to Socket.io (for example) for transfer the socket to HTTP. By using a function like this for example, but without renew a establishing a connection to socket.io :
io.sockets.on('connection', function (socket) {
socket.emit(content);
});
Thanks you for your help.
++ Metra.
Here's a complete example with a socket.io server, a web server sending out a very simple page (it will just log all messages to console) and an UDP socket listening for messages, passing them to all connected clients:
var http = require('http'),
dgram = require('dgram'),
socketio = require('socket.io');
var app = http.createServer(handleRequest),
io = socketio.listen(app),
socket = dgram.createSocket('udp4');
socket.on('message', function(content, rinfo) {
console.log('got message', content, 'from', rinfo.address, rinfo.port);
io.sockets.emit('udp message', content.toString());
});
function handleRequest(req, res) {
res.writeHead(200, {'content-type': 'text/html'});
res.end("<!doctype html> \
<html><head> \
<script src='/socket.io/socket.io.js'></script> \
<script> \
var socket = io.connect('localhost', {port: 8000}); \
socket.on('udp message', function(message) { console.log(message) }); \
</script></head></html>");
}
socket.bind(7788);
app.listen(8000);
Update: As io.sockets.emit shows, all messages received on the UDP port 7788 are sent to all connected clients. If you want to route them based on some data in the message or similar, you could use Socket.IO's "room" feature: io.sockets.of(someRoom).emit. In the connection handler for Socket.IO, you can join each client to some room.

Resources