Subversion Repositories qbpwcf-lib(archive)

Rev

Rev 918 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
513 liveuser 1
#!/bin/php
2
<?php
3
 
4
/*
5
	QBPWCF, Quick Build PHP website Component base on Fedora Linux.
618 liveuser 6
    Copyright (C) 2015~2024 Min-Jhin,Chen
513 liveuser 7
 
8
    This file is part of QBPWCF.
9
 
10
    QBPWCF is free software: you can redistribute it and/or modify
11
    it under the terms of the GNU General Public License as published by
12
    the Free Software Foundation, either version 3 of the License, or
13
    (at your option) any later version.
14
 
15
    QBPWCF is distributed in the hope that it will be useful,
16
    but WITHOUT ANY WARRANTY; without even the implied warranty of
17
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
    GNU General Public License for more details.
19
 
20
    You should have received a copy of the GNU General Public License
21
    along with QBPWCF.  If not, see <http://www.gnu.org/licenses/>.
22
 
23
*/
24
 
25
/*
26
說明:
520 liveuser 27
啟動 web socket server.
28
預設 addr 為 127.0.0.1.
29
預設 port 為 8080.
513 liveuser 30
 
31
範例:
520 liveuser 32
webSocketServer.php [--addr 127.0.0.1] [--port 8080]
513 liveuser 33
*/
34
 
35
#使用命名空間qbpwcf
36
namespace qbpwcf;
37
 
952 liveuser 38
#取得 lib path
39
exec("php -f ".escapeshellarg(pathinfo(__FILE__)["dirname"]."/libexec/folderOfUsrLib.php"),$output,$status);
40
 
41
#如果執行失敗
42
if($status!==0){
43
 
44
	#debug
45
	var_dump(__LINE__,$output);
46
 
47
	#結束執行,回傳shell 1.
48
	exit(1);
49
 
50
	}#if end
51
 
52
#儲存lib path
53
$folderOfUsrLib=$output[0];
54
 
513 liveuser 55
#以該檔案的實際位置的 lib path 為 include path 首位
952 liveuser 56
$output=array();
57
exec("cd ".escapeshellarg(pathinfo(__FILE__)["dirname"]."/../".$folderOfUsrLib."/qbpwcf").";pwd;",$output,$status);
58
 
59
#如果執行失敗
60
if($status!==0){
61
 
62
	#debug
63
	var_dump(__LINE__,$output);
64
 
65
	#結束執行,回傳shell 1.
66
	exit(1);
67
 
68
	}#if end
69
 
70
#設置 include path 
513 liveuser 71
set_include_path($output[0].PATH_SEPARATOR.get_include_path());
72
 
73
#匯入外部套件
74
include("allInOne.php");
75
 
76
#說明函式
77
function help()
78
{
79
	#印出指令說明
80
	echo "Usage of ".basename(__FILE__).":".PHP_EOL; 
520 liveuser 81
	echo "--addr 代表 Server 要 Listen 的 address".PHP_EOL;
513 liveuser 82
	echo "--port 代表 Server 要 Listen 的 port".PHP_EOL;
83
 
84
	#結束執行
85
	exit;
86
}
87
 
88
#函式說明:
89
#解析參數.
90
#回傳結果:
91
#$result["status"],執行是否正常,"true"代表正常,"false"代表不正常.
92
#$reuslt["error"],執行不正常結束的錯訊息陣列.
93
#$result["function"],當前執行的函式名稱.
94
#$result["content"],解析好的參數陣列.
95
#$result["content"][$key][$i],參數 $key 的 $i+1 個參數數值內容.
96
#$result["program"],字串,執行的程式名稱.
97
#必填參數:
98
#無
99
#可省略參數:
100
#$conf["helpFunc"],如果解析的參數不成對,則要執行的函式名稱.
101
$conf["helpFunc"]="help";
102
#備註:
103
#僅能在命令列底下執行.
104
#建議:
105
#以後可將參數 --a--b 的名稱與後面的數值 $value 存成 $result["a"]["b"][$i]=$value .
106
$parseArgu=cmd::parseArgu($conf);
107
unset($conf);
108
 
