I am trying to implement a FTP file upload in android, using Apache commons library. The communication must be done through explicit TLS authentication. I can login, connect to server and list files successfully, but when i am trying to store a file to the server, it creates a file in the destination folder of the server with size 0 and throwing SSLException: Write error, broken pipe.
How to overcome this?
Below is my code:
FTPSClient ftpClient = new FTPSClient("TLS", false);
ftpClient.addProtocolCommandListener(new PrintCommandListener(new
KeyManagerFactory kmf = getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(null, null);
KeyManager km = kmf.getKeyManagers()[0];
ftpClient.setKeyManager(km);
ftpClient.setBufferSize(1000);
ftpClient.setConnectTimeout(5000);
ftpClient.connect(InetAddress.getByName("server ip address"), 990);
// Set protection buffer size
ftpClient.execPBSZ(0);
// // Set data channel protection to private
ftpClient.execPROT("P");
ftpClient.login("username", "password");
ftpClient.changeWorkingDirectory("/");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
buffInp = new BufferedInputStream(new FileInputStream(file.getAbsolutePath()));
//throwing exception here
boolean status = ftpClient.storeFile( picture.getName(), buffInp );
Related
I'm basically new to mobile development and stuck for a few weeks because,
I am unable to connect XAMARIN Android app with MQTTT over TLS.
Maybe i am using the wrong library or is it an Xamarin error?
My certificate is a .crt file from m21.cloudmqtt.com.
https://crt.sh/?id=5253106089
First was using System.Net MQTT but they are currently unable to work over TLS.
So i currently i am using MQTTNet, with (for the moment) the default certificate from m21.cloud.com which i have stored in Assets folder.I tested this local with and without a certificate and its working fine.
The MQTTNet Client with cert from local folder is like this, and works like it should:
var caCert = new X509Certificate2("C:/pathtocert.crt");
var source = new CancellationTokenSource().Token;
var token = source;
var factory = new MqttFactory();
var mqttClient = factory.CreateMqttClient();
var mqttOptions = new MqttClientOptionsBuilder()
.WithTcpServer(server, port)
.WithClientId(clientId)
.WithCredentials(username, pswd)
.WithTls(new MqttClientOptionsBuilderTlsParameters
{
UseTls = true,
Certificates = new List<X509Certificate> { caCert }
})
.Build();
mqttClient.ConnectAsync(mqttOptions, token).Wait(token);
To get the Certifcate from Android Assets Folder i used the same client code as above and t et the certificate i used:
using (var assetStream = await Xamarin.Essentials.FileSystem.OpenAppPackageFileAsync("filename.crt"))
using (var memStream = new MemoryStream())
{
assetStream.CopyTo(memStream);
caCert = new X509Certificate(memStream.ToArray());
}
I dont understand why its not working, for now its also okay if the certificate isn't used but it needs to use TLS. But tried, and i still get unauthorized error.
var mqttOptions = new MqttClientOptionsBuilder()
.WithTcpServer(server, port)
.WithClientId(clientId)
.WithCredentials(username, pswd)
.WithTls(new MqttClientOptionsBuilderTlsParameters
{
UseTls = true,
})
.Build();
Thanks in adnvance.
I generated an access token to be able to make API calls for my own account without going through the authorization flow. I found this Dropbox files Get API but I don't know how to use it.
I tried this code, but it doesn't seem to work:
// Authentication with Token
AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys);
mDBApi = new DropboxAPI<AndroidAuthSession>(session);
mDBApi.getSession().setOAuth2AccessToken(ACCESS_TOKEN);
// Upload a file to Apps folder
File file = new File("working-draft.txt");
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
DropboxAPI.Entry response = mDBApi.putFile("/magnum-opus.txt", inputStream,
file.length(), null, null);
Log.i("DbExampleLog", "The uploaded file's rev is: " + response.rev);
} catch (Exception e) {
e.printStackTrace();
}
How can I upload and download directly to the Apps folder using the token key?
Also is there a way to print the list of all the files in my Apps folder?
The docs are pretty poor. I found the following examples on Github which helped me:
https://github.com/dropbox/dropbox-sdk-java/tree/master/examples/android/src/main/java/com/dropbox/core/examples/android
In gradle
compile 'com.dropbox.core:dropbox-core-sdk:3.0.2' or whatever is the latest
The key and secret are written into a JSON file + there's an entry you need to add into the manifest with the app key. Just follow the example which shows placeholders.
Once you've done the handshake and got the access token back
DbxRequestConfig requestConfig = DbxRequestConfig.newBuilder("your identifier")
.withHttpRequestor(new
OkHttp3Requestor(OkHttp3Requestor.defaultOkHttpClient()))
.build();
dbxClient = new DbxClientV2(requestConfig, accessToken);
dbxClient.files().[operation e.g. upload\download\file listing]
I am using Pjusa for Voip, I have done communication through UDP and TCP but could not communitcate through TLS setting`
TlsConfig tlsConfig = new TlsConfig();
File cacheDir = new File(ctx.getCacheDir(), "ca");
InputStream input = ctx.getResources().openRawResource(R.raw.ca);
tlsConfig.setCaListFile(cacheDir.getPath());
input = ctx.getResources().openRawResource(R.raw.secure);
cacheDir = new File(ctx.getCacheDir(), "secure");
tlsConfig.setCertFile(cacheDir.getPath());
tlsConfig.setMethod(pjsip_ssl_method.PJSIP_SSLV23_METHOD);`
I have attached CaListFile and setCertFile files like that method and that setting working but When I establish a call then I found error like that
tlsc0x9e7db014 TLS connect() error: Connection refused [code=120111]
tsx0x9d945864 Failed to send Request msg INVITE/cseq=25416 (tdta0x9d991000)! err=120111 (Connection refused)
In IOS I found some more setting for TLS , but could not implement in PJSUA
any one can help me out how to use that piece of code in android in PJSUA library
pj_sockaddr_in remote;
pjsip_transport *transport;
remote.sin_family = pj_AF_INET();
remote.sin_zero_len = 0;
remote.sin_addr.s_addr = pj_inet_addr(#"xxx.xx.xx.xx").s_addr;
remote.sin_addr.s_addr = INADDR_ANY;
bzero(&(remote.sin_zero),sizeof(remote.sin_zero));
app_config->cfg.use_srtp = PJMEDIA_SRTP_MANDATORY;
app_config->cfg.srtp_secure_signaling = 1;
thanks in advance
TlsConfig tlsConfig = new TlsConfig();
tlsConfig.setCertFile(certFile);
sipTpConfig.setTlsConfig(tlsConfig);
tlsConfig.setCaListFile(caListFile);
I did R&D from web searching and reading document of SIP and PJSIP, then I find the sluotion for accountConfig for PJMEDIA_SRTP_MANDATORY and setSrtpSecureSignaling(1) by that way provided below
accCfg.getMediaConfig().setSrtpUse(pjmedia_srtp_use.PJMEDIA_SRTP_MANDATORY);
accCfg.getMediaConfig().setSrtpSecureSignaling(1);
Hence TLS working with CAListFile and CertificateFile
i'm newbie on android,
I'm trying to upload file from sdcard to ftp server using android, the code seems to be correct. While debbuging it says that my connet and upload functions to the server can not access the classes given by org.appache.commons.net (no source found in those classes), knowing that i have this org.appache.commons.net jar in the libs foldre, the project build path and the user libraries.
Should i use another librarie or, is there any other work to do ?
The code
public boolean ftpConnect(String host, String username,String password, int port){
try {
mFTPClient = new FTPClient();
mFTPClient.connect(host, port);
mFTPClient.enterLocalPassiveMode();
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
Log.w("into the ftpUpload","!!");
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
Log.w("into the ftpUpload","!!");
return status;
}
} catch(Exception e) {
Log.d(TAG, "Error: could not connect to host " + host );
}
return false;}
call this methode in another class using
FtpClient FTP = new FtpClient();
FTP.ftpConnect("..*.", "", "*", 21);
I'm doing it juste like several posts propose it, concerning the lib i added the org.apache.commons.net jar to the lib file and to the java build path..
The exception is given exactly here: mFTPClient.connect(host, port); (btw there are no logs).. Does anybody have an idea what can be the problem with that? I tried lot of codes that works for others but it fail to connect to the ftp server every time. Thanks for your responses.
Running following code on emulator. Connecting to filezilla server on windows development host using ip address 10.0.2.2.
FTPClient ftp = new FTPClient();
try
{
ftp.connect("10.0.2.2", 21);
ftp.login(username, password);
String REMOTE_DEFAULT_INITIAL_DIRECTORY = ftp.currentDirectory();
File mDirectory = new File(REMOTE_DEFAULT_INITIAL_DIRECTORY);
File[] listing = mDirectory.listFiles();
}
catch (Exception e)
{
e.printStackTrace();
}
Problem: The File[] contains listing of files on android client instead of server.
Thanks
Imdad
I use the same library for my Android project and to get the listing I use the following:
FTPClient ftpClient = new FTPClient();
ftpClient.connect(serverName);
ftpClient.login(username, password);
ftpClient.setPassive(true);
ftpClient.setType(FTPClient.TYPE_BINARY);
final FTPFile[] remoteFiles = ftpClient.list();
Android Emulator dosen't support FTP connection...
Because, Emulator is fixed port to 5554 ~ 5555?
FTP prot is 21..
So, you just run on real device.