I have written a code in poco c++ library that is supposed to send a request to the server to get some data. The is running from inside a docker container. And I am getting a "hostname not resolved" error. The sample code is as follow
//initialize session
Poco::SharedPtr<InvalidCertificateHandler> ptrCert = new AcceptCertificateHandler(false);
_ptrContext = new Context(Context::TLSV1_2_CLIENT_USE, "", "", "", Context::VERIFY_RELAXED, 9, false, "ALL:!ADH:!LOW:!EXP:!MD5:#STRENGTH");
_ptrContext->enableSessionCache(true);
// Disable SSL versions 2 & 3 and TLS versions 1.0 & 1.1
_ptrContext->disableProtocols(Poco::Net::Context::PROTO_SSLV2 | Poco::Net::Context::PROTO_SSLV3 | Poco::Net::Context::PROTO_TLSV1 | Poco::Net::Context::PROTO_TLSV1_1);
SSLManager::instance().initializeClient(0, ptrCert, _ptrContext);
_httpsession_secure = new HTTPSClientSession(_hostname, _port);
//build request
Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_POST, uri, Poco::Net::HTTPMessage::HTTP_1_1);
req.setContentLength(http_body.length());
req.setContentType("application/x-www-form-urlencoded");
// Send request
std::ostream &os = _httpsession_secure->sendRequest(req);
os << http_body;
// Wait for response
Poco::Net::HTTPResponse res;
std::istream &rs = _httpsession_secure->receiveResponse(res);
I have run a curl command as the CMD entry in the docker container, and the command is executing properly and giving the result. so that means the host is accessible inside the container. When I execute the code inside the container, it is failing. So I am surely missing something in the code. Please guide.
As per your answer to a my question in the comments, you are using:
_httpsession_secure = new HTTPSClientSession(_hostname, _port);
where _hostname is of the form to https://somehost.somedomain.
This is wrong, you must not pass an URI there, you just have to pass the domain name.
_hostname = "somehost.somedomain";
_httpsession_secure = new HTTPSClientSession(_hostname, _port);
Related
I used the python code below to create a port-forwarding session.
But it seems like the session is getting terminated in a few minutes? Can anyone tell me if I am missing something here.
My target is to bind a remote port (80) to a local port (8888).
self._session_parameters = {
"Target": self._instance_id,
"DocumentName": "AWS-StartPortForwardingSession",
"Parameters": {"portNumber"[str(self._remote_port)],
"localPortNumber":[str(self._remote_port)]}
self._response = self._ssm.start_session(
Target=self._session_parameters["Target"],
DocumentName=self._session_parameters["DocumentName"],
Parameters=self._session_parameters["Parameters"])
logger.info("Received response: %s", self._response["SessionId"])
self._session_id, self._token_value = (
self._response["SessionId"],
self._response["TokenValue"])
I keep getting a 520 error when trying to load s3 files via my code. It all works fine locally but when I upload the changes to my production server which is behind cloudflare I get a 520 error. Im using IIS 7.5 with asp classic code, here is my test page which is call everytime I want to download a file from s3.
https://www.gbca.org.au/aws_test.asp?fileID=9450&hash=688254C6503507FDDF8CF5D5CD113212&type=pam
It doesnt make sense and cloudflare doesnt provide any error messages.
' #########################################
function downloadFile()
Server.ScriptTimeout = 30000
set http = Server.CreateObject("Chilkat_9_5_0.Http")
http.UnlockComponent("BLUESIHttp_MHoP0vyTTL3e")
http.AwsAccessKey = AWS_ACCESS_KEY
http.AwsSecretKey = AWS_SECRET
if bucketType = "not-secure" then
http.AwsEndpoint = "s3.ap-southeast-1.amazonaws.com"
http.AwsRegion = "ap-southeast-1"
bucketLocale = AWS_BUCKET_ASIA
else
http.AwsEndpoint = "s3.ap-southeast-2.amazonaws.com"
http.AwsRegion = "ap-southeast-2"
bucketLocale = AWS_BUCKET_SECURE
end if
s3FileBytes = http.S3_DownloadBytes(bucketLocale, objectName)
If (http.LastMethodSuccess <> 1) Then
Response.Write "<pre>" & Server.HTMLEncode(http.LastErrorText) & "</pre>"
Response.End
End If
'response.write("AWS_BUCKET_ASIA: " & AWS_BUCKET_ASIA & "<br />")
'response.write("objectName: " & objectName& "<br />")
'response.write("s3FileBytes: " & ubound(s3FileBytes) & "<br />")
''response.write("s3FileBytes: " & filetype & "<br />")
''response.end()
Response.Clear
Response.AddHeader "Pragma", "no-cache"
Response.AddHeader "Content-Disposition", "attachment; filename=""" & filename & """"
Response.AddHeader "Content-Length", ubound(s3FileBytes)
Response.AddHeader "Connect", "close"
Response.ContentType = filetype
Response.BinaryWrite s3FileBytes
set AWS = nothing
'-- log the file access
'SQLLine = "INSERT INTO download_history (fileID, who, etc) VALUES (" & fileID & ")"
'DBCC.execute(SQLLine)
end function
https://www.gbca.org.au/aws_test.asp?fileID=9450&hash=688254C6503507FDDF8CF5D5CD113212&type=pam
Error 520 is essentially a catch-all response when something unexpected happens or when the origin server incorrectly interprets or does not tolerate a request due to a protocol violation or an empty response.
Besides reviewing your server logs, I recommend contacting Cloudflare support to review logs on their end as well. Unless you're on Enterprise Plan and explicitly requested to enable 100% logs, keep in mind they only keep 1% anonymized sampled logs for a limited time, so the logs might not be available if you contact them too late.
I've seen cases where nginx error upstream prematurely closed connection while reading response header from upstream was observed, upstream in this case means the origin server. This indicates that the origin server or the path along which it travelled was having issues during this period which caused Cloudflare to generate those 520 errors. Correlating the timestamp with your server's logs will give you better picture as to what the root cause could possibly be.
I am using the Zehon FTP utility on a ColdFusion 9 server. When I am FTP'ing files, it creates one directory, transfers about 16 files, then gives the message :
com.zehon.exception.FileTransferException: org.apache.commons.vfs.FileSystemException: Could not connect to FTP server on "ftpservername.com".
Here's the code:
<cfscript>
//FTP server information
host = "#getSiteList.TMS_FTPADDRESS#";
username = "#getSiteList.TMS_USERNAME#";
password = "#getSiteList.TMS_PASSWORD#";
/* sendingFolder = Folder whose content is to be uploaded recursively
* to the FTP server.
*/
sendingFolder = "#local_Folder#";
/* Forward slash / = root dir of FTP server.
* if you wish to FTP to privateDir under the root, for example,
* then set destFolder to "/privateDir"
*/
destFolder = "/#parent_Folder#";
FTP = createObject("java", "com.zehon.ftp.FTP");
thisBatchTransferProgressDefault= createObject("java", "com.zehon.BatchTransferProgressDefault").init();
FileTransferStatus = createObject("java", "com.zehon.FileTransferStatus");
try {
status = FTP.sendFolder(sendingFolder, destFolder, thisBatchTransferProgressDefault, host, username, password);
if(FileTransferStatus.SUCCESS is status){
writeOutput(sendingFolder & " got ftp-ed successfully to folder " & destFolder);
}
else if(FileTransferStatus.FAILURE is status){
writeOutput("Failed to ftp to folder " & destFolder);
}
} catch (any e) {
writeOutput(e.message);
}
</cfscript>
I tried this on two different servers and the same issue. If I use FileZilla or CFFTP, I can transfer all my files (CFFTP is having issues creating subfolders, which is why I moved away from that, and we want our customers to use their web app to FTP files, not a client). Has anyone else experience this? If so, was a solution discovered? Thanks
Setup: I have set up embedded jetty (v9.1) to serve static files with the setDirectoriesListed(true) and the code I am using is below:
// Create a basic Jetty server object that will listen on port 8080. Note that if you set this to port 0
// then a randomly available port will be assigned that you can either look in the logs for the port,
// or programmatically obtain it for use in test cases.
Server server = new Server(9090);
// Create the ResourceHandler. It is the object that will actually handle the request for a given file. It is
// a Jetty Handler object so it is suitable for chaining with other handlers as you will see in other examples.
ResourceHandler resource_handler = new ResourceHandler();
// Configure the ResourceHandler. Setting the resource base indicates where the files should be served out of.
// In this example it is the current directory but it can be configured to anything that the jvm has access to.
resource_handler.setDirectoriesListed(true);
resource_handler.setWelcomeFiles(new String[]{ "index.html" });
resource_handler.setResourceBase(".");
// Add the ResourceHandler to the server.
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
server.setHandler(handlers);
// Start things up! By using the server.join() the server thread will join with the current thread.
// See "http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join()" for more details.
server.start();
server.join();
This code is originally from here.
When I navigate to the address http://localhost:9090/, I see the files listed in the directory and I am able to click and open individual text files.
Problem: For some inexplicable reason, only when I click on a file of 0 bytes (aka it's an empty file, but still shown in the browser), the connection tries to load but eventually times out (30 seconds) and I get a response in safari saying the "server unexpectedly dropped the connection." In addition, when I make a HttpURLConnection to the 0 byte file, I get a content length returned of -1; This of course is only for empty files.
Expected Behavior as seen in standalone Jetty: When I use standalone jetty and serve the same files, I am able to "open" the empty file which just returns a blank page in a web browser. When using the HttpURLConnection, I get a content length of 0.
While this seems like a "pointless" task, one server is programmatically syncing with the embedded jetty server (so I want those empty files to sync). I imagine it has something to do with the resource handler seeing 0 bytes as it serves the static content, but I'm not too sure how to get the same behavior of the standalone jetty server as right now, it errors when trying to pull the empty files.
Thanks!
Your code works, as-is, at least on Jetty 9.2.7.v20140116
Full example I used:
package jetty;
import java.io.File;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
public class SimpleResources
{
public static void main(String[] args)
{
Server server = new Server(9090);
String resourceBase = System.getProperty("resourceBase", ".");
System.err.printf("Resource Base is: %s%n", new File(resourceBase).getAbsolutePath());
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setDirectoriesListed(true);
resource_handler.setWelcomeFiles(new String[] { "index.html" });
resource_handler.setResourceBase(resourceBase);
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] { resource_handler, new DefaultHandler() });
server.setHandler(handlers);
try
{
server.start();
server.join();
}
catch (Throwable t)
{
t.printStackTrace(System.err);
}
}
}
I ran it pointing the -DresourceBase system property to a directory that has the following ...
$ ls -la
total 8
drwxrwxr-x. 2 joakim joakim 4096 Jan 20 11:53 .
drwxrwxr-x. 3 joakim joakim 4096 Jan 20 11:53 ..
-rw-rw-r--. 1 joakim joakim 0 Jan 20 11:53 foo.txt
And once running the console shows ...
2015-01-20 11:55:07.788:INFO::main: Logging initialized #68ms
Resource Base is: /home/joakim/code/Jetty/empties
2015-01-20 11:55:07.837:INFO:oejs.Server:main: jetty-9.2.7.v20150116
2015-01-20 11:55:07.860:INFO:oejs.ServerConnector:main: Started ServerConnector#5461eda{HTTP/1.1}{0.0.0.0:9090}
2015-01-20 11:55:07.861:INFO:oejs.Server:main: Started #144ms
With a test request like such ...
$ curl --dump-header - http://localhost:9090/foo.txt
HTTP/1.1 200 OK
Date: Tue, 20 Jan 2015 18:55:39 GMT
Content-Type: text/plain
Content-Length: 0
Server: Jetty(9.2.7.v20150116)
Update:
Works as-is with no modifications on the following versions of jetty as well (didn't do an exhaustive test of versions, just a few older ones as well)
9.2.6.v20141205 - Identical Results
9.2.4.v20141103 - Identical Results
9.2.1.v20140609 - Identical Results
9.1.5.v20140505 - No Date in response headers, rest is the same (yes, it also sends Content-Length: 0)
I'm using the following project for enabling APNS in my project:
https://github.com/stephenmuss/django-ios-notifications
I'm able to send and receive push notifications on my production app fine, but the sandbox apns is having strange issues which i'm not able to solve. It's constantly not connecting to the push service. When I do manually the _connect() on the APNService or FeedbackService classes, I get the following error:
File "/Users/MyUser/git/prod/django/ios_notifications/models.py", line 56, in _connect
self.connection.do_handshake()
Error: [('SSL routines', 'SSL3_READ_BYTES', 'sslv3 alert handshake failure')]
I tried recreating the APN certificate a number of times and constantly get the same error. Is there anything else i'm missing?
I'm using the endpoints gateway.push.apple.com and gateway.sandbox.push.apple.com for connecting to the service. Is there anything else I should look into for this? I have read the following:
Apns php error "Failed to connect to APNS: 110 Connection timed out."
Converting PKCS#12 certificate into PEM using OpenSSL
Error Using PHP for iPhone APNS
Turns out Apple changed ssl context from SSL3 to TLSv1 in development. They will do this in Production eventually (not sure when). The following link shows my pull request which was accepted into the above project:
https://github.com/stephenmuss/django-ios-notifications/commit/879d589c032b935ab2921b099fd3286440bc174e
Basically, use OpenSSL.SSL.TLSv1_METHOD if you're using python or something similar in other languages.
Although OpenSSL.SSL.SSLv3_METHOD works in production, it may not work in the near future. OpenSSL.SSL.TLSv1_METHOD works in production and development.
UPDATE
Apple will remove SSL 3.0 support in production on October 29th, 2014 due to the poodle flaw.
https://developer.apple.com/news/?id=10222014a
I have worked on APN using python-django, for this you need three things URL, PORT and Certificate provided by Apple for authentication.
views.py
import socket, ssl, json, struct
theCertfile = '/tmp/abc.cert' ## absolute path where certificate file is placed.
ios_url = 'gateway.push.apple.com'
ios_port = 2195
deviceToken = '3234t54tgwg34g' ## ios device token to which you want to send notification
def ios_push(msg, theCertfile, ios_url, ios_port, deviceToken):
thePayLoad = {
'aps': {
'alert':msg,
'sound':'default',
'badge':0,
},
}
theHost = ( ios_url, ios_port )
data = json.dumps( thePayLoad )
deviceToken = deviceToken.replace(' ','')
byteToken = deviceToken.decode('hex') # Python 2
theFormat = '!BH32sH%ds' % len(data)
theNotification = struct.pack( theFormat, 0, 32, byteToken, len(data), data )
# Create our connection using the certfile saved locally
ssl_sock = ssl.wrap_socket( socket.socket( socket.AF_INET, socket.SOCK_STREAM ), certfile = theCertfile )
ssl_sock.connect( theHost )
# Write out our data
ssl_sock.write( theNotification )
# Close the connection -- apple would prefer that we keep
# a connection open and push data as needed.
ssl_sock.close()
Hopefully this would work for you.