Subversion Repositories php-qbpwcf

Rev

Rev 66 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

#!/usr/bin/php
<?php

/*
        QBPWCF, Quick Build PHP website Component base on Fedora Linux.
    Copyright (C) 2015~2024 Min-Jhin,Chen

    This file is part of QBPWCF.

    QBPWCF is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    QBPWCF is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with QBPWCF.  If not, see <http://www.gnu.org/licenses/>.
    
*/

/*
說明:
啟動 web socket server.
預設 addr 為 127.0.0.1.
預設 port 為 8080.

範例:
webSocketServer.php [--addr 127.0.0.1] [--port 8080]
*/

#使用命名空間qbpwcf
namespace qbpwcf;

#取得 lib path
exec("php -f ".escapeshellarg(pathinfo(__FILE__)["dirname"]."/libexec/folderOfUsrLib.php"),$output,$status);

#如果執行失敗
if($status!==0){

        #debug
        var_dump(__LINE__,$output);

        #結束執行,回傳shell 1.
        exit(1);

        }#if end

#儲存lib path
$folderOfUsrLib=$output[0];

#以該檔案的實際位置的 lib path 為 include path 首位
$output=array();
exec("cd ".escapeshellarg(pathinfo(__FILE__)["dirname"]."/../".$folderOfUsrLib."/qbpwcf").";pwd;",$output,$status);

#如果執行失敗
if($status!==0){

        #debug
        var_dump(__LINE__,$output);

        #結束執行,回傳shell 1.
        exit(1);

        }#if end

#設置 include path 
set_include_path($output[0].PATH_SEPARATOR.get_include_path());

#匯入外部套件
include("allInOne.php");

#說明函式
function help()
{
        #印出指令說明
        echo "Usage of ".basename(__FILE__).":".PHP_EOL; 
        echo "--addr 代表 Server 要 Listen 的 address".PHP_EOL;
        echo "--port 代表 Server 要 Listen 的 port".PHP_EOL;
        
        #結束執行
        exit;
}

#函式說明:
#解析參數.
#回傳結果:
#$result["status"],執行是否正常,"true"代表正常,"false"代表不正常.
#$reuslt["error"],執行不正常結束的錯訊息陣列.
#$result["function"],當前執行的函式名稱.
#$result["content"],解析好的參數陣列.
#$result["content"][$key][$i],參數 $key 的 $i+1 個參數數值內容.
#$result["program"],字串,執行的程式名稱.
#必填參數:
#無
#可省略參數:
#$conf["helpFunc"],如果解析的參數不成對,則要執行的函式名稱.
$conf["helpFunc"]="help";
#備註:
#僅能在命令列底下執行.
#建議:
#以後可將參數 --a--b 的名稱與後面的數值 $value 存成 $result["a"]["b"][$i]=$value .
$parseArgu=cmd::parseArgu($conf);
unset($conf);

#如果解析參數失敗
if($parseArgu["status"]==="false")
{
        #印出結果
        var_dump($parseArgu);
        
        #結束執行
        exit;
        
}#if end

#檢查參數
#函式說明:
#檢查必填與可省略參數,可省略參數可指定預設要給與什麼數值內容。
#$result["status"],執行是否正常,"true"代表正常,"false"代表不正常.
#$reuslt["error"],執行不正常結束的錯訊息陣列.
#$result["function"],當前執行的函式名稱.
#$result["passed"],識別要檢查的全體變數是否存在以及型態是否正確的變數,"true"代表檢查全部通過;"false"代表檢查不通過
#$result[$shouldBeCheckedVarName]["varExist"],所檢查的變數是否存在,"false"代表不存在;"true"代表存在
#$result[$shouldBeCheckedVarName]["varType"],所檢查的變數型態是否正確,"false"代表錯誤;"true"代表正確
#$result[$shouldBeCheckedVarName]["error"],每個參數設定的錯誤訊息
#$result["shouldNotBeEmpty"],不應該為空字串或控陣列的變數.
#$result["argu"],字串陣列,目前輸入的參數名稱陣列.
#$result["legalVarName"],字串陣列,合法可用的參數名稱陣列.
#$result["notNeedVar"],字串陣列,多餘的參數名稱.
#必填寫的參數:
#$conf["varInput"],陣列變數,要檢查的陣列變數,請在要檢查的參數前面加上&,這樣變動的結果才能被套用。
$conf["varInput"]=&$parseArgu["content"];
#$conf["referenceVarKey"],字串,$conf參數後面的key值,用於移除不要的參考陣列.
$conf["referenceVarKey"]="variableCheck::checkArguments";
#可以省略的參數:
#$conf["mustBeFilledVariableName"],爲必填參數的變數名稱陣列,形態爲陣列變數,元素數量需要跟"mustBeFilledVariableType"參數的元素數量一致,例如: $conf["mustBeFilledVariableName"] = array("id","account","password");
#$conf["mustBeFilledVariableName"]=array("config","acctVarName","passVarName","dbVarName","dbAddrVarName","dbPortVarName","backupAddr");
#$conf["mustBeFilledVariableType"],爲必填參數的變數陣列應該爲何種變數形態,形態爲陣列,元素數量需要跟"mustBeFilledVariableName"參數的元素數量一致,例如: $conf["mustBeFilledVariableType"] = array("string",integer,"double","resource","object"); , null代表不指定變數形態.
#$conf["mustBeFilledVariableType"]=array("array","array","array","array","array","array","array");
#$conf["canBeEmptyString"],字串,必填變數內容如果是空字串就不能算是有設置的話,請設為"false",預設爲"true",可以為空字串.
#$conf["canBeEmptyString"]="false";
#$conf["canNotBeEmpty"],字串陣列,哪些必填參數的內容不得為空字串或空陣列,僅當$conf["canBeEmptyString"]為"true"時會生效.
#$conf["canNotBeEmpty"]=array();
#$conf["canBeEmpty"],字串陣列,哪些必填參數的內容可為空字串或空陣列,僅當$conf["canBeEmptyString"]為"false"時會生效.
#$conf["canBeEmpty"]=array();
#$conf["skipableVariableCanNotBeEmpty"],字串陣列,哪些可省略參數不可以為空字串或空陣列.
#$conf["skipableVariableCanNotBeEmpty"]=array("backTime");
#$conf["skipableVariableName"],陣列字串,爲可省略參數的變數名稱陣列,形態爲陣列變數,例如: $conf["skipableVariableName"] = array("id","account","password");
$conf["skipableVariableName"]=array("addr","port");
#$conf["skipableVariableType"],陣列字串,爲可省略參數的變數名稱陣列,形態爲陣列變數,例如: $conf["skipableVariableType"] = array("string",integer,"double");
$conf["skipableVariableType"]=array("array","array");
#$conf["skipableVarDefaultValue"],字串陣列,每個不存在的可省略變數要初始化為什麼,null與代表不指定,若預設值是參數之一,請將$conf["mustBeFilledVar"]改成"\$conf["\mustBeFilledVar\"]".
$conf["skipableVarDefaultValue"]=array(array("127.0.0.1"),array("8080"));
#$conf["disallowAllSkipableVarIsEmpty"],字串,是否允許每個可省略參數都為空字串,預設為"true"允許,反之為"false".
#$conf["variableCheck::checkArguments"]["disallowAllSkipableVarIsEmpty"]="false";
#$conf["disallowAllSkipableVarIsEmptyArray"],字串,是否允許每個可省略參數都為空陣列,預設為"true"允許,反之為"false".
#$conf["disallowAllSkipableVarIsEmptyArray"]="";
#$conf["arrayCountEqualCheck"],字串陣列,為檢查哪些陣列參數的元素數量要一樣,$conf["arrayCountEqualCheck"][$i]=array()為第$i組key為哪些的變數其元素數量要相等.
#$conf["arrayCountEqualCheck"][]=array();
#參考資料來源:
#array_keys=>http://php.net/manual/en/function.array-keys.php
$checkArguments=variableCheck::checkArguments($conf);
unset($conf);

#若執行失敗
if($checkArguments["status"]==="false"){

        #印出結果
        var_dump($checkArguments);
        
        #結束執行
        exit;

        }#if end

#若檢查不通過
if($checkArguments["passed"]==="false"){

        #印出結果
        var_dump($checkArguments);
        
        #結束執行
        exit;

        }#if end

#取得各項參數
$addr=$parseArgu["content"]["addr"][0];
$port=$parseArgu["content"]["port"][0];

#函式說明:
#建立php原生的socket tcp/ip server,進而實作webSocket
#回傳結果:
#$result["status"],執行正常與否,"true"代表正常,"false"代表不正常.
#$result["error"],錯誤訊息陣列.
#$resutl["function"],當前執行的涵式名稱.
#$result["argu"],所使用的參數.
#必填參數:
#$conf["fileArgu"],字串,變數__FILE__的內容.
$conf["fileArgu"]=__FILE__;
#可省略參數:
#$conf["listenIp"],字串,要接聽的主機ip,預設為本機的ip.
$conf["listenIp"]=$addr;
#$conf["listenPort"],字串,要接聽的port,預設為已使用port+1.
$conf["listenPort"]=$port;
#$conf["wsMode"],字串,是否要用webSocket模式,預設為"false",不使用,若為"true"則要使用.
$conf["wsMode"]="true";
#$conf["processFuncs"],陣列,針對收到的訊息要呼叫的函式,會帶入一個參數陣列,array("data"=>收到的資料,"serverSock"=>serverSock,"clientSock"=>clientSock,"clientInfo"=>用戶端的資訊,"clientIndex"=>用戶端的索引,"allConn"=>所有連線的用戶端的連線資訊),回傳的結果若為陣列$result,其$result["status"]為"false"時,會結束執行(等待下個訊息).
$conf["processFuncs"]=array("\qbpwcf\pwd");
#參考資料:
#http://php.net/manual/en/sockets.examples.php
#http://us3.php.net/manual/en/function.socket-select.php
#response should at least end with "\r"=>http://stackoverflow.com/questions/25739768/websocket-communication-between-chromeclient-and-hotspotserver-status-line
#response status code should be 101=>http://stackoverflow.com/questions/29829597/i-get-a-status-200-when-connecting-to-the-websocket-but-it-is-an-error
#webSocket實做=>http://srchea.com/build-a-real-time-application-using-html5-websockets
#webSocketServer實做=>http://www.cuelogic.com/blog/php-and-html5-websocket-server-and-client-communication/
#備註:
#僅能在命令列執行.
$nativeSocketTcpIpServer=webSock::nativeSocketTcpIpServer($conf);
unset($conf);

#如果 啟動失敗
if($nativeSocketTcpIpServer["status"]==="false"){

        #印出結果
        var_dump($nativeSocketTcpIpServer);
        
        #結束執行
        exit;

        }#if end

/*
函式說明:
提供取得當前路徑的功能
*/
function pwd(&$params){

        #取得收到的訊息
        $receivedData=$params["data"];
        
        #取得 server 的 socket
        $serverSocket=$params["serverSock"];
        
        #取得 client 的 socket
        $clientSocket=$params["clientSock"];
        
        #取得 client 的資訊
        $clientInfo=$params["clientInfo"];
        
        #取得 client 的索引
        $clientIndex=$params["clientIndex"];
        
        #取得 all clients 的資訊
        $allConn=$params["allConn"];
        
        #函式說明:
        #呼叫shell執行系統命令,並取得回傳的內容.
        #回傳結果:
        #$result["status"],執行是否正常,"true"代表正常,"false"代表不正常.
        #$result["error"],錯誤訊息陣列.
        #$result["function"],當前執行的函數名稱.
        #$result["argu"],使用的參數.
        #$result["cmd"],執行的指令內容.
        #$result["fullCmd"],如果參數 $conf["inBackGround"] 為 "true" 則會回傳該值.
        #$result["output"],爲執行完二元碼後的輸出陣列,若 $conf["inBackGround"] 為 "true",則為當下的輸出.
        #$result["tmpFileOutput"],儲存輸出的暫存檔案名稱,若 $conf["inBackGround"] 為 "true" 則會回傳該值.
        #$result["running"],是否還在執行.
        #$result["pid"],pid.
        #$result["statusCode"],執行結束後的代碼.
        #$result["escape"],陣列,儲存重新排序過且已經escape過的指令(key為"cmd")與參數(key為"argu").
        #必填參數:
        #$conf["command"],字串,要執行的指令.
        $conf["command"]="pwd";
        #$conf["fileArgu"],字串,變數__FILE__的內容.
        $conf["fileArgu"]=__FILE__;
        #可省略參數:
        #$conf["argu"],陣列字串,指令搭配的參數,預設為空陣列.
        #$conf["argu"]=array("");
        #$conf["arguIsAddr"],陣列字串,指令搭配的哪些參數為路徑,為路徑的參數會進行轉換以便符合呼叫當前函數的位置,預設不指定,若有3個參數,其中第3個參數為路徑,則表示為array("false","false","true").
        #$conf["arguIsAddr"]=array();
        #$conf["pre"],陣列,要在本指令前執行的每個指令與參數.
        #$conf["pre"][$i]["cmd"],字串,要在本指令前執行的第$i+1個指令.
        #$conf["pre"][$i]["param"],陣列字串,要在本指令前執行的第$i+1個指令的參數.
        #$conf["enablePrintDescription"],字串,是否要印出$conf["printDescription"]的內容,"true"代表要,"false"代表不要,預設為"false".
        #$conf["enablePrintDescription"]="true";
        #$conf["printDescription"],字串,執行該外部程式前要印出來的的文字,預設為$conf["command"]的內容加上使用的$conf["argu"]參數.
        #$conf["printDescription"]="";
        #$conf["escapeshellarg"],字串,是否要啟用過濾參數,用了比較安全,但可能會出錯,"true"為啟用,"false"為不啟用,預設為"false".如果參數為"< 、<< 、> 、>> 、| 、2>&1"之一則不會過濾.
        #$conf["escapeshellarg"]="false";
        #$conf["thereIsShellVar"],陣列字串,指令搭配的參數"argu",若含有「\'」,則取代為「"」.每個argu參數都要有對應的元素."true"代表要置換.
        #$conf["thereIsShellVar"]=array();
        #$conf["username"],字串,要用什麼使用者來執行,預設為執行php的使用者,該參數不適用於apache環境.
        #$conf["username"]="";
        #$conf["password"],字串,root的使用者密碼,預設不使用密碼,該參數不適用於apache環境.
        #$conf["password"]="";
        #$conf["useScript"],字串,是否要啟用Linux的script指令來記錄輸出,"true"代表要,Fedora的selinux會擋住該操作;"false"代表不要,預設為"false".
        #$conf["useScript"]="";
        #$conf["logFilePath"],字串,當 $conf["useScript"] 為 "true" 時,輸出的內容要暫存到哪裡,預設為 "/tmp/.qbpwcf_tmp/external/callShell/".
        #$conf["logFilePath"]=".qbpwcf_tmp/external/callShell/";
        #$conf["inBackGround"],字串,是否要在背景執行,且不會等待程式執行結束再執行下一個指令,"true"代表是,"false"代表不要,預設為"false",如果$conf["command"]有用「;」區隔的多個指令將會出錯.
        #$conf["inBackGround"]="";
        #$conf["getErr"],字串,"true"代表將錯誤輸出變成標準輸出,反之"false"為不變動.
        #$conf["getErr"]="false";
        #$conf["doNotRun"],字串,"true"代表不執行指令,預設為"false"會執行指令.
        #$conf["doNotRun"]="false";
        #參考資料:
        #exec=>http://php.net/manual/en/function.exec.php
        #escapeshellcmd=>http://php.net/manual/en/function.escapeshellcmd.php
        #escapeshellarg=>http://php.net/manual/en/function.escapeshellarg.php
        #備註:
        #不是所有指令都能用apache的身份執行,目前已知java,javac指令無法執行,使用root身份可能會被selinux阻擋.
        #若使用的 command、argu 參數,含有 ~ 則會被視為字串,若有需要其於 shell 中代表的家目錄位置,可用 fileAccess::tildeToPath 來進行轉換.   
        $callShell=external::callShell($conf);
        unset($conf);
        
        #如果執行失敗
        if($callShell["status"]==="false"){
        
                #印出結果
                return $callShell;
                
                }#if end
        
        #取得經過編碼的執行後結果字串
        $callShellResultStr=json_encode($callShell);
        
        #debug
        #var_dump(__LINE__,$callShellResultStr);
        
        #函式說明:
        #加密 handshake 後要傳送的訊息 
        #回傳結果:
        #$result["status"],執行是否正常,"true"代表正常,"false"代表不正常.
        #$result["error"],執行不正常結束的錯訊息陣列.
        #$result["content"],陣列,加密 handshake 後要傳送給 client 的訊息,若有多個代表要分為多個 Fragmentation 來依序傳送.
        #$result["argu"],陣列,使用的參數.
        #必填參數:
        #$conf["text"],字串,要加密的訊息.
        $conf["webSock::encode"]["text"]=$callShellResultStr;
        #可省略參數:
        #$conf["ping"],字串,"true"代表為ping訊息;反之為"false",預設為"false".
        #$conf["ping"]="true";
        #參考資料:
        #https://www.rfc-editor.org/rfc/rfc6455#page-28, Web Socket Base Framing Protocol.
        #備註:
        #目前$conf["text"]長度超過125會出錯.
        $talkback=webSock::encode($conf["webSock::encode"]);    
        unset($conf["webSock::encode"]);
                
        #如果產生 web socket 格式封包 失敗
        if($talkback["status"]==="false"){
        
                #印出結果
                return $talkback;
        
                }#if end
                
        #針對每個訊息的分段
        foreach($talkback["content"] as $msgIndex=>$msg){
                
                #提示第幾個訊息
                echo "第 ".($msgIndex+1)." 個訊息的內容:".PHP_EOL;
                
                #函式說明:
                #將字串中的每個字變成bytes陣列
                #回傳結果:
                #$result["content"],bytes陣列.
                #必填參數:
                #$conf["input"],字串,要轉換成bytes陣列的字串.
                $conf["stringProcess::str2bytesArray"]["input"]=$msg;
                #可省略參數:
                #無.
                #參考資料:
                #無.
                #備註:
                #無.
                $str2bytesArray=stringProcess::str2bytesArray($conf["stringProcess::str2bytesArray"]);
                unset($conf["stringProcess::str2bytesArray"]);
                
                #如果執行失敗
                if($str2bytesArray["status"]==="false"){
                
                        #印出結果
                        return $str2bytesArray;
                
                        }#if end
                
                #針對每個 bytes
                foreach($str2bytesArray["content"] as $byteIndex=>$bytes){
                
                        #函式說明:
                        #將bytes數字(16進位)轉換為bit字串(0跟1來表述)
                        #回傳結果:
                        #$result["content"],bit字串(0跟1來表述).
                        #必填參數:
                        #$conf["bytes"],字串,要轉換成bit的bytes數字.
                        $conf["stringProcess::bytes2bitString"]["bytes"]=$bytes;
                        #可省略參數:
                        #無.
                        #參考資料:
                        #無.
                        #備註:
                        #無.
                        $bytes2bitString=stringProcess::bytes2bitString($conf["stringProcess::bytes2bitString"]);
                        unset($conf["stringProcess::bytes2bitString"]);
                        
                        #如果執行失敗
                        if($bytes2bitString["status"]==="false"){
                        
                                #印出結果
                                return $bytes2bitString;
                
                        }#if end
                        
                        #印出 8bit
                        echo $bytes2bitString["content"];
                        
                        #如果為 32 bit 結束
                        if(($byteIndex+1)%4===0){
                        
                                #印出換行符號
                                echo PHP_EOL;
                        
                                }#if end
                
                        }#foreach end
                
                #回傳訊息
                $socket_write=socket_write($clientSocket, $msg, strlen($msg));

                #換行
                echo PHP_EOL;

                #debug
                #var_dump(__LINE__,$socket_write,socket_strerror(socket_last_error($clientSocket)));
                
                }#foreach end   
        
        #初始化結果
        $result=array();

        #設置執行正常
        $result["status"]="continue";
        
        #回傳結果
        return $result;

        }#function pwd end