109
#如果解析參數失敗
110
if($parseArgu["status"]==="false")
111
{
112
	#印出結果
113
	var_dump($parseArgu);
114
 
115
	#結束執行
116
	exit;
117
 
118
}#if end
119
 
120
#檢查參數
121
#函式說明:
122
#檢查必填與可省略參數,可省略參數可指定預設要給與什麼數值內容。
123
#$result["status"],執行是否正常,"true"代表正常,"false"代表不正常.
124
#$reuslt["error"],執行不正常結束的錯訊息陣列.
125
#$result["function"],當前執行的函式名稱.
126
#$result["passed"],識別要檢查的全體變數是否存在以及型態是否正確的變數,"true"代表檢查全部通過;"false"代表檢查不通過
127
#$result[$shouldBeCheckedVarName]["varExist"],所檢查的變數是否存在,"false"代表不存在;"true"代表存在
128
#$result[$shouldBeCheckedVarName]["varType"],所檢查的變數型態是否正確,"false"代表錯誤;"true"代表正確
129
#$result[$shouldBeCheckedVarName]["error"],每個參數設定的錯誤訊息
130
#$result["shouldNotBeEmpty"],不應該為空字串或控陣列的變數.
131
#$result["argu"],字串陣列,目前輸入的參數名稱陣列.
132
#$result["legalVarName"],字串陣列,合法可用的參數名稱陣列.
133
#$result["notNeedVar"],字串陣列,多餘的參數名稱.
134
#必填寫的參數:
135
#$conf["varInput"],陣列變數,要檢查的陣列變數,請在要檢查的參數前面加上&,這樣變動的結果才能被套用。
136
$conf["varInput"]=&$parseArgu["content"];
137
#$conf["referenceVarKey"],字串,$conf參數後面的key值,用於移除不要的參考陣列.
138
$conf["referenceVarKey"]="variableCheck::checkArguments";
139
#可以省略的參數:
140
#$conf["mustBeFilledVariableName"],爲必填參數的變數名稱陣列,形態爲陣列變數,元素數量需要跟"mustBeFilledVariableType"參數的元素數量一致,例如: $conf["mustBeFilledVariableName"] = array("id","account","password");
141
#$conf["mustBeFilledVariableName"]=array("config","acctVarName","passVarName","dbVarName","dbAddrVarName","dbPortVarName","backupAddr");
142
#$conf["mustBeFilledVariableType"],爲必填參數的變數陣列應該爲何種變數形態,形態爲陣列,元素數量需要跟"mustBeFilledVariableName"參數的元素數量一致,例如: $conf["mustBeFilledVariableType"] = array("string",integer,"double","resource","object"); , null代表不指定變數形態.
143
#$conf["mustBeFilledVariableType"]=array("array","array","array","array","array","array","array");
144
#$conf["canBeEmptyString"],字串,必填變數內容如果是空字串就不能算是有設置的話,請設為"false",預設爲"true",可以為空字串.
145
#$conf["canBeEmptyString"]="false";
146
#$conf["canNotBeEmpty"],字串陣列,哪些必填參數的內容不得為空字串或空陣列,僅當$conf["canBeEmptyString"]為"true"時會生效.
147
#$conf["canNotBeEmpty"]=array();
148
#$conf["canBeEmpty"],字串陣列,哪些必填參數的內容可為空字串或空陣列,僅當$conf["canBeEmptyString"]為"false"時會生效.
149
#$conf["canBeEmpty"]=array();
150
#$conf["skipableVariableCanNotBeEmpty"],字串陣列,哪些可省略參數不可以為空字串或空陣列.
151
#$conf["skipableVariableCanNotBeEmpty"]=array("backTime");
152
#$conf["skipableVariableName"],陣列字串,爲可省略參數的變數名稱陣列,形態爲陣列變數,例如: $conf["skipableVariableName"] = array("id","account","password");
520 liveuser 153
$conf["skipableVariableName"]=array("addr","port");
513 liveuser 154
#$conf["skipableVariableType"],陣列字串,爲可省略參數的變數名稱陣列,形態爲陣列變數,例如: $conf["skipableVariableType"] = array("string",integer,"double");
520 liveuser 155
$conf["skipableVariableType"]=array("array","array");
513 liveuser 156
#$conf["skipableVarDefaultValue"],字串陣列,每個不存在的可省略變數要初始化為什麼,null與代表不指定,若預設值是參數之一,請將$conf["mustBeFilledVar"]改成"\$conf["\mustBeFilledVar\"]".
520 liveuser 157
$conf["skipableVarDefaultValue"]=array(array("127.0.0.1"),array("8080"));
513 liveuser 158
#$conf["disallowAllSkipableVarIsEmpty"],字串,是否允許每個可省略參數都為空字串,預設為"true"允許,反之為"false".
159
#$conf["variableCheck::checkArguments"]["disallowAllSkipableVarIsEmpty"]="false";
160
#$conf["disallowAllSkipableVarIsEmptyArray"],字串,是否允許每個可省略參數都為空陣列,預設為"true"允許,反之為"false".
161
#$conf["disallowAllSkipableVarIsEmptyArray"]="";
162
#$conf["arrayCountEqualCheck"],字串陣列,為檢查哪些陣列參數的元素數量要一樣,$conf["arrayCountEqualCheck"][$i]=array()為第$i組key為哪些的變數其元素數量要相等.
163
#$conf["arrayCountEqualCheck"][]=array();
164
#參考資料來源:
165
#array_keys=>http://php.net/manual/en/function.array-keys.php
166
$checkArguments=variableCheck::checkArguments($conf);
167
unset($conf);
168
 
169
#若執行失敗
170
if($checkArguments["status"]==="false"){
171
 
172
	#印出結果
173
	var_dump($checkArguments);
174
 
175
	#結束執行
176
	exit;
177
 
178
	}#if end
179
 
180
#若檢查不通過
181
if($checkArguments["passed"]==="false"){
182
 
183
	#印出結果
184
	var_dump($checkArguments);
185
 
186
	#結束執行
187
	exit;
188
 
189
	}#if end
190
 
191
#取得各項參數
520 liveuser 192
$addr=$parseArgu["content"]["addr"][0];
513 liveuser 193
$port=$parseArgu["content"]["port"][0];
194
 
195
#函式說明:
196
#建立php原生的socket tcp/ip server,進而實作webSocket
197
#回傳結果:
198
#$result["status"],執行正常與否,"true"代表正常,"false"代表不正常.
199
#$result["error"],錯誤訊息陣列.
200
#$resutl["function"],當前執行的涵式名稱.
201
#$result["argu"],所使用的參數.
202
#必填參數:
203
#$conf["fileArgu"],字串,變數__FILE__的內容.
204
$conf["fileArgu"]=__FILE__;
205
#可省略參數:
206
#$conf["listenIp"],字串,要接聽的主機ip,預設為本機的ip.
520 liveuser 207
$conf["listenIp"]=$addr;
513 liveuser 208
#$conf["listenPort"],字串,要接聽的port,預設為已使用port+1.
209
$conf["listenPort"]=$port;
744 liveuser 210
#$conf["wsMode"],字串,是否要用webSocket模式,預設為"false",不使用,若為"true"則要使用.
211
$conf["wsMode"]="true";
513 liveuser 212
#$conf["processFuncs"],陣列,針對收到的訊息要呼叫的函式,會帶入一個參數陣列,array("data"=>收到的資料,"serverSock"=>serverSock,"clientSock"=>clientSock,"clientInfo"=>用戶端的資訊,"clientIndex"=>用戶端的索引,"allConn"=>所有連線的用戶端的連線資訊),回傳的結果若為陣列$result,其$result["status"]為"false"時,會結束執行(等待下個訊息).
213
$conf["processFuncs"]=array("\qbpwcf\pwd");
214
#參考資料:
215
#http://php.net/manual/en/sockets.examples.php
216
#http://us3.php.net/manual/en/function.socket-select.php
217
#response should at least end with "\r"=>http://stackoverflow.com/questions/25739768/websocket-communication-between-chromeclient-and-hotspotserver-status-line
218
#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
219
#webSocket實做=>http://srchea.com/build-a-real-time-application-using-html5-websockets
220
#webSocketServer實做=>http://www.cuelogic.com/blog/php-and-html5-websocket-server-and-client-communication/
221
#備註:
222
#僅能在命令列執行.
223
$nativeSocketTcpIpServer=webSock::nativeSocketTcpIpServer($conf);
224
unset($conf);
225
 
226
#如果 啟動失敗
227
if($nativeSocketTcpIpServer["status"]==="false"){
228
 
229
	#印出結果
230
	var_dump($nativeSocketTcpIpServer);
231
 
232
	#結束執行
233
	exit;
234
 
235
	}#if end
236
 
237
/*
238
函式說明:
239
提供取得當前路徑的功能
240
*/
520 liveuser 241
function pwd(&$params){
513 liveuser 242
 
243
	#取得收到的訊息
244
	$receivedData=$params["data"];
245
 
246
	#取得 server 的 socket
247
	$serverSocket=$params["serverSock"];
248
 
249
	#取得 client 的 socket
250
	$clientSocket=$params["clientSock"];
251
 
252
	#取得 client 的資訊
253
	$clientInfo=$params["clientInfo"];
254
 
255
	#取得 client 的索引
256
	$clientIndex=$params["clientIndex"];
257
 
258
	#取得 all clients 的資訊
259
	$allConn=$params["allConn"];
260
 
261
	#函式說明:
262
	#呼叫shell執行系統命令,並取得回傳的內容.
263
	#回傳結果:
264
	#$result["status"],執行是否正常,"true"代表正常,"false"代表不正常.
265
	#$result["error"],錯誤訊息陣列.
266
	#$result["function"],當前執行的函數名稱.
267
	#$result["argu"],使用的參數.
268
	#$result["cmd"],執行的指令內容.
269
	#$result["fullCmd"],如果參數 $conf["inBackGround"] 為 "true" 則會回傳該值.
270
	#$result["output"],爲執行完二元碼後的輸出陣列,若 $conf["inBackGround"] 為 "true",則為當下的輸出.
271
	#$result["tmpFileOutput"],儲存輸出的暫存檔案名稱,若 $conf["inBackGround"] 為 "true" 則會回傳該值.
272
	#$result["running"],是否還在執行.
273
	#$result["pid"],pid.
274
	#$result["statusCode"],執行結束後的代碼.
275
	#$result["escape"],陣列,儲存重新排序過且已經escape過的指令(key為"cmd")與參數(key為"argu").
276
	#必填參數:
277
	#$conf["command"],字串,要執行的指令.
278
	$conf["command"]="pwd";
279
	#$conf["fileArgu"],字串,變數__FILE__的內容.
280
	$conf["fileArgu"]=__FILE__;
281
	#可省略參數:
282
	#$conf["argu"],陣列字串,指令搭配的參數,預設為空陣列.
283
	#$conf["argu"]=array("");
284
	#$conf["arguIsAddr"],陣列字串,指令搭配的哪些參數為路徑,為路徑的參數會進行轉換以便符合呼叫當前函數的位置,預設不指定,若有3個參數,其中第3個參數為路徑,則表示為array("false","false","true").
285
	#$conf["arguIsAddr"]=array();
286
	#$conf["pre"],陣列,要在本指令前執行的每個指令與參數.
287
	#$conf["pre"][$i]["cmd"],字串,要在本指令前執行的第$i+1個指令.
288
	#$conf["pre"][$i]["param"],陣列字串,要在本指令前執行的第$i+1個指令的參數.
289
	#$conf["enablePrintDescription"],字串,是否要印出$conf["printDescription"]的內容,"true"代表要,"false"代表不要,預設為"false".
290
	#$conf["enablePrintDescription"]="true";
291
	#$conf["printDescription"],字串,執行該外部程式前要印出來的的文字,預設為$conf["command"]的內容加上使用的$conf["argu"]參數.
292
	#$conf["printDescription"]="";
293
	#$conf["escapeshellarg"],字串,是否要啟用過濾參數,用了比較安全,但可能會出錯,"true"為啟用,"false"為不啟用,預設為"false".如果參數為"< 、<< 、> 、>> 、| 、2>&1"之一則不會過濾.
294
	#$conf["escapeshellarg"]="false";
295
	#$conf["thereIsShellVar"],陣列字串,指令搭配的參數"argu",若含有「\'」,則取代為「"」.每個argu參數都要有對應的元素."true"代表要置換.
296
	#$conf["thereIsShellVar"]=array();
297
	#$conf["username"],字串,要用什麼使用者來執行,預設為執行php的使用者,該參數不適用於apache環境.
298
	#$conf["username"]="";
299
	#$conf["password"],字串,root的使用者密碼,預設不使用密碼,該參數不適用於apache環境.
300
	#$conf["password"]="";
301
	#$conf["useScript"],字串,是否要啟用Linux的script指令來記錄輸出,"true"代表要,Fedora的selinux會擋住該操作;"false"代表不要,預設為"false".
302
	#$conf["useScript"]="";
303
	#$conf["logFilePath"],字串,當 $conf["useScript"] 為 "true" 時,輸出的內容要暫存到哪裡,預設為 "/tmp/.qbpwcf_tmp/external/callShell/".
304
	#$conf["logFilePath"]=".qbpwcf_tmp/external/callShell/";
305
	#$conf["inBackGround"],字串,是否要在背景執行,且不會等待程式執行結束再執行下一個指令,"true"代表是,"false"代表不要,預設為"false",如果$conf["command"]有用「;」區隔的多個指令將會出錯.
306
	#$conf["inBackGround"]="";
307
	#$conf["getErr"],字串,"true"代表將錯誤輸出變成標準輸出,反之"false"為不變動.
308
	#$conf["getErr"]="false";
309
	#$conf["doNotRun"],字串,"true"代表不執行指令,預設為"false"會執行指令.
310
	#$conf["doNotRun"]="false";
311
	#參考資料:
312
	#exec=>http://php.net/manual/en/function.exec.php
313
	#escapeshellcmd=>http://php.net/manual/en/function.escapeshellcmd.php
314
	#escapeshellarg=>http://php.net/manual/en/function.escapeshellarg.php
315
	#備註:
316
	#不是所有指令都能用apache的身份執行,目前已知java,javac指令無法執行,使用root身份可能會被selinux阻擋.
317
	#若使用的 command、argu 參數,含有 ~ 則會被視為字串,若有需要其於 shell 中代表的家目錄位置,可用 fileAccess::tildeToPath 來進行轉換.	
318
	$callShell=external::callShell($conf);
319
	unset($conf);
320
 
321
	#如果執行失敗
322
	if($callShell["status"]==="false"){
323
 
324
		#印出結果
520 liveuser 325
		return $callShell;
513 liveuser 326
 
327
		}#if end
328
 
520 liveuser 329
	#取得經過編碼的執行後結果字串
330
	$callShellResultStr=json_encode($callShell);
331
 
332
	#debug
333
	#var_dump(__LINE__,$callShellResultStr);
334
 
335
	#函式說明:
336
	#加密 handshake 後要傳送的訊息 
337
	#回傳結果:
338
	#$result["status"],執行是否正常,"true"代表正常,"false"代表不正常.
339
	#$result["error"],執行不正常結束的錯訊息陣列.
340
	#$result["content"],陣列,加密 handshake 後要傳送給 client 的訊息,若有多個代表要分為多個 Fragmentation 來依序傳送.
341
	#$result["argu"],陣列,使用的參數.
342
	#必填參數:
343
	#$conf["text"],字串,要加密的訊息.
344
	$conf["webSock::encode"]["text"]=$callShellResultStr;
345
	#可省略參數:
346
	#$conf["ping"],字串,"true"代表為ping訊息;反之為"false",預設為"false".
347
	#$conf["ping"]="true";
348
	#參考資料:
349
	#https://www.rfc-editor.org/rfc/rfc6455#page-28, Web Socket Base Framing Protocol.
350
	#備註:
351
	#目前$conf["text"]長度超過125會出錯.
352
	$talkback=webSock::encode($conf["webSock::encode"]);	
513 liveuser 353
	unset($conf["webSock::encode"]);
520 liveuser 354
 
355
	#如果產生 web socket 格式封包 失敗
356
	if($talkback["status"]==="false"){
357
 
358
		#印出結果
359
		return $talkback;
360
 
361
		}#if end
362
 
363
	#針對每個訊息的分段
364
	foreach($talkback["content"] as $msgIndex=>$msg){
365
 
366
		#提示第幾個訊息
367
		echo "第 ".($msgIndex+1)." 個訊息的內容:".PHP_EOL;
368
 
369
		#函式說明:
370
		#將字串中的每個字變成bytes陣列
371
		#回傳結果:
372
		#$result["content"],bytes陣列.
373
		#必填參數:
374
		#$conf["input"],字串,要轉換成bytes陣列的字串.
375
		$conf["stringProcess::str2bytesArray"]["input"]=$msg;
376
		#可省略參數:
377
		#無.
378
		#參考資料:
379
		#無.
380
		#備註:
381
		#無.
382
		$str2bytesArray=stringProcess::str2bytesArray($conf["stringProcess::str2bytesArray"]);
383
		unset($conf["stringProcess::str2bytesArray"]);
384
 
385
		#如果執行失敗
386
		if($str2bytesArray["status"]==="false"){
387
 
388
			#印出結果
389
			return $str2bytesArray;
390
 
391
			}#if end
392
 
393
		#針對每個 bytes
394
		foreach($str2bytesArray["content"] as $byteIndex=>$bytes){
395
 
396
			#函式說明:
397
			#將bytes數字(16進位)轉換為bit字串(0跟1來表述)
398
			#回傳結果:
399
			#$result["content"],bit字串(0跟1來表述).
400
			#必填參數:
401
			#$conf["bytes"],字串,要轉換成bit的bytes數字.
402
			$conf["stringProcess::bytes2bitString"]["bytes"]=$bytes;
403
			#可省略參數:
404
			#無.
405
			#參考資料:
406
			#無.
407
			#備註:
408
			#無.
409
			$bytes2bitString=stringProcess::bytes2bitString($conf["stringProcess::bytes2bitString"]);
410
			unset($conf["stringProcess::bytes2bitString"]);
411
 
412
			#如果執行失敗
413
			if($bytes2bitString["status"]==="false"){
414
 
415
				#印出結果
416
				return $bytes2bitString;
417
 
418
			}#if end
419
 
420
			#印出 8bit
421
			echo $bytes2bitString["content"];
422
 
423
			#如果為 32 bit 結束
424
			if(($byteIndex+1)%4===0){
425
 
426
				#印出換行符號
427
				echo PHP_EOL;
428
 
429
				}#if end
430
 
431
			}#foreach end
432
 
433
		#回傳訊息
434
		$socket_write=socket_write($clientSocket, $msg, strlen($msg));
513 liveuser 435
 
520 liveuser 436
		#換行
437
		echo PHP_EOL;
513 liveuser 438
 
520 liveuser 439
		#debug
440
		#var_dump(__LINE__,$socket_write,socket_strerror(socket_last_error($clientSocket)));
441
 
442
		}#foreach end	
443
 
513 liveuser 444
	#初始化結果
445
	$result=array();
446
 
447
	#設置執行正常
520 liveuser 448
	$result["status"]="continue";
449
 
513 liveuser 450
	#回傳結果
451
	return $result;
452
 
520 liveuser 453
	}#function pwd end
454