PROGRAMOWANIE W ŚRODWISKU SIECIOWYM I


 

ĆWICZENIE VI

 

 

/*
Basic client FTP support
*/

import java.net.*;
import java.io.*;
import java.util.*;
import javax.net.*;
import javax.net.ssl.*;
import java.security.*;
import com.sun.net.ssl.*;

public class SSLCadreFtp{
// socket factories
SSLSocketFactory socketFactory = null;
SSLServerSocketFactory serverSocketFactory = null;

// FTP dual sockets
//java.net.Socket controlSocket = null;
//java.net.ServerSocket dataSocket = null;
SSLSocket controlSocket = null;
SSLServerSocket dataSocket = null;

// Used to communcate over control socket
java.io.BufferedReader controlIn = null;
java.io.PrintWriter controlOut = null;

// Used for receiving files from server
java.io.RandomAccessFile fin = null;
java.io.DataInputStream dis = null;
//java.net.Socket dataOut = null;
SSLSocket dataOut = null;

// Used for sending files to server
java.io.InputStream is = null;
java.io.DataOutputStream dos = null;
//java.net.Socket dataIn = null;
SSLSocket dataIn = null;

String hostName = null;
String userName = null;
String passWord = null;
String transferMode = null;
String transferFile = null;
String serverDirectory = null;
String clientDirectory = null;

public SSLCadreFtp( String hN,
String uN,
String pW){
hostName=hN;userName=uN;passWord=pW;
this.connect();
}

private void connect(){
try{
// Dynamic registration of SunJSSE provider
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
System.out.println("connect-1");

// Create a socket factories
socketFactory=(SSLSocketFactory) SSLSocketFactory.getDefault();
serverSocketFactory=(SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
System.out.println("connect-2");

//ftp has a dual-socket protocol
//controlSocket=socketFactory.createSocket(hostName,21);
controlSocket=(SSLSocket)socketFactory.createSocket(hostName,990);
controlSocket.setSoTimeout(1000);
System.out.println("connect-3");

//dataSocket= new java.net.ServerSocket(0);
dataSocket=(SSLServerSocket)serverSocketFactory.createServerSocket(0);
dataSocket.setSoTimeout(1000);
System.out.println("connect-4");

// the control channel (messages to ftp server)
controlOut= (new java.io.PrintWriter(
controlSocket.getOutputStream(),true)
);
System.out.println("connect-5");

// the control channel (messages from ftp server)
controlIn= (new java.io.BufferedReader(
new java.io.InputStreamReader(
controlSocket.getInputStream())
)
);
System.out.println("connect-6");

// Login to the server
controlOut.println("USER " +userName);
controlOut.flush();
System.out.println("connect-7");

controlOut.println("PASS " +passWord);
controlOut.flush();
System.out.println("connect-8");

//controlOut.println("SSL AUTH");
//controlOut.flush();
//System.out.println("connect-9");

//controlOut.println("PROT P");
//controlOut.flush();
//System.out.println("connect-10");
}
catch(java.net.UnknownHostException e){
e.printStackTrace();
System.exit(0);
}
catch (java.io.IOException e){
e.printStackTrace();
System.exit(0);
}
catch (Exception e){
e.printStackTrace();
System.exit(0);
}
}

public void setMode(String tM){
transferMode=tM;
System.out.println("setMode...");
}

public void setFile(String f){
transferFile=f;
System.out.println("setFile...");
}

public void setServerDir(String sD){
serverDirectory=sD;
System.out.println("setServerDir...");
}

public void setClientDir(String cD){
clientDirectory=cD;
System.out.println("setClientDir...");
}

private void setTransferMode(){
// Set type of transfer ASCII or BINARY
if((transferMode.equals("B"))||(transferMode.equals("b"))){
//controlOut.println("TYPE L 32"); //BINARY {to unix}
//controlOut.println("TYPE L 8"); //BINARY {to pc}
controlOut.println("TYPE I"); //BINARY
}
else{
//controlOut.println("TYPE A N"); //ASCII
controlOut.println("TYPE A"); //ASCII
}
controlOut.flush();
System.out.println("setTransferMode...");
}

private void setClientPort(){
// Determine which port to send/get data to/from
// must put port info into the ftp RFC 959 format
// PORT h1,h2,h3,h4,p1,p2
int clientPort = dataSocket.getLocalPort();
int p1 = ((clientPort & 0xff00) >> 8);
int p2 = (clientPort & 0x00ff);
String port_command="PORT " +
controlSocket.getLocalAddress().getHostAddress().replace('.',',')+ //h1,h2,h3,h4
"," + p1 + "," + p2; //p1,p2
controlOut.println(port_command);
controlOut.flush();
System.out.println("setClientPort...");
}

private void setServerDirectory(){
// go to proper directory on server side
if (serverDirectory != null){
controlOut.println("CWD " + serverDirectory);
controlOut.flush();
}
System.out.println("setServerDirectory...");
}

private void createClientSideFile(){
// create file structure (on client-side) of the file you will retrieve
// we will write to this file on the client local disk
try{
if(clientDirectory != null)
fin=new java.io.RandomAccessFile((clientDirectory+transferFile),"rw");
else
fin=new java.io.RandomAccessFile((transferFile),"rw");
}
catch(java.io.FileNotFoundException e){
e.printStackTrace();
System.exit(0);
}
catch(java.io.IOException e){
e.printStackTrace();
System.exit(0);
}
catch (Exception e){
e.printStackTrace();
System.exit(0);
}
System.out.println("createClientSideFile...");
}

private void setClientSideFile(){
// create file structure (on client-side) of the file you will retrieve
// we will write to this file on the client local disk
try{
// do put logic
if(clientDirectory != null)
is = new java.io.FileInputStream(clientDirectory+transferFile);
else
is = new java.io.FileInputStream(transferFile);
}
catch(java.io.FileNotFoundException e){
e.printStackTrace();
System.exit(0);
}
catch(java.io.IOException e){
e.printStackTrace();
System.exit(0);
}
catch (Exception e){
e.printStackTrace();
System.exit(0);
}
System.out.println("setClientSideFile...");
}

public String getFile(){
try {
this.setTransferMode();
this.setClientPort();
this.setServerDirectory();
this.createClientSideFile();

// request (from server) to retrive a file
controlOut.println("RETR " +transferFile);
controlOut.flush();
System.out.println("RETR...");

// retrive the file from the data socket
dataIn=(SSLSocket)dataSocket.accept();
dis =new java.io.DataInputStream(dataIn.getInputStream());

// read info from dataSocket & write out to local disk
int offset;
byte[] data = new byte[1024];
while((offset=dis.read(data))!=-1){
fin.write(data, 0, offset);
}
System.out.println("RETR the file complete...");
fin.close();
dis.close();
dataIn.close();

//this.showControlReponses();
}
catch(java.net.UnknownHostException e){
e.printStackTrace();
return ("ftp failure");
}
catch (java.io.IOException e){
e.printStackTrace();
return ("ftp failure");
}
catch (Exception e){
e.printStackTrace();
return ("ftp failure");
}
return ("ftp success");
}

public String putFile(){
try {
this.setTransferMode();
this.setClientPort();
this.setServerDirectory();
this.setClientSideFile();

// request (from server) to retrive a file
controlOut.println("STOR " +transferFile);
controlOut.flush();
System.out.println("STOR...");

// store the file to the data socket
dataOut=(SSLSocket)dataSocket.accept();
dos = new java.io.DataOutputStream(dataOut.getOutputStream());

// write info from local disk & write out to dataSocket
int offset;
byte[] data = new byte[1024];
while((offset=is.read(data))!=-1){
dos.write(data, 0, offset);
}
System.out.println("STOR the file complete...");
is.close();
dos.close();
dataOut.close();

//this.showControlReponses();
}
catch(java.net.UnknownHostException e){
e.printStackTrace();
return ("ftp failure");
}
catch (java.io.IOException e){
e.printStackTrace();
return ("ftp failure");
}
catch (Exception e){
e.printStackTrace();
return ("ftp failure");
}
return ("ftp success");
}

public void bye(){
quitFtp();
System.out.println("bye...");
}

private void quitFtp(){
try {
// quit the ftp session
controlOut.println("QUIT");
controlOut.flush();

// Get a history of all processing
this.showControlReponses();

controlOut.close();
controlIn.close();
controlSocket.close();
dataSocket.close();
}
catch (java.io.IOException e){
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
System.out.println("quitFtp...");
}

private void showControlReponses(){
try {
// Display history of the ftp servers responses
// to our commands
System.out.println("--- ftp control responses ---");
String inputLine_client;
while ((inputLine_client=controlIn.readLine())!=null)
System.out.println(inputLine_client);
}
catch (java.io.IOException e){
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
System.out.println("showControlReponses...");
}

public static void main(String arg[]){
SSLCadreFtp cftp=null;

/*// Example FTP get
cftp= new SSLCadreFtp("aptest","test","test");
cftp.setMode("a");
cftp.setFile("DateUtil.java");
//cftp.setServerDir("/db/java/henry");
cftp.setClientDir("C:\\Henry\\ftptest\\");
System.out.println("\nStatus: "+cftp.getFile());
cftp.bye();

// Example FTP put
cftp= new SSLCadreFtp("aptest","test","test");
cftp.setMode("a");
cftp.setFile("PutFtp.java");
//cftp.setServerDir("/db/java/henry");
cftp.setClientDir("C:\\Henry\\ftptest\\");
System.out.println("\nStatus: "+cftp.putFile());
cftp.bye();
*/

// Example FTP get
cftp= new SSLCadreFtp("aptest","test","test");
cftp.setMode("b");
cftp.setFile("RegistryElement.java");
cftp.setServerDir("/db/java/henry");
cftp.setClientDir("C:\\Henry\\ftptest\\");
System.out.println("\nStatus: "+cftp.getFile());
cftp.bye();

/*
Example FTP put
cftp = new SSLCadreFtp("aptest","test","test");
cftp.setMode("a");
cftp.setFile("PutFtp.java");
cftp.setServerDir("/db/java/henry");
cftp.setClientDir("C:\\Henry\\ftptest\\");
System.out.println("\nStatus: "+cftp.putFile());
cftp.bye();
*/
}
}

 

 

 

WYWOŁANIE SKRYPTU PHP Z POZIOMU PROGRAMU JAVA

 

import java.io.*;
import java.util.*;
 
class Streamer extends Thread {
        
        InputStream IS;
        String Type;
        
        Streamer(InputStream _IS, String _Type) {
               
               IS = _IS;
               Type = _Type;
               
        }
        
        public void run() {
               
               
               try{
                       
                       InputStreamReader ISR = new InputStreamReader(IS);
                       BufferedReader BR = new BufferedReader(ISR);
                       String line = null;
                       while((line = BR.readLine())!= null)
                       System.out.println(Type + ">" + line);
                       
               }
               catch(IOException ex){ex.printStackTrace();}
               
        }
        
}
 
public class test {
   public static void main(String[] args) {
      Runtime run = Runtime.getRuntime();
      try {
 
                String[] commands = {"d:\\php.5.2.6\\php-win.exe", "-f", "example.php"};      
         Process pp=run.exec(commands);
         BufferedReader in =new BufferedReader(new InputStreamReader(pp.getErrorStream()));
 
         Streamer St = new Streamer(pp.getInputStream(),"OUTPUT");
         
         St.start();
         
         int exitVal = pp.waitFor();
         System.out.println("Process exitValue: " + exitVal);
      } catch (Exception e) {
         e.printStackTrace();
         System.out.println(e.getMessage());
      }
   }
} }

 

 

 

PRZYKŁADOWY KOD PHP

 

<?php

$hello = "Hello World!";

$a_number = 4;

$anotherNumber = 8;

$myString = "Hello!";

echo $myString;

echo "<h5>I like using PHP!</h5>";

?>

 

 

ZADANIE

1)     Implementacja funkcji INSERT, DELETE, UPDATE na tabeli USERS na serwerze służących do obsługi kont użytkowników systemu klient-serwer. Optymalnie z wykorzystaniem odpowiedniego GUI, aplikacji graficznej.

2)     Implementacja wszystkich połączeń klient serwer z wykorzystaniem protokołu SSL według wzoru podanego w pierwszym kodzie na stronie.

