javax.mail: Sending without authentication hangs inside Transport.send() - authentication

I am trying to send error reports from an application using a local send-only Postfix server. The server works fine (I have tested it using both telnet and mail) but I can't get the code below to work:
Properties props = new Properties();
props.put("mail.smtp.host",host); // "localhost"
props.put("mail.smtp.port",port); // "25"
props.put("mail.smtp.auth",auth); // false
props.put("mail.smtp.starttls.enable",tls); // false
props.put("mail.smtp.ssl.enable",ssl); // false
props.put("mail.smtp.sendpartial",true);
Session session = Session.getDefaultInstance(props);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
msg.setSubject(subject);
msg.setContent(content,"text/plain");
Transport.send(msg);
I have traced it up to the final call to send(), and it just hangs at that point -- it never returns from the call.
If I set "mail.smtp.auth" to true and replace the call to Transport.send() with this code:
Transport transport = s.getTransport("smtp");
transport.connect(host,Integer.parseInt(port,10),"foo","bar");
transport.sendMessage(msg,msg.getRecipients(Message.RecipientType.TO));
transport.close();
then it hangs inside the call to connect(). The same as true if I set "mail.smtp.auth" to false and set the username and password to null in the call to connect().
In /var/log/mail.log I see this:
connect from localhost[127.0.0.1]
and after I kill the hung process:
lost connection after CONNECT from localhost[127.0.0.1]
disconnect from localhost[127.0.0.1] commands=0/0
Can anyone see what I've done wrong here?

The problem turned out to be that the user "postfix" was being blocked by iptables. Adding an ACCEPT rule for postfix solved the problem.

Related

Blazor WebAssembly MQTT over websockets not working

I'm trying to implement an mqtt over websocket client subscriber in Blazor using Paho. The problem is it insists on using wss instead of ws and throws an ERR_SSL_PROTOCOL_ERROR error upon connection.
Here's a simplified code block:
var mqtt;
var host = "api.mydomainexample.com";
var port = 1884;
function onConnect(){
console.log("connected ! Now listening for messages ..");
mqtt.subscribe("someTopic");
}
function onFailure(message){
console.log("connection to host failed: " + message);
}
function onMessageArrived(msg){
var message = "Message received on topic '"+ msg.destinationName +"': "+ msg.payloadString;
console.log(message);
}
function mqttConnect() {
console.log("connecting to " + host + " ..");
mqtt = new Paho.MQTT.Client(host, port, clientid);
var options = {
timeout: 3,
onSuccess: onConnect,
onFailure: onFailure,
useSSL: false
};
mqtt.onMessageArrived = onMessageArrived;
mqtt.connect(options);
}
I copied this code into an html page created in notepad, called the function from the html body and ran the file in browser. It worked and subscribed well.
Also I added useSSL: false in the connection options although I didnt have it before but still didnt work.
here's the error I'm having from console:
WebSocket connection to 'wss://api.mydomainexample:1884/mqtt' failed: Error in connection establishment: net::ERR_SSL_PROTOCOL_ERROR
I also changed my projects launch settings so that it launches as http and not https because based on this answer, I cannot use a ws from a page loaded through https.
Any ideas ? Can't I just connect to a websocket without certificate in blazor?
Ok it turns out that when creating the blazor application, there is an option to 'configure on https' where this option causes requests redirection from http to https and consequently asks for secure wss instead of ws.
Hope this helps someone!

MailKit - Unexpected behaviour of Dissconnect

I use MailKit to send messages, app runs on Win 10.
I wrote my Mailservice, and my project used this service to send infos, warnings or fault notifications to me.
In the case that more messages should be sent within a short periode (loop ?), I get the error 'Too many connections open .."
Ok. I used 'Await' to await the end of each step and so I await the end of the disconnect-operation.
How can I get too many open connections?
Private Shared Async Function TransmitMail(mail As MimeMessage) As Task(Of Boolean)
Try
Using client = New SmtpClient()
With client
Await .ConnectAsync(Host, 587, False)
Await .AuthenticateAsync(UserName, Password)
Await .SendAsync(mail)
Await .DisconnectAsync(True)
Threading.Thread.Sleep(5000) <<<<--
End With |
End Using |
Return True |
``` |
After adding a explicite sleep of about 5 seconds, the problem is gone.
Any explaination?
Thanks for helping.
With best regards
Gerhard
Just because you closed and cleaned up the socket on the local machine doesn't mean that the server has had a chance to close and cleanup the socket at the remote end.

socket http lua to set timeout

I am trying to create a function that can call REST with the http socket lua.
And I tried to set the timeout this way. But, when I run this function, the timeout is not running. How should I set the timeout?
local http = require "socket.http"
local socket = require "socket"
local respbody = {}
http.request {
method = req_method,
url = req_url,
source = ltn12.source.string(req_body),
headers =
{
["Content-Type"] = req_content_type,
["content-length"] = string.len(req_body),
["Host"] = host,
},
sink = ltn12.sink.table(respbody),
create = function()
local req_sock = socket.tcp()
req_sock:settimeout(3, 't')
return req_sock
end,
}
You may want to check lua-http. I use it to call REST and works like a charm. I am not an expert but, as far as I can tell, it is a good LUA http implementation.
You can set a two seconds timeout as simple as:
local http_client = require "http.client"
local myconnection = http_client.connect {
host = "myrestserver.domain.com";
timeout = 2;
}
Full documentation in here.
if I implement the example with my requirements, will it be like this? cmiiw
local http_client = require "http.client"
local req_body = "key1=value1&key2=value2"
local myconnection = http_client.connect {
method = "POST";
url = "myrestserver.domain.com/api/example";
host = "myrestserver.domain.com";
source = req_body
headers = {
["Content-Type"] = "application/x-www-form-urlencoded",
["content-length"] = string.len(req_body),
},
timeout = 2;
}
LuaSocket implicitly set http.TIMEOUT to the socket object.
Also you have to remember that socket timeout is not the same as request timeout.
Socket timeout means timeout for each operation independently. For simple case you can wait connection up to timeout seconds and then each read operation can take up to timeout seconds. And because of HTTP client read response line by line you get timeout seconds for each header plus for each body chunk. Also, there may be redirecions where each redirection is a separate HTTP request/response. If you use TLS there also will be hendshake after connection which also took several send/receive operation.
I did not use lua-http module and do not know how timeout implemented there.
But I prefer use modules like cURL if I really need to restrict request timeout.

strophe connect openfire error

I input a jid and pwd on a html form, and use Strophe to connect to openfire, but when I press the login button, the xmpp server response is error 302.
I enabled the option on openfire, and restarted it.
var BOSH_SERVICE = 'http://ip:7070/http-bind';
$('#btn-login').click(function() {
if(!connected) {
connection = new Strophe.Connection(BOSH_SERVICE);
connection.connect($("#input-jid").val(), $("#input-pwd").val(), onConnect);
jid = $("#input-jid").val();
}
});
It seems a little harder than to use smack in java because of the network problem?
The problem is in the uri specified in BOSH_SERVICE.
Correct uri is:
http://ip:7070/http-bind/
Pay attention to the / at the bottom of the string.

Google login in PHP backend and JS frontend

Front end is 100% JS. User click on sign in button and an authResult['code'] is received and send via ajax to localhost/api/user/login which has the following content:
$code = $data['code'];
require_once 'Google/Client.php';
$client = new Google_Client();
$client->setClientId('xxxxxx');
$client->setClientSecret('xxxxx');
$client->setRedirectUri('http://localhost:8080');
$client->setScopes('email'); //Why do I need this? I already set scope in JS.
$client->authenticate($code); //It fails here. with no error. just 400 bad request.
$token = json_decode($client->getAccessToken());
$reqUrl = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=' .
$token->access_token;
$req = new Google_HttpRequest($reqUrl);
$tokenInfo = json_decode(
$client::getIo()->authenticatedRequest($req)->getResponseBody());
//Check errors.
//Save user personal info in database
//Set login sessions
Why do I need to set scopes if I already set them in javascript?
Why is it failing when authenticate function is called? Im getting no erros.
Why do I need a setRedirectUri() when it is on the backend?
You don't need to set scopes in this case.
(see answer 3, but also): Check your client ID matches the one used in the Javascript, and that the client secret is exactly as in the console (no trailing/leading spaces).
Changing your redirecturi to 'postmessage' - this is the string used when the code was generated via the Javascript process.
You can also try manually constructing the URL and calling it with curl to make sure everything is as you expect: https://developers.google.com/accounts/docs/OAuth2WebServer#handlingtheresponse