3)     Pobranie katalogu z biblioteką PHP

4)     Wywołanie dowolnego skryptu PHP według wzoru podanego w kodzie drugim na stronie.

 

 

Kod wykorzystania protokołu SSL pod adresem: http://forums.sun.com/thread.jspa?threadID=149461

 

 

Tutorial odnośnie wywołania programu zewnętrznego z poziomu programu w Javie pod adresem: http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=1

 

Tutorial nt połączeń SSL:

 

JAVA + SSL Tutorial (serwer i klient)

CERTYFIKAT

Najpierw należy utworzyć certyfikat, wykorzystując narzędzie keytool, część J2SE SDK (program pobiera informacje o właścicielu certyfikatu oraz haśle, wprowadzić 123456  jako hasło):

keytool -genkey -keystore mySrvKeystore -keyalg RSA

Po wykonaniu polecenia, ceretyfikat znajduje się w katalogu roboczym polecenia keytool.

KOD SERWERA (EchoServer.java)

import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
 
public
class EchoServer {
    public
            static
    void
            main(String[] arstring) {
        try {
            SSLServerSocketFactory sslserversocketfactory =
                    (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
            SSLServerSocket sslserversocket =
                    (SSLServerSocket) sslserversocketfactory.createServerSocket(9999);
            SSLSocket sslsocket = (SSLSocket) sslserversocket.accept();
 
            InputStream inputstream = sslsocket.getInputStream();
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
 
            String string = null;
            while ((string = bufferedreader.readLine()) != null) {
                System.out.println(string);
                System.out.flush();
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}
      

 

 

KOMPILACJA:

 

javac EchoServer.java

 

KOD KLIENTA (EchoClient.java)

 

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.*;
 
public
class EchoClient {
    public
            static
    void
            main(String[] arstring) {
        try {
            SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket("localhost", 9999);
 
            InputStream inputstream = System.in;
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
 
            OutputStream outputstream = sslsocket.getOutputStream();
            OutputStreamWriter outputstreamwriter = new OutputStreamWriter(outputstream);
            BufferedWriter bufferedwriter = new BufferedWriter(outputstreamwriter);
 
            String string = null;
            while ((string = bufferedreader.readLine()) != null) {
                bufferedwriter.write(string + '\n');
                bufferedwriter.flush();
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}
      

 

KOMPILACJA:

 

javac EchoClient.java

 

URUCHOMIENIE

 

Skopiować certyfikat do katalogu roboczego, uruchomić serwer z parametrami, (należy zmienić nazwę keyStore  i /lub trustStrorePassword jeżli podane zostały inne podczas tworzenia certyfikatu:

 

java -Djavax.net.ssl.keyStore=mySrvKeystore -Djavax.net.ssl.keyStorePassword=123456 EchoServer

 

 

W podobny sposób skopiowac certyfikat do karalogu roboczego klienta i wywołać:

 

java -Djavax.net.ssl.trustStore=mySrvKeystore -Djavax.net.ssl.trustStorePassword=123456 EchoClient

 

W celu uzuskania informacji debugowania, należy dodatkowo dołączyć następującą opcję:

 

-Djava.protocol.handler.pkgs=com.sun.net.ssl.internal.www.protocol -Djavax.net.debug=ssl

 

 

Opracowano na podstawie materiału Tomas Vilda