ogp_agent.pl 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782
  1. #!/usr/bin/perl
  2. #
  3. # OGP - Open Game Panel
  4. # Copyright (C) 2008 - 2014 The OGP Development Team
  5. #
  6. # http://www.opengamepanel.org/
  7. #
  8. # This program is free software; you can redistribute it and/or
  9. # modify it under the terms of the GNU General Public License
  10. # as published by the Free Software Foundation; either version 2
  11. # of the License, or any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with this program; if not, write to the Free Software
  20. # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  21. #
  22. use warnings;
  23. use strict;
  24. use Cwd; # Fast way to get the current directory
  25. use lib getcwd();
  26. use Frontier::Daemon::Forking; # Forking XML-RPC server
  27. use File::Copy; # Simple file copy functions
  28. use File::Copy::Recursive
  29. qw(fcopy rcopy dircopy fmove rmove dirmove pathempty pathrmdir)
  30. ; # Used to copy whole directories
  31. use File::Basename; # Used to get the file name or the directory name from a given path
  32. use Crypt::XXTEA; # Encryption between webpages and agent.
  33. use Cfg::Config; # Config file
  34. use Cfg::Preferences; # Preferences file
  35. use Fcntl ':flock'; # Import LOCK_* constants for file locking
  36. use LWP::UserAgent; # Used for fetching URLs
  37. use MIME::Base64; # Used to ensure data travelling right through the network.
  38. use Getopt::Long; # Used for command line params.
  39. use Path::Class::File; # Used to handle files and directories.
  40. use File::Path qw(mkpath);
  41. use Archive::Extract; # Used to handle archived files.
  42. use File::Find;
  43. use Schedule::Cron; # Used for scheduling tasks
  44. # Compression tools
  45. use IO::Compress::Bzip2 qw(bzip2 $Bzip2Error); # Used to compress files to bz2.
  46. use Compress::Zlib; # Used to compress file download buffers to zlib.
  47. use Archive::Tar; # Used to create tar, tgz or tbz archives.
  48. use Archive::Zip qw( :ERROR_CODES :CONSTANTS ); # Used to create zip archives.
  49. # Current location of the agent.
  50. use constant AGENT_RUN_DIR => getcwd();
  51. # Load our config file values
  52. use constant AGENT_KEY => $Cfg::Config{key};
  53. use constant AGENT_IP => $Cfg::Config{listen_ip};
  54. use constant AGENT_LOG_FILE => $Cfg::Config{logfile};
  55. use constant AGENT_PORT => $Cfg::Config{listen_port};
  56. use constant AGENT_VERSION => $Cfg::Config{version};
  57. use constant SCREEN_LOG_LOCAL => $Cfg::Preferences{screen_log_local};
  58. use constant DELETE_LOGS_AFTER => $Cfg::Preferences{delete_logs_after};
  59. use constant AGENT_PID_FILE =>
  60. Path::Class::File->new(AGENT_RUN_DIR, 'ogp_agent.pid');
  61. use constant STEAM_LICENSE_OK => "Accept";
  62. use constant STEAM_LICENSE => $Cfg::Config{steam_license};
  63. use constant MANUAL_TMP_DIR => Path::Class::Dir->new(AGENT_RUN_DIR, 'tmp');
  64. use constant STEAMCMD_CLIENT_DIR => Path::Class::Dir->new(AGENT_RUN_DIR, 'steamcmd');
  65. use constant STEAMCMD_CLIENT_BIN =>
  66. Path::Class::File->new(STEAMCMD_CLIENT_DIR, 'steamcmd.sh');
  67. use constant SCREEN_LOGS_DIR =>
  68. Path::Class::Dir->new(AGENT_RUN_DIR, 'screenlogs');
  69. use constant GAME_STARTUP_DIR =>
  70. Path::Class::Dir->new(AGENT_RUN_DIR, 'startups');
  71. use constant SCREENRC_FILE =>
  72. Path::Class::File->new(AGENT_RUN_DIR, 'ogp_screenrc');
  73. use constant SCREENRC_TMP_FILE =>
  74. Path::Class::File->new(AGENT_RUN_DIR, 'ogp_screenrc.tmp');
  75. use constant SCREEN_TYPE_HOME => "HOME";
  76. use constant SCREEN_TYPE_UPDATE => "UPDATE";
  77. use constant FD_DIR => Path::Class::Dir->new(AGENT_RUN_DIR, 'FastDownload');
  78. use constant FD_ALIASES_DIR => Path::Class::Dir->new(FD_DIR, 'aliases');
  79. use constant FD_PID_FILE => Path::Class::File->new(FD_DIR, 'fd.pid');
  80. use constant SCHED_PID => Path::Class::File->new(AGENT_RUN_DIR, 'scheduler.pid');
  81. use constant SCHED_TASKS => Path::Class::File->new(AGENT_RUN_DIR, 'scheduler.tasks');
  82. use constant SCHED_LOG_FILE => Path::Class::File->new(AGENT_RUN_DIR, 'scheduler.log');
  83. $Cfg::Config{sudo_password} =~ s/('+)/'\"$1\"'/g;
  84. our $SUDOPASSWD = $Cfg::Config{sudo_password};
  85. my $no_startups = 0;
  86. my $clear_startups = 0;
  87. our $log_std_out = 0;
  88. GetOptions(
  89. 'no-startups' => \$no_startups,
  90. 'clear-startups' => \$clear_startups,
  91. 'log-stdout' => \$log_std_out
  92. );
  93. # Starting the agent as root user is not supported anymore.
  94. if ($< == 0)
  95. {
  96. print "ERROR: You are trying to start the agent as root user.";
  97. print "This is not currently supported. If you wish to start the";
  98. print "you need to create a normal user account for it.";
  99. exit 1;
  100. }
  101. ### Logger function.
  102. ### @param line the line that is put to the log file.
  103. sub logger
  104. {
  105. my $logcmd = $_[0];
  106. my $also_print = 0;
  107. if (@_ == 2)
  108. {
  109. ($also_print) = $_[1];
  110. }
  111. $logcmd = localtime() . " $logcmd\n";
  112. if ($log_std_out == 1)
  113. {
  114. print "$logcmd";
  115. return;
  116. }
  117. if ($also_print == 1)
  118. {
  119. print "$logcmd";
  120. }
  121. open(LOGFILE, '>>', AGENT_LOG_FILE)
  122. or die("Can't open " . AGENT_LOG_FILE . " - $!");
  123. flock(LOGFILE, LOCK_EX) or die("Failed to lock log file.");
  124. seek(LOGFILE, 0, 2) or die("Failed to seek to end of file.");
  125. print LOGFILE "$logcmd" or die("Failed to write to log file.");
  126. flock(LOGFILE, LOCK_UN) or die("Failed to unlock log file.");
  127. close(LOGFILE) or die("Failed to close log file.");
  128. }
  129. # Rotate the log file
  130. if (-e AGENT_LOG_FILE)
  131. {
  132. if (-e AGENT_LOG_FILE . ".bak")
  133. {
  134. unlink(AGENT_LOG_FILE . ".bak");
  135. }
  136. logger "Rotating log file";
  137. move(AGENT_LOG_FILE, AGENT_LOG_FILE . ".bak");
  138. logger "New log file created";
  139. }
  140. open INPUTFILE, "<", SCREENRC_FILE or die $!;
  141. open OUTPUTFILE, ">", SCREENRC_TMP_FILE or die $!;
  142. my $dest = SCREEN_LOGS_DIR . "/screenlog.%t";
  143. while (<INPUTFILE>)
  144. {
  145. $_ =~ s/logfile.*/logfile $dest/g;
  146. print OUTPUTFILE $_;
  147. }
  148. close INPUTFILE;
  149. close OUTPUTFILE;
  150. unlink SCREENRC_FILE;
  151. move(SCREENRC_TMP_FILE,SCREENRC_FILE);
  152. # Check the screen logs folder
  153. if (!-d SCREEN_LOGS_DIR && !mkdir SCREEN_LOGS_DIR)
  154. {
  155. logger "Could not create " . SCREEN_LOGS_DIR . " directory $!.", 1;
  156. exit -1;
  157. }
  158. if (check_steam_cmd_client() == -1)
  159. {
  160. print "ERROR: You must download and uncompress the new steamcmd package.";
  161. print "BE SURE TO INSTALL IT IN " . AGENT_RUN_DIR . "/steamcmd directory,";
  162. print "so it can be managed by the agent to install servers.";
  163. exit 1;
  164. }
  165. # create the directory for startup flags
  166. if (!-e GAME_STARTUP_DIR)
  167. {
  168. logger "Creating the startups directory " . GAME_STARTUP_DIR . "";
  169. if (!mkdir GAME_STARTUP_DIR)
  170. {
  171. my $message =
  172. "Failed to create the "
  173. . GAME_STARTUP_DIR
  174. . " directory - check permissions. Errno: $!";
  175. logger $message, 1;
  176. exit 1;
  177. }
  178. }
  179. elsif ($clear_startups)
  180. {
  181. opendir(STARTUPDIR, GAME_STARTUP_DIR);
  182. while (my $startup_file = readdir(STARTUPDIR))
  183. {
  184. # Skip . and ..
  185. next if $startup_file =~ /^\./;
  186. $startup_file = Path::Class::File->new(GAME_STARTUP_DIR, $startup_file);
  187. logger "Removing " . $startup_file . ".";
  188. unlink($startup_file);
  189. }
  190. closedir(STARTUPDIR);
  191. }
  192. # If the directory already existed check if we need to start some games.
  193. elsif ($no_startups != 1)
  194. {
  195. # Loop through all the startup flags, and call universal startup
  196. opendir(STARTUPDIR, GAME_STARTUP_DIR);
  197. logger "Reading startup flags from " . GAME_STARTUP_DIR . "";
  198. while (my $dirlist = readdir(STARTUPDIR))
  199. {
  200. # Skip . and ..
  201. next if $dirlist =~ /^\./;
  202. logger "Found $dirlist";
  203. open(STARTFILE, '<', Path::Class::Dir->new(GAME_STARTUP_DIR, $dirlist))
  204. || logger "Error opening start flag $!";
  205. while (<STARTFILE>)
  206. {
  207. my (
  208. $home_id, $home_path, $server_exe,
  209. $run_dir, $startup_cmd, $server_port,
  210. $server_ip, $cpu, $nice, $preStart, $envVars
  211. ) = split(',', $_);
  212. if (is_screen_running_without_decrypt(SCREEN_TYPE_HOME, $home_id) ==
  213. 1)
  214. {
  215. logger
  216. "This server ($server_exe on $server_ip : $server_port) is already running (ID: $home_id).";
  217. next;
  218. }
  219. logger "Starting server_exe $server_exe from home $home_path.";
  220. universal_start_without_decrypt(
  221. $home_id, $home_path, $server_exe,
  222. $run_dir, $startup_cmd, $server_port,
  223. $server_ip, $cpu, $nice, $preStart, $envVars
  224. );
  225. }
  226. close(STARTFILE);
  227. }
  228. closedir(STARTUPDIR);
  229. }
  230. # Create the pid file
  231. open(PID, '>', AGENT_PID_FILE)
  232. or die("Can't write to pid file - " . AGENT_PID_FILE . "\n");
  233. print PID "$$\n";
  234. close(PID);
  235. logger "Open Game Panel - Agent started - "
  236. . AGENT_VERSION
  237. . " - port "
  238. . AGENT_PORT
  239. . " - PID $$", 1;
  240. # Stop previous scheduler process if exists
  241. scheduler_stop();
  242. # Create new object with default dispatcher for scheduled tasks
  243. my $cron = new Schedule::Cron( \&scheduler_dispatcher, {
  244. nofork => 1,
  245. loglevel => 0,
  246. log => sub { print $_[1], "\n"; }
  247. } );
  248. $cron->add_entry( "* * * * * *", \&scheduler_read_tasks );
  249. # Run scheduler
  250. $cron->run( {detach=>1, pid_file=>SCHED_PID} );
  251. if(-e Path::Class::File->new(FD_DIR, 'Settings.pm'))
  252. {
  253. require "FastDownload/Settings.pm"; # Settings for Fast Download Daemon.
  254. if(defined($FastDownload::Settings{autostart_on_agent_startup}) && $FastDownload::Settings{autostart_on_agent_startup} eq "1")
  255. {
  256. start_fastdl();
  257. }
  258. }
  259. my $d = Frontier::Daemon::Forking->new(
  260. methods => {
  261. is_screen_running => \&is_screen_running,
  262. universal_start => \&universal_start,
  263. renice_process => \&renice_process,
  264. cpu_count => \&cpu_count,
  265. rfile_exists => \&rfile_exists,
  266. quick_chk => \&quick_chk,
  267. steam_cmd => \&steam_cmd,
  268. get_log => \&get_log,
  269. stop_server => \&stop_server,
  270. send_rcon_command => \&send_rcon_command,
  271. dirlist => \&dirlist,
  272. dirlistfm => \&dirlistfm,
  273. readfile => \&readfile,
  274. writefile => \&writefile,
  275. rebootnow => \&rebootnow,
  276. what_os => \&what_os,
  277. start_file_download => \&start_file_download,
  278. lock_additional_files => \&lock_additional_files,
  279. is_file_download_in_progress => \&is_file_download_in_progress,
  280. uncompress_file => \&uncompress_file,
  281. discover_ips => \&discover_ips,
  282. mon_stats => \&mon_stats,
  283. exec => \&exec,
  284. clone_home => \&clone_home,
  285. remove_home => \&remove_home,
  286. start_rsync_install => \&start_rsync_install,
  287. rsync_progress => \&rsync_progress,
  288. restart_server => \&restart_server,
  289. sudo_exec => \&sudo_exec,
  290. master_server_update => \&master_server_update,
  291. secure_path => \&secure_path,
  292. get_chattr => \&get_chattr,
  293. ftp_mgr => \&ftp_mgr,
  294. compress_files => \&compress_files,
  295. stop_fastdl => \&stop_fastdl,
  296. restart_fastdl => \&restart_fastdl,
  297. fastdl_status => \&fastdl_status,
  298. fastdl_get_aliases => \&fastdl_get_aliases,
  299. fastdl_add_alias => \&fastdl_add_alias,
  300. fastdl_del_alias => \&fastdl_del_alias,
  301. fastdl_get_info => \&fastdl_get_info,
  302. fastdl_create_config => \&fastdl_create_config,
  303. agent_restart => \&agent_restart,
  304. scheduler_add_task => \&scheduler_add_task,
  305. scheduler_del_task => \&scheduler_del_task,
  306. scheduler_list_tasks => \&scheduler_list_tasks,
  307. scheduler_edit_task => \&scheduler_edit_task,
  308. get_file_part => \&get_file_part,
  309. stop_update => \&stop_update,
  310. shell_action => \&shell_action,
  311. remote_query => \&remote_query
  312. },
  313. debug => 4,
  314. LocalPort => AGENT_PORT,
  315. LocalAddr => AGENT_IP,
  316. ReuseAddr => '1'
  317. ) or die "Couldn't start OGP Agent: $!";
  318. sub backup_home_log
  319. {
  320. my ($home_id, $log_file) = @_;
  321. my $home_backup_dir = SCREEN_LOGS_DIR . "/home_id_" . $home_id;
  322. if( ! -e $home_backup_dir )
  323. {
  324. if( ! mkdir $home_backup_dir )
  325. {
  326. logger "Can not create a backup directory at $home_backup_dir.";
  327. return 1;
  328. }
  329. }
  330. my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
  331. my $backup_file_name = $mday . $mon . $year . '_' . $hour . 'h' . $min . 'm' . $sec . "s.log";
  332. my $output_path = $home_backup_dir . "/" . $backup_file_name;
  333. # Used for deleting log files older than DELETE_LOGS_AFTER
  334. my @file_list;
  335. my @find_dirs; # directories to search
  336. my $now = time(); # get current time
  337. my $days;
  338. if((DELETE_LOGS_AFTER =~ /^[+-]?\d+$/) && (DELETE_LOGS_AFTER > 0)){
  339. $days = DELETE_LOGS_AFTER; # how many days old
  340. }else{
  341. $days = 30; # how many days old
  342. }
  343. my $seconds_per_day = 60*60*24; # seconds in a day
  344. my $AGE = $days*$seconds_per_day; # age in seconds
  345. push (@find_dirs, $home_backup_dir);
  346. # Create local copy of log file backup in the log_backups folder and current user home directory if SCREEN_LOG_LOCAL = 1
  347. if(SCREEN_LOG_LOCAL == 1)
  348. {
  349. # Create local backups folder
  350. my $local_log_folder = Path::Class::Dir->new("logs_backup");
  351. if(!-e $local_log_folder){
  352. mkdir($local_log_folder);
  353. }
  354. # Add full path to @find_dirs so that log files older than DELETE_LOGS_AFTER are deleted
  355. my $fullpath_to_local_logs = Path::Class::Dir->new(getcwd(), "logs_backup");
  356. push (@find_dirs, $fullpath_to_local_logs);
  357. my $log_local = $local_log_folder . "/" . $backup_file_name;
  358. # Delete the local log file if it already exists
  359. if(-e $log_local){
  360. unlink $log_local;
  361. }
  362. # If the log file contains UPDATE in the filename, do not allow users to see it since it will contain steam credentials
  363. # Will return -1 for not existing
  364. my $isUpdate = index($log_file,SCREEN_TYPE_UPDATE);
  365. if($isUpdate == -1){
  366. copy($log_file,$log_local);
  367. }
  368. }
  369. # Delete all files in @find_dirs older than DELETE_LOGS_AFTER days
  370. find ( sub {
  371. my $file = $File::Find::name;
  372. if ( -f $file ) {
  373. push (@file_list, $file);
  374. }
  375. }, @find_dirs);
  376. for my $file (@file_list) {
  377. my @stats = stat($file);
  378. if ($now-$stats[9] > $AGE) {
  379. unlink $file;
  380. }
  381. }
  382. move($log_file,$output_path);
  383. return 0;
  384. }
  385. sub get_home_pids
  386. {
  387. my ($home_id) = @_;
  388. my $screen_id = create_screen_id(SCREEN_TYPE_HOME, $home_id);
  389. my ($pid, @pids);
  390. ($pid) = split(/\./, `screen -ls | grep -E -o "[0-9]+\.$screen_id"`, 2);
  391. chomp($pid);
  392. while ($pid =~ /^[0-9]+$/)
  393. {
  394. push(@pids,$pid);
  395. $pid = `pgrep -P $pid`;
  396. chomp($pid);
  397. }
  398. return @pids;
  399. }
  400. sub create_screen_id
  401. {
  402. my ($screen_type, $home_id) = @_;
  403. return sprintf("OGP_%s_%09d", $screen_type, $home_id);
  404. }
  405. sub create_screen_cmd
  406. {
  407. my ($screen_id, $exec_cmd) = @_;
  408. $exec_cmd = replace_OGP_Vars($screen_id, $exec_cmd);
  409. return
  410. sprintf('export WINEDEBUG="fixme-all" && export DISPLAY=:1 && screen -d -m -t "%1$s" -c ' . SCREENRC_FILE . ' -S %1$s %2$s',
  411. $screen_id, $exec_cmd);
  412. }
  413. sub create_screen_cmd_loop
  414. {
  415. my ($screen_id, $exec_cmd, $envVars) = @_;
  416. my $server_start_bashfile = $screen_id . "_startup_scr.sh";
  417. $exec_cmd = replace_OGP_Vars($screen_id, $exec_cmd);
  418. # Allow file to be overwritten
  419. if(-e $server_start_bashfile){
  420. secure_path_without_decrypt('chattr-i', $server_start_bashfile);
  421. }
  422. # Create bash file that screen will run which spawns the server
  423. # If it crashes without user intervention, it will restart
  424. open (SERV_START_SCRIPT, '>', $server_start_bashfile);
  425. my $respawn_server_command = "#!/bin/bash" . "\n"
  426. . "function startServer(){" . "\n" ;
  427. if(defined $envVars && $envVars ne ""){
  428. $respawn_server_command .= $envVars;
  429. }
  430. $respawn_server_command .= "NUMSECONDS=`expr \$(date +%s)`" . "\n"
  431. . "until " . $exec_cmd . "; do" . "\n"
  432. . "let DIFF=(`date +%s` - \"\$NUMSECONDS\")" . "\n"
  433. . "if [ \"\$DIFF\" -gt 15 ]; then" . "\n"
  434. . "NUMSECONDS=`expr \$(date +%s)`" . "\n"
  435. . "echo \"Server '" . $exec_cmd . "' crashed with exit code \$?. Respawning...\" >&2 " . "\n"
  436. . "fi" . "\n"
  437. . "sleep 3" . "\n"
  438. . "done" . "\n"
  439. . "let DIFF=(`date +%s` - \"\$NUMSECONDS\")" . "\n"
  440. . "if [ ! -e \"SERVER_STOPPED\" ] && [ \"\$DIFF\" -gt 15 ]; then" . "\n"
  441. . "startServer" . "\n"
  442. . "fi" . "\n"
  443. . "}" . "\n"
  444. . "startServer" . "\n";
  445. print SERV_START_SCRIPT $respawn_server_command;
  446. close (SERV_START_SCRIPT);
  447. # Secure file
  448. secure_path_without_decrypt('chattr+i', $server_start_bashfile);
  449. my $screen_exec_script = "bash " . $server_start_bashfile;
  450. return
  451. sprintf('export WINEDEBUG="fixme-all" && export DISPLAY=:1 && screen -d -m -t "%1$s" -c ' . SCREENRC_FILE . ' -S %1$s %2$s',
  452. $screen_id, $screen_exec_script);
  453. }
  454. sub replace_OGP_Vars{
  455. # This function replaces constants from game server XML Configs with OGP paths for Steam Auto Updates for example
  456. my ($screen_id, $exec_cmd) = @_;
  457. my $screen_id_for_txt_update = substr ($screen_id, rindex($screen_id, '_') + 1);
  458. my $steamInsFile = $screen_id_for_txt_update . "_install.txt";
  459. my $steamCMDPath = STEAMCMD_CLIENT_DIR;
  460. my $fullPath = Path::Class::File->new($steamCMDPath, $steamInsFile);
  461. # If the install file exists, the game can be auto updated, else it will be ignored by the game for improper syntax
  462. # To generate the install file, the "Install/Update via Steam" button must be clicked on at least once!
  463. if(-e $fullPath){
  464. $exec_cmd =~ s/{OGP_STEAM_CMD_DIR}/$steamCMDPath/g;
  465. $exec_cmd =~ s/{STEAMCMD_INSTALL_FILE}/$steamInsFile/g;
  466. }
  467. return $exec_cmd;
  468. }
  469. sub replace_OGP_Env_Vars{
  470. # This function replaces constants from environment variables set in the XML
  471. my ($homeid, $homepath, $strToReplace) = @_;
  472. $strToReplace =~ s/{OGP_HOME_DIR}/$homepath/g;
  473. return $strToReplace;
  474. }
  475. sub encode_list
  476. {
  477. my $encoded_content = '';
  478. if(@_)
  479. {
  480. foreach my $line (@_)
  481. {
  482. $encoded_content .= encode_base64($line, "") . '\n';
  483. }
  484. }
  485. return $encoded_content;
  486. }
  487. sub decrypt_param
  488. {
  489. my ($param) = @_;
  490. $param = decode_base64($param);
  491. $param = Crypt::XXTEA::decrypt($param, AGENT_KEY);
  492. $param = decode_base64($param);
  493. return $param;
  494. }
  495. sub decrypt_params
  496. {
  497. my @params;
  498. foreach my $param (@_)
  499. {
  500. $param = &decrypt_param($param);
  501. push(@params, $param);
  502. }
  503. return @params;
  504. }
  505. sub check_steam_cmd_client
  506. {
  507. if (STEAM_LICENSE ne STEAM_LICENSE_OK)
  508. {
  509. logger "Steam license not accepted, stopping Steam client check.";
  510. return 0;
  511. }
  512. if (!-d STEAMCMD_CLIENT_DIR && !mkdir STEAMCMD_CLIENT_DIR)
  513. {
  514. logger "Could not create " . STEAMCMD_CLIENT_DIR . " directory $!.", 1;
  515. exit -1;
  516. }
  517. if (!-w STEAMCMD_CLIENT_DIR)
  518. {
  519. logger "Steam client dir '"
  520. . STEAMCMD_CLIENT_DIR
  521. . "' not writable. Unable to get Steam client.";
  522. return -1;
  523. }
  524. if (!-f STEAMCMD_CLIENT_BIN)
  525. {
  526. logger "The Steam client, steamcmd, does not exist yet, installing...";
  527. my $steam_client_file = 'steamcmd_linux.tar.gz';
  528. my $steam_client_path = Path::Class::File->new(STEAMCMD_CLIENT_DIR, $steam_client_file);
  529. my $steam_client_url =
  530. "http://media.steampowered.com/client/" . $steam_client_file;
  531. logger "Downloading the Steam client from $steam_client_url to '"
  532. . $steam_client_path . "'.";
  533. my $ua = LWP::UserAgent->new;
  534. $ua->agent('Mozilla/5.0');
  535. my $response = $ua->get($steam_client_url, ':content_file' => "$steam_client_path");
  536. unless ($response->is_success)
  537. {
  538. logger "Failed to download steam installer from "
  539. . $steam_client_url
  540. . ".", 1;
  541. return -1;
  542. }
  543. if (-f $steam_client_path)
  544. {
  545. logger "Uncompressing $steam_client_path";
  546. if ( uncompress_file_without_decrypt($steam_client_path, STEAMCMD_CLIENT_DIR) != 1 )
  547. {
  548. unlink($steam_client_path);
  549. logger "Unable to uncompress $steam_client_path, the file has been removed.";
  550. return -1;
  551. }
  552. unlink($steam_client_path);
  553. }
  554. }
  555. if (!-x STEAMCMD_CLIENT_BIN)
  556. {
  557. if ( ! chmod 0755, STEAMCMD_CLIENT_BIN )
  558. {
  559. logger "Unable to apply execution permission to ".STEAMCMD_CLIENT_BIN.".";
  560. }
  561. }
  562. return 1;
  563. }
  564. sub is_screen_running
  565. {
  566. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  567. my ($screen_type, $home_id) = decrypt_params(@_);
  568. return is_screen_running_without_decrypt($screen_type, $home_id);
  569. }
  570. sub is_screen_running_without_decrypt
  571. {
  572. my ($screen_type, $home_id) = @_;
  573. my $screen_id = create_screen_id($screen_type, $home_id);
  574. my $is_running = `screen -list | grep $screen_id`;
  575. if ($is_running =~ /^\s*$/)
  576. {
  577. return 0;
  578. }
  579. else
  580. {
  581. return 1;
  582. }
  583. }
  584. # Delete Server Stopped Status File:
  585. sub deleteStoppedStatFile
  586. {
  587. my ($home_path) = @_;
  588. my $server_stop_status_file = Path::Class::File->new($home_path, "SERVER_STOPPED");
  589. if(-e $server_stop_status_file)
  590. {
  591. unlink $server_stop_status_file;
  592. }
  593. }
  594. # Universal startup function
  595. sub universal_start
  596. {
  597. chomp(@_);
  598. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  599. return universal_start_without_decrypt(decrypt_params(@_));
  600. }
  601. # Split to two parts because of internal calls.
  602. sub universal_start_without_decrypt
  603. {
  604. my (
  605. $home_id, $home_path, $server_exe, $run_dir,
  606. $startup_cmd, $server_port, $server_ip, $cpu, $nice, $preStart, $envVars
  607. ) = @_;
  608. # Replace any {OGP_HOME_DIR} in the $start_cmd with the server's home directory path
  609. $startup_cmd = replace_OGP_Env_Vars($home_id, $home_path, $startup_cmd);
  610. if (is_screen_running_without_decrypt(SCREEN_TYPE_HOME, $home_id) == 1)
  611. {
  612. logger "This server is already running (ID: $home_id).";
  613. return -14;
  614. }
  615. if (!-e $home_path)
  616. {
  617. logger "Can't find server's install path [ $home_path ].";
  618. return -10;
  619. }
  620. my $uid = `id -u`;
  621. chomp $uid;
  622. my $gid = `id -g`;
  623. chomp $gid;
  624. my $path = $home_path;
  625. $path =~ s/('+)/'\"$1\"'/g;
  626. sudo_exec_without_decrypt('chown -Rf '.$uid.':'.$gid.' \''.$path.'\'');
  627. # Some game require that we are in the directory where the binary is.
  628. my $game_binary_dir = Path::Class::Dir->new($home_path, $run_dir);
  629. if ( -e $game_binary_dir && !chdir $game_binary_dir)
  630. {
  631. logger "Could not change to server binary directory $game_binary_dir.";
  632. return -12;
  633. }
  634. secure_path_without_decrypt('chattr-i', $server_exe);
  635. if (!-x $server_exe)
  636. {
  637. if (!chmod 0755, $server_exe)
  638. {
  639. logger "The $server_exe file is not executable.";
  640. return -13;
  641. }
  642. }
  643. if(defined $preStart && $preStart ne ""){
  644. # Get it in the format that the startup file can use
  645. $preStart = multiline_to_startup_comma_format($preStart);
  646. }else{
  647. $preStart = "";
  648. }
  649. if(defined $envVars && $envVars ne ""){
  650. # Replace variables in the envvars if they exist
  651. my @prestartenvvars = split /[\r\n]+/, $envVars;
  652. my $envVarStr = "";
  653. foreach my $line (@prestartenvvars) {
  654. $line = replace_OGP_Env_Vars($home_id, $home_path, $line);
  655. if($line ne ""){
  656. logger "Configuring environment variable: $line";
  657. $envVarStr .= "$line\n";
  658. }
  659. }
  660. if(defined $envVarStr && $envVarStr ne ""){
  661. $envVars = $envVarStr;
  662. }
  663. # Get it in the format that the startup file can use
  664. $envVars = multiline_to_startup_comma_format($envVars);
  665. }else{
  666. $envVars = "";
  667. }
  668. secure_path_without_decrypt('chattr+i', $server_exe);
  669. # Create startup file for the server.
  670. my $startup_file =
  671. Path::Class::File->new(GAME_STARTUP_DIR, "$server_ip-$server_port");
  672. if (open(STARTUP, '>', $startup_file))
  673. {
  674. print STARTUP
  675. "$home_id,$home_path,$server_exe,$run_dir,$startup_cmd,$server_port,$server_ip,$cpu,$nice,$preStart,$envVars";
  676. logger "Created startup flag for $server_ip-$server_port";
  677. close(STARTUP);
  678. }
  679. else
  680. {
  681. logger "Cannot create file in " . $startup_file . " : $!";
  682. }
  683. if(defined $preStart && $preStart ne ""){
  684. # Get it in the format that the startup file can use
  685. $preStart = startup_comma_format_to_multiline($preStart);
  686. }else{
  687. $preStart = "";
  688. }
  689. if(defined $envVars && $envVars ne ""){
  690. # Get it in the format that the startup file can use
  691. $envVars = startup_comma_format_to_multiline($envVars);
  692. }else{
  693. $envVars = "";
  694. }
  695. # Create the startup string.
  696. my $screen_id = create_screen_id(SCREEN_TYPE_HOME, $home_id);
  697. my $file_extension = substr $server_exe, -4;
  698. my $cli_bin;
  699. my $command;
  700. my $run_before_start;
  701. if($file_extension eq ".exe" or $file_extension eq ".bat")
  702. {
  703. $command = "wine $server_exe $startup_cmd";
  704. if ($cpu ne 'NA')
  705. {
  706. $command = "taskset -c $cpu wine $server_exe $startup_cmd";
  707. }
  708. if(defined($Cfg::Preferences{ogp_autorestart_server}) && $Cfg::Preferences{ogp_autorestart_server} eq "1"){
  709. deleteStoppedStatFile($home_path);
  710. $cli_bin = create_screen_cmd_loop($screen_id, $command, $envVars);
  711. }else{
  712. $cli_bin = create_screen_cmd($screen_id, $command);
  713. }
  714. }
  715. elsif($file_extension eq ".jar")
  716. {
  717. $command = "$startup_cmd";
  718. if ($cpu ne 'NA')
  719. {
  720. $command = "taskset -c $cpu $startup_cmd";
  721. }
  722. if(defined($Cfg::Preferences{ogp_autorestart_server}) && $Cfg::Preferences{ogp_autorestart_server} eq "1"){
  723. deleteStoppedStatFile($home_path);
  724. $cli_bin = create_screen_cmd_loop($screen_id, $command, $envVars);
  725. }else{
  726. $cli_bin = create_screen_cmd($screen_id, $command);
  727. }
  728. }
  729. else
  730. {
  731. $command = "./$server_exe $startup_cmd";
  732. if ($cpu ne 'NA')
  733. {
  734. $command = "taskset -c $cpu ./$server_exe $startup_cmd";
  735. }
  736. if(defined($Cfg::Preferences{ogp_autorestart_server}) && $Cfg::Preferences{ogp_autorestart_server} eq "1"){
  737. deleteStoppedStatFile($home_path);
  738. $cli_bin = create_screen_cmd_loop($screen_id, $command, $envVars);
  739. }else{
  740. $cli_bin = create_screen_cmd($screen_id, $command);
  741. }
  742. }
  743. my $log_file = Path::Class::File->new(SCREEN_LOGS_DIR, "screenlog.$screen_id");
  744. backup_home_log( $home_id, $log_file );
  745. logger
  746. "Startup command [ $cli_bin ] will be executed in dir $game_binary_dir.";
  747. # Run before start script and set environment variables which will affect create_screen_cmd only... loop already has the envvars as well
  748. $run_before_start = run_before_start_commands($home_id, $home_path, $preStart, $envVars);
  749. system($cli_bin);
  750. sleep(1);
  751. renice_process_without_decrypt($home_id, $nice);
  752. chdir AGENT_RUN_DIR;
  753. return 1;
  754. }
  755. # This is used to change the priority of process
  756. # @return 1 if successfully set prosess priority
  757. # @return -1 in case of an error.
  758. sub renice_process
  759. {
  760. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  761. return renice_process_without_decrypt(decrypt_params(@_));
  762. }
  763. sub renice_process_without_decrypt
  764. {
  765. my ($home_id, $nice) = @_;
  766. if ($nice != 0)
  767. {
  768. my @pids = get_home_pids($home_id);
  769. logger
  770. "Renicing pids [ @pids ] from home_id $home_id with nice value $nice.";
  771. foreach my $pid (@pids)
  772. {
  773. my $rpid = kill 0, $pid;
  774. if ($rpid == 1)
  775. {
  776. my $ret = sudo_exec_without_decrypt('/usr/bin/renice '.$nice.' '.$pid);
  777. ($ret) = split(/;/, $ret, 2);
  778. if($ret != 1)
  779. {
  780. logger "Unable to renice process, probably bad sudo password or not in sudoers list.";
  781. return -1
  782. }
  783. }
  784. }
  785. }
  786. return 1;
  787. }
  788. # This is used to force a process to run on a particular CPU
  789. sub force_cpu
  790. {
  791. return force_cpu_without_decrypt(decrypt_params(@_));
  792. }
  793. sub force_cpu_without_decrypt
  794. {
  795. my ($home_id, $cpu) = @_;
  796. if ($cpu ne 'NA')
  797. {
  798. my @pids = get_home_pids($home_id);
  799. logger
  800. "Setting server from home_id $home_id with pids @pids to run on CPU $cpu.";
  801. foreach my $pid (@pids)
  802. {
  803. my $rpid = kill 0, $pid;
  804. if ($rpid == 1)
  805. {
  806. my $ret = sudo_exec_without_decrypt('/usr/bin/taskset -pc '.$cpu.' '.$pid);
  807. ($ret) = split(/;/, $ret, 2);
  808. if($ret != 1)
  809. {
  810. logger "Unable to set cpu, probably a bad sudo password or not in sudoers list.";
  811. return -1
  812. }
  813. }
  814. }
  815. }
  816. return 1;
  817. }
  818. # Returns the number of CPUs available.
  819. sub cpu_count
  820. {
  821. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  822. if (!-e "/proc/cpuinfo")
  823. {
  824. return "ERROR - Missing /proc/cpuinfo";
  825. }
  826. open(CPUINFO, '<', "/proc/cpuinfo")
  827. or return "ERROR - Cannot open /proc/cpuinfo";
  828. my $cpu_count = 0;
  829. while (<CPUINFO>)
  830. {
  831. chomp;
  832. next if $_ !~ /^processor/;
  833. $cpu_count++;
  834. }
  835. close(CPUINFO);
  836. return "$cpu_count";
  837. }
  838. ### File exists check ####
  839. # Simple a way to check if a file exists using the remote agent
  840. #
  841. # @return 0 when file exists.
  842. # @return 1 when file does not exist.
  843. sub rfile_exists
  844. {
  845. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  846. chdir AGENT_RUN_DIR;
  847. my $checkFile = decrypt_param(@_);
  848. if (-e $checkFile)
  849. {
  850. return 0;
  851. }
  852. else
  853. {
  854. return 1;
  855. }
  856. }
  857. #### Quick check to verify agent is up and running
  858. # Used to quickly see if the agent is online, and if the keys match.
  859. # The message that is sent to the agent must be hello, if not then
  860. # it is intrepret as encryption key missmatch.
  861. #
  862. # @return 1 when encrypted message is not 'hello'
  863. # @return 0 when check is ok.
  864. sub quick_chk
  865. {
  866. my $dec_check = &decrypt_param(@_);
  867. if ($dec_check ne 'hello')
  868. {
  869. logger "ERROR - Encryption key mismatch! Returning 1 to asker.";
  870. return 1;
  871. }
  872. return 0;
  873. }
  874. ### Return -10 If home path is not found.
  875. ### Return -9 If log type was invalid.
  876. ### Return -8 If log file was not found.
  877. ### 0 reserved for connection problems.
  878. ### Return 1;content If log found and screen running.
  879. ### Return 2;content If log found but screen is not running.
  880. sub get_log
  881. {
  882. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  883. my ($screen_type, $home_id, $home_path, $nb_of_lines, $log_file) = decrypt_params(@_);
  884. if (!chdir $home_path)
  885. {
  886. logger "Can't change to server's install path [ $home_path ].";
  887. return -10;
  888. }
  889. if ( ($screen_type eq SCREEN_TYPE_UPDATE)
  890. && ($screen_type eq SCREEN_TYPE_HOME))
  891. {
  892. logger "Invalid screen type '$screen_type'.";
  893. return -9;
  894. }
  895. if(!$log_file)
  896. {
  897. my $screen_id = create_screen_id($screen_type, $home_id);
  898. $log_file = Path::Class::File->new(SCREEN_LOGS_DIR, "screenlog.$screen_id");
  899. }
  900. else
  901. {
  902. $log_file = Path::Class::File->new($home_path, $log_file);
  903. }
  904. chmod 0644, $log_file;
  905. # Create local copy of current log file if SCREEN_LOG_LOCAL = 1
  906. if(SCREEN_LOG_LOCAL == 1)
  907. {
  908. my $log_local = Path::Class::File->new($home_path, "LOG_$screen_type.txt");
  909. if ( -e $log_local )
  910. {
  911. unlink $log_local;
  912. }
  913. # Copy log file only if it's not an UPDATE type as it may contain steam credentials
  914. if($screen_type eq SCREEN_TYPE_HOME){
  915. copy($log_file, $log_local);
  916. }
  917. }
  918. # Regenerate the log file if it doesn't exist
  919. unless ( -e $log_file )
  920. {
  921. if (open(NEWLOG, '>', $log_file))
  922. {
  923. logger "Log file missing, regenerating: " . $log_file;
  924. print NEWLOG "Log file missing, started new log\n";
  925. close(NEWLOG);
  926. }
  927. else
  928. {
  929. logger "Cannot regenerate log file in " . $log_file . " : $!";
  930. return -8;
  931. }
  932. }
  933. # Return a few lines of output to the web browser
  934. my(@modedlines) = `tail -n $nb_of_lines $log_file`;
  935. my $linecount = 0;
  936. foreach my $line (@modedlines) {
  937. #Text replacements to remove the Steam user login from steamcmd logs for security reasons.
  938. $line =~ s/login .*//g;
  939. $line =~ s/Logging .*//g;
  940. $line =~ s/set_steam_guard_code.*//g;
  941. $line =~ s/force_install_dir.*//g;
  942. #Text replacements to remove empty lines.
  943. $line =~ s/^ +//g;
  944. $line =~ s/^\t+//g;
  945. $line =~ s/^\e+//g;
  946. #Remove � from console output when master server update is running.
  947. $line =~ s/�//g;
  948. $modedlines[$linecount]=$line;
  949. $linecount++;
  950. }
  951. my $encoded_content = encode_list(@modedlines);
  952. chdir AGENT_RUN_DIR;
  953. if(is_screen_running_without_decrypt($screen_type, $home_id) == 1)
  954. {
  955. return "1;" . $encoded_content;
  956. }
  957. else
  958. {
  959. return "2;" . $encoded_content;
  960. }
  961. }
  962. # stop server function
  963. sub stop_server
  964. {
  965. chomp(@_);
  966. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  967. return stop_server_without_decrypt(decrypt_params(@_));
  968. }
  969. ##### Stop server without decrypt
  970. ### Return 1 when error occurred on decryption.
  971. ### Return 0 on success
  972. sub stop_server_without_decrypt
  973. {
  974. my ($home_id, $server_ip, $server_port, $control_protocol,
  975. $control_password, $control_type, $home_path) = @_;
  976. my $startup_file = Path::Class::File->new(GAME_STARTUP_DIR, "$server_ip-$server_port");
  977. if (-e $startup_file)
  978. {
  979. logger "Removing startup flag " . $startup_file . "";
  980. unlink($startup_file)
  981. or logger "Cannot remove the startup flag file $startup_file $!";
  982. }
  983. # Create file indicator that the game server has been stopped if defined
  984. if(defined($Cfg::Preferences{ogp_autorestart_server}) && $Cfg::Preferences{ogp_autorestart_server} eq "1"){
  985. # Get current directory and chdir into the game's home dir
  986. my $curDir = getcwd();
  987. chdir $home_path;
  988. # Create stopped indicator file used by autorestart of OGP if server crashes
  989. open(STOPFILE, '>', "SERVER_STOPPED");
  990. close(STOPFILE);
  991. # Return to original directory
  992. chdir $curDir;
  993. }
  994. # Some validation checks for the variables.
  995. if ($server_ip =~ /^\s*$/ || $server_port < 0 || $server_port > 65535)
  996. {
  997. logger("Invalid IP:Port given $server_ip:$server_port.");
  998. return 1;
  999. }
  1000. if ($control_password !~ /^\s*$/ and $control_protocol ne "")
  1001. {
  1002. if ($control_protocol eq "rcon")
  1003. {
  1004. use KKrcon::KKrcon;
  1005. my $rcon = new KKrcon(
  1006. Password => $control_password,
  1007. Host => $server_ip,
  1008. Port => $server_port,
  1009. Type => $control_type
  1010. );
  1011. my $rconCommand = "quit";
  1012. $rcon->execute($rconCommand);
  1013. }
  1014. elsif ($control_protocol eq "rcon2")
  1015. {
  1016. use KKrcon::HL2;
  1017. my $rcon2 = new HL2(
  1018. hostname => $server_ip,
  1019. port => $server_port,
  1020. password => $control_password,
  1021. timeout => 2
  1022. );
  1023. my $rconCommand = "quit";
  1024. $rcon2->run($rconCommand);
  1025. }
  1026. if (is_screen_running_without_decrypt(SCREEN_TYPE_HOME, $home_id) == 0)
  1027. {
  1028. logger "Stopped server $server_ip:$server_port with rcon quit.";
  1029. return 0;
  1030. }
  1031. else
  1032. {
  1033. logger "Failed to send rcon quit. Stopping server with kill command.";
  1034. }
  1035. my @server_pids = get_home_pids($home_id);
  1036. my $cnt;
  1037. foreach my $pid (@server_pids)
  1038. {
  1039. chomp($pid);
  1040. $cnt = kill 15, $pid;
  1041. if ($cnt != 1)
  1042. {
  1043. $cnt = kill 9, $pid;
  1044. if ($cnt == 1)
  1045. {
  1046. logger "Stopped process with pid $pid successfully using kill 9.";
  1047. }
  1048. else
  1049. {
  1050. logger "Process $pid can not be stopped.";
  1051. }
  1052. }
  1053. else
  1054. {
  1055. logger "Stopped process with pid $pid successfully using kill 15.";
  1056. }
  1057. }
  1058. system('screen -wipe > /dev/null 2>&1');
  1059. return 0;
  1060. }
  1061. else
  1062. {
  1063. logger "Remote control protocol not available or PASSWORD NOT SET. Using kill signal instead.";
  1064. my @server_pids = get_home_pids($home_id);
  1065. my $cnt;
  1066. foreach my $pid (@server_pids)
  1067. {
  1068. chomp($pid);
  1069. $cnt = kill 15, $pid;
  1070. if ($cnt != 1)
  1071. {
  1072. $cnt = kill 9, $pid;
  1073. if ($cnt == 1)
  1074. {
  1075. logger "Stopped process with pid $pid successfully using kill 9.";
  1076. }
  1077. else
  1078. {
  1079. logger "Process $pid can not be stopped.";
  1080. }
  1081. }
  1082. else
  1083. {
  1084. logger "Stopped process with pid $pid successfully using kill 15.";
  1085. }
  1086. }
  1087. system('screen -wipe > /dev/null 2>&1');
  1088. return 0;
  1089. }
  1090. }
  1091. ##### Send RCON command
  1092. ### Return 0 when error occurred on decryption.
  1093. ### Return 1 on success
  1094. sub send_rcon_command
  1095. {
  1096. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1097. my ($home_id, $server_ip, $server_port, $control_protocol,
  1098. $control_password, $control_type, $rconCommand) = decrypt_params(@_);
  1099. # legacy console
  1100. if ($control_protocol eq "lcon")
  1101. {
  1102. my $screen_id = create_screen_id(SCREEN_TYPE_HOME, $home_id);
  1103. system('screen -S '.$screen_id.' -p 0 -X stuff "'.$rconCommand.'$(printf \\\\r)"');
  1104. logger "Sending legacy console command to ".$screen_id.": \n$rconCommand \n .";
  1105. if ($? == -1)
  1106. {
  1107. my(@modedlines) = "$rconCommand";
  1108. my $encoded_content = encode_list(@modedlines);
  1109. return "1;" . $encoded_content;
  1110. }
  1111. return 0;
  1112. }
  1113. # Some validation checks for the variables.
  1114. if ($server_ip =~ /^\s*$/ || $server_port < 0 || $server_port > 65535)
  1115. {
  1116. logger("Invalid IP:Port given $server_ip:$server_port.");
  1117. return 0;
  1118. }
  1119. if ($control_password !~ /^\s*$/)
  1120. {
  1121. if ($control_protocol eq "rcon")
  1122. {
  1123. use KKrcon::KKrcon;
  1124. my $rcon = new KKrcon(
  1125. Password => $control_password,
  1126. Host => $server_ip,
  1127. Port => $server_port,
  1128. Type => $control_type
  1129. );
  1130. logger "Sending RCON command to $server_ip:$server_port: \n$rconCommand \n .";
  1131. my(@modedlines) = $rcon->execute($rconCommand);
  1132. my $encoded_content = encode_list(@modedlines);
  1133. return "1;" . $encoded_content;
  1134. }
  1135. else
  1136. {
  1137. if ($control_protocol eq "rcon2")
  1138. {
  1139. use KKrcon::HL2;
  1140. my $rcon2 = new HL2(
  1141. hostname => $server_ip,
  1142. port => $server_port,
  1143. password => $control_password,
  1144. timeout => 2
  1145. );
  1146. logger "Sending RCON command to $server_ip:$server_port: \n $rconCommand \n .";
  1147. my(@modedlines) = $rcon2->run($rconCommand);
  1148. my $encoded_content = encode_list(@modedlines);
  1149. return "1;" . $encoded_content;
  1150. }
  1151. }
  1152. }
  1153. else
  1154. {
  1155. logger "Control protocol PASSWORD NOT SET.";
  1156. return -10;
  1157. }
  1158. }
  1159. ##### Returns a directory listing
  1160. ### @return List of directories if everything OK.
  1161. ### @return 0 If the directory is not found.
  1162. ### @return -1 If cannot open the directory.
  1163. sub dirlist
  1164. {
  1165. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1166. my ($datadir) = &decrypt_param(@_);
  1167. logger "Asked for dirlist of $datadir directory.";
  1168. if (!-d $datadir)
  1169. {
  1170. logger "ERROR - Directory [ $datadir ] not found!";
  1171. return -1;
  1172. }
  1173. if (!opendir(DIR, $datadir))
  1174. {
  1175. logger "ERROR - Can't open $datadir: $!";
  1176. return -2;
  1177. }
  1178. my @dirlist = readdir(DIR);
  1179. closedir(DIR);
  1180. return join(";", @dirlist);
  1181. }
  1182. ##### Returns a directory listing with extra info the filemanager
  1183. ### @return List of directories if everything OK.
  1184. ### @return 1 If the directory is empty.
  1185. ### @return -1 If the directory is not found.
  1186. ### @return -2 If cannot open the directory.
  1187. sub dirlistfm
  1188. {
  1189. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1190. my $datadir = &decrypt_param(@_);
  1191. logger "Asked for dirlist of $datadir directory.";
  1192. if (!-d $datadir)
  1193. {
  1194. logger "ERROR - Directory [ $datadir ] not found!";
  1195. return -1;
  1196. }
  1197. if (!opendir(DIR, $datadir))
  1198. {
  1199. logger "ERROR - Can't open $datadir: $!";
  1200. return -2;
  1201. }
  1202. my $dir = $datadir;
  1203. $dir =~ s/('+)/'"$1"'/g;
  1204. my $lsattr = `lsattr '$dir' 2>/dev/null`;
  1205. my @attr_all = split /\n+/, $lsattr;
  1206. my %attr = ();
  1207. my ($a, $p, @f);
  1208. foreach (@attr_all)
  1209. {
  1210. ($a, $p) = split(/\s/, $_, 2);
  1211. @f = split /\//, $p;
  1212. $attr{$f[-1]} = $a;
  1213. }
  1214. my %dirfiles = ();
  1215. my (
  1216. $dev, $ino, $mode, $nlink, $uid, $gid, $rdev,
  1217. $size, $atime, $mtime, $ctime, $blksize, $blocks
  1218. );
  1219. my $count = 0;
  1220. chdir($datadir);
  1221. while (my $item = readdir(DIR))
  1222. {
  1223. #skip the . and .. special dirs
  1224. next if $item eq '.';
  1225. next if $item eq '..';
  1226. #print "Dir list is" . $item."\n";
  1227. #Stat the file to get ownership and size
  1228. (
  1229. $dev, $ino, $mode, $nlink, $uid, $gid, $rdev,
  1230. $size, $atime, $mtime, $ctime, $blksize, $blocks
  1231. ) = stat($item);
  1232. $uid = getpwuid($uid);
  1233. $gid = getgrgid($gid);
  1234. #This if else logic determines what it is, File, Directory, other
  1235. if (-T $item)
  1236. {
  1237. # print "File\n";
  1238. $dirfiles{'files'}{$count}{'filename'} = encode_base64($item);
  1239. $dirfiles{'files'}{$count}{'size'} = $size;
  1240. $dirfiles{'files'}{$count}{'user'} = $uid;
  1241. $dirfiles{'files'}{$count}{'group'} = $gid;
  1242. $dirfiles{'files'}{$count}{'attr'} = $attr{$item};
  1243. }
  1244. elsif (-d $item)
  1245. {
  1246. # print "Dir\n";
  1247. $dirfiles{'directorys'}{$count}{'filename'} = encode_base64($item);
  1248. $dirfiles{'directorys'}{$count}{'size'} = $size;
  1249. $dirfiles{'directorys'}{$count}{'user'} = $uid;
  1250. $dirfiles{'directorys'}{$count}{'group'} = $gid;
  1251. }
  1252. elsif (-B $item)
  1253. {
  1254. #print "File\n";
  1255. $dirfiles{'binarys'}{$count}{'filename'} = encode_base64($item);
  1256. $dirfiles{'binarys'}{$count}{'size'} = $size;
  1257. $dirfiles{'binarys'}{$count}{'user'} = $uid;
  1258. $dirfiles{'binarys'}{$count}{'group'} = $gid;
  1259. $dirfiles{'binarys'}{$count}{'attr'} = $attr{$item};
  1260. }
  1261. else
  1262. {
  1263. #print "Unknown\n"
  1264. #will be listed as common files;
  1265. $dirfiles{'files'}{$count}{'filename'} = encode_base64($item);
  1266. $dirfiles{'files'}{$count}{'size'} = $size;
  1267. $dirfiles{'files'}{$count}{'user'} = $uid;
  1268. $dirfiles{'files'}{$count}{'group'} = $gid;
  1269. $dirfiles{'files'}{$count}{'attr'} = $attr{$item};
  1270. }
  1271. $count++;
  1272. }
  1273. closedir(DIR);
  1274. if ($count eq 0)
  1275. {
  1276. logger "Empty directory $datadir.";
  1277. return 1;
  1278. }
  1279. chdir AGENT_RUN_DIR;
  1280. #Now we return it to the webpage, as array
  1281. return {%dirfiles};
  1282. }
  1283. ###### Returns the contents of a text file
  1284. sub readfile
  1285. {
  1286. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1287. chdir AGENT_RUN_DIR;
  1288. my $userfile = &decrypt_param(@_);
  1289. unless ( -e $userfile )
  1290. {
  1291. if (open(BLANK, '>', $userfile))
  1292. {
  1293. close(BLANK);
  1294. }
  1295. }
  1296. if (!open(USERFILE, '<', $userfile))
  1297. {
  1298. logger "ERROR - Can't open file $userfile for reading.";
  1299. return -1;
  1300. }
  1301. my ($wholefile, $buf);
  1302. while (read(USERFILE, $buf, 60 * 57))
  1303. {
  1304. $wholefile .= encode_base64($buf);
  1305. }
  1306. close(USERFILE);
  1307. if(!defined $wholefile)
  1308. {
  1309. return "1; ";
  1310. }
  1311. return "1;" . $wholefile;
  1312. }
  1313. ###### Backs up file, then writes data to new file
  1314. ### @return 1 On success
  1315. ### @return 0 In case of a failure
  1316. sub writefile
  1317. {
  1318. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1319. chdir AGENT_RUN_DIR;
  1320. # $writefile = file we're editing, $filedata = the contents were writing to it
  1321. my ($writefile, $filedata) = &decrypt_params(@_);
  1322. if (!-e $writefile)
  1323. {
  1324. open FILE, ">", $writefile;
  1325. }
  1326. else
  1327. {
  1328. # backup the existing file
  1329. logger
  1330. "Backing up file $writefile to $writefile.bak before writing new data.";
  1331. if (!copy("$writefile", "$writefile.bak"))
  1332. {
  1333. logger
  1334. "ERROR - Failed to backup $writefile to $writefile.bak. Error: $!";
  1335. return 0;
  1336. }
  1337. }
  1338. if (!-w $writefile)
  1339. {
  1340. logger "ERROR - File [ $writefile ] is not writeable!";
  1341. return 0;
  1342. }
  1343. if (!open(WRITER, '>', $writefile))
  1344. {
  1345. logger "ERROR - Failed to open $writefile for writing.";
  1346. return 0;
  1347. }
  1348. $filedata = decode_base64($filedata);
  1349. $filedata =~ s/\r//g;
  1350. print WRITER "$filedata";
  1351. close(WRITER);
  1352. logger "Wrote $writefile successfully!";
  1353. return 1;
  1354. }
  1355. ###### Reboots the server remotely through panel
  1356. ### @return 1 On success
  1357. ### @return 0 In case of a failure
  1358. sub rebootnow
  1359. {
  1360. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1361. sudo_exec_without_decrypt('sleep 10s; shutdown -r now');
  1362. logger "Scheduled system reboot to occur in 10 seconds successfully!";
  1363. return 1;
  1364. }
  1365. # Determine the os of the agent machine.
  1366. sub what_os
  1367. {
  1368. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1369. logger "Asking for OS type";
  1370. my $which_uname = `which uname`;
  1371. chomp $which_uname;
  1372. if ($which_uname ne "")
  1373. {
  1374. my $os;
  1375. my $os_name;
  1376. my $os_arch;
  1377. my $wine_ver = "";
  1378. $os_name = `$which_uname`;
  1379. chomp $os_name;
  1380. $os_arch = `$which_uname -m`;
  1381. chomp $os_arch;
  1382. my $which_wine = `which wine`;
  1383. chomp $which_wine;
  1384. if ($which_wine ne "")
  1385. {
  1386. $wine_ver = `$which_wine --version`;
  1387. chomp $wine_ver;
  1388. $wine_ver = "|".$wine_ver;
  1389. }
  1390. $os = $os_name." ".$os_arch.$wine_ver;
  1391. logger "OS is $os";
  1392. return "$os";
  1393. }
  1394. else
  1395. {
  1396. logger "Cannot determine OS..that is odd";
  1397. return "Unknown";
  1398. }
  1399. }
  1400. ### @return PID of the download process if started succesfully.
  1401. ### @return -1 If could not create temporary download directory.
  1402. ### @return -2 If could not create destination directory.
  1403. ### @return -3 If resources unavailable.
  1404. sub start_file_download
  1405. {
  1406. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1407. my ($url, $destination, $filename, $action, $post_script) = &decrypt_params(@_);
  1408. logger
  1409. "Starting to download URL $url. Destination: $destination - Filename: $filename";
  1410. if (!-e $destination)
  1411. {
  1412. logger "Creating destination directory.";
  1413. if (!mkpath $destination )
  1414. {
  1415. logger "Could not create destination '$destination' directory : $!";
  1416. return -2;
  1417. }
  1418. }
  1419. my $download_file_path = Path::Class::File->new($destination, "$filename");
  1420. my $pid = fork();
  1421. if (not defined $pid)
  1422. {
  1423. logger "Could not allocate resources for download.";
  1424. return -3;
  1425. }
  1426. # Only the forked child goes here.
  1427. elsif ($pid == 0)
  1428. {
  1429. my $ua = LWP::UserAgent->new( ssl_opts => { verify_hostname => 0,
  1430. SSL_verify_mode => 0x00 } );
  1431. $ua->agent('Mozilla/5.0');
  1432. my $response = $ua->get($url, ':content_file' => "$download_file_path");
  1433. if ($response->is_success)
  1434. {
  1435. logger "Successfully fetched $url and stored it to $download_file_path. Retval: ".$response->status_line;
  1436. if (!-e $download_file_path)
  1437. {
  1438. logger "File $download_file_path does not exist.";
  1439. exit(0);
  1440. }
  1441. if ($action eq "uncompress")
  1442. {
  1443. logger "Starting file uncompress as ordered.";
  1444. uncompress_file_without_decrypt($download_file_path,
  1445. $destination);
  1446. }
  1447. }
  1448. else
  1449. {
  1450. logger
  1451. "Unable to fetch $url, or save to $download_file_path. Retval: ".$response->status_line;
  1452. exit(0);
  1453. }
  1454. # Child process must exit.
  1455. exit(0);
  1456. }
  1457. else
  1458. {
  1459. if ($post_script ne "")
  1460. {
  1461. logger "Running postscript commands.";
  1462. my @postcmdlines = split /[\r\n]+/, $post_script;
  1463. my $postcmdfile = $destination."/".'postinstall.sh';
  1464. open FILE, '>', $postcmdfile;
  1465. print FILE "cd $destination\n";
  1466. print FILE "while kill -0 $pid >/dev/null 2>&1\n";
  1467. print FILE "do\n";
  1468. print FILE " sleep 1\n";
  1469. print FILE "done\n";
  1470. foreach my $line (@postcmdlines) {
  1471. print FILE "$line\n";
  1472. }
  1473. print FILE "rm -f $destination/postinstall.sh\n";
  1474. close FILE;
  1475. chmod 0755, $postcmdfile;
  1476. my $screen_id = create_screen_id("post_script", $pid);
  1477. my $cli_bin = create_screen_cmd($screen_id, "bash $postcmdfile");
  1478. system($cli_bin);
  1479. }
  1480. logger "Download process for $download_file_path has pid number $pid.";
  1481. return "$pid";
  1482. }
  1483. }
  1484. sub lock_additional_files{
  1485. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1486. my ($homedir, $files, $action) = &decrypt_params(@_);
  1487. return lock_additional_files_logic($homedir, $files, $action);
  1488. }
  1489. sub lock_additional_files_logic{
  1490. my ($homedir, $filesToLock, $action, $returnType) = @_;
  1491. logger "Locking additional files specified in the XML.";
  1492. my $commandStr = "";
  1493. $filesToLock = startup_comma_format_to_multiline($filesToLock);
  1494. $filesToLock = replace_OGP_Env_Vars("", $homedir, $filesToLock);
  1495. my @filesToProcess = split /[\r\n]+/, $filesToLock;
  1496. foreach my $line (@filesToProcess) {
  1497. my $fullPath = $homedir . "/" . $line;
  1498. if($action eq "lock"){
  1499. if(defined $returnType && $returnType eq "str"){
  1500. $commandStr .= "echo '".$SUDOPASSWD."' | sudo -S -p \"\" sh -c \"" . secure_path_without_decrypt("chattr+i", $fullPath, $returnType) . "\" > /dev/null 2>&1" . "\n";
  1501. $commandStr .= "echo '".$SUDOPASSWD."' | sudo -S -p \"\" sh -c \"" . secure_path_without_decrypt("chattr+i", $line, $returnType) . "\" > /dev/null 2>&1" . "\n";
  1502. }else{
  1503. secure_path_without_decrypt("chattr+i", $fullPath);
  1504. secure_path_without_decrypt("chattr+i", $line);
  1505. }
  1506. }else{
  1507. if(defined $returnType && $returnType eq "str"){
  1508. $commandStr .= "echo '".$SUDOPASSWD."' | sudo -S -p \"\" sh -c \"" . secure_path_without_decrypt("chattr-i", $fullPath, $returnType) . "\" > /dev/null 2>&1" . "\n";
  1509. $commandStr .= "echo '".$SUDOPASSWD."' | sudo -S -p \"\" sh -c \"" . secure_path_without_decrypt("chattr-i", $line, $returnType) . "\" > /dev/null 2>&1" . "\n";
  1510. }else{
  1511. secure_path_without_decrypt("chattr-i", $fullPath);
  1512. secure_path_without_decrypt("chattr-i", $line);
  1513. }
  1514. }
  1515. }
  1516. if($commandStr ne ""){
  1517. return $commandStr;
  1518. }
  1519. return "";
  1520. }
  1521. sub run_before_start_commands
  1522. {
  1523. #return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1524. my ($server_id, $homedir, $beforestartcmd, $envVars) = @_;
  1525. if ($homedir ne "" && $server_id ne ""){
  1526. # Run any prestart scripts
  1527. if (defined $beforestartcmd && $beforestartcmd ne "")
  1528. {
  1529. logger "Running pre-start XML commands before starting server ID $server_id with a home directory of $homedir.";
  1530. my @prestartcmdlines = split /[\r\n]+/, $beforestartcmd;
  1531. my $prestartcmdfile = $homedir."/".'prestart_ogp.sh';
  1532. open FILE, '>', $prestartcmdfile;
  1533. print FILE "#!/bin/bash" . "\n";
  1534. print FILE "cd $homedir\n";
  1535. foreach my $line (@prestartcmdlines) {
  1536. print FILE "$line\n";
  1537. }
  1538. print FILE "rm -f $prestartcmdfile\n";
  1539. close FILE;
  1540. chmod 0755, $prestartcmdfile;
  1541. system("bash $prestartcmdfile");
  1542. }
  1543. # Set and export any environment variables for game server developers unwilling to properly learn Linux
  1544. if (defined $envVars && $envVars ne ""){
  1545. my @prestartenvvars = split /[\r\n]+/, $envVars;
  1546. foreach my $line (@prestartenvvars) {
  1547. $line = replace_OGP_Env_Vars($server_id, $homedir, $line);
  1548. if($line ne ""){
  1549. logger "Configuring environment variable: $line";
  1550. system($line);
  1551. }
  1552. }
  1553. }
  1554. }else{
  1555. return -2;
  1556. }
  1557. return 1;
  1558. }
  1559. sub multiline_to_startup_comma_format{
  1560. my ($multiLineVar) = @_;
  1561. $multiLineVar =~ s/,//g; # commas are invalid anyways in bash
  1562. $multiLineVar =~ s/[\r]+//g;
  1563. $multiLineVar =~ s/[\n]+/{OGPNEWLINE}/g;
  1564. return $multiLineVar;
  1565. }
  1566. sub startup_comma_format_to_multiline{
  1567. my ($multiLineVar) = @_;
  1568. $multiLineVar =~ s/{OGPNEWLINE}/\n/g;
  1569. return $multiLineVar;
  1570. }
  1571. sub create_secure_script
  1572. {
  1573. my ($home_path, $exec_folder_path, $exec_path) = @_;
  1574. secure_path_without_decrypt('chattr-i', $home_path);
  1575. my $secure = "$home_path/secure.sh";
  1576. $home_path =~ s/('+)/'\"$1\"'/g;
  1577. $exec_folder_path =~ s/('+)/'\"$1\"'/g;
  1578. $exec_path =~ s/('+)/'\"$1\"'/g;
  1579. my $sec = $secure;
  1580. $sec =~ s/('+)/'\"$1\"'/g;
  1581. open FILE, '>', $secure;
  1582. print FILE "chmod 771 '$exec_folder_path'\n".
  1583. "chmod 750 '$exec_path'\n".
  1584. "chmod +x '$exec_path'\n".
  1585. "chattr +i '$exec_path'\n".
  1586. "rm -f '$sec'";
  1587. close FILE;
  1588. chmod 0770, $secure;
  1589. sudo_exec_without_decrypt("chown 0:0 '$sec'");
  1590. return 0;
  1591. }
  1592. sub check_b4_chdir
  1593. {
  1594. my ( $path ) = @_;
  1595. my $uid = `id -u`;
  1596. chomp $uid;
  1597. my $gid = `id -g`;
  1598. chomp $gid;
  1599. if (!-e $path)
  1600. {
  1601. logger "$path does not exist yet. Trying to create it...";
  1602. if (!mkpath($path))
  1603. {
  1604. logger "Error creating $path . Errno: $!";
  1605. return -1;
  1606. }
  1607. # Set perms on it as well
  1608. sudo_exec_without_decrypt('chown -Rf '.$uid.':'.$gid.' \''.$path.'\'');
  1609. }
  1610. else
  1611. {
  1612. # File or directory already exists
  1613. # Make sure it's owned by the agent
  1614. secure_path_without_decrypt('chattr-i', $path);
  1615. }
  1616. if (!chdir $path)
  1617. {
  1618. logger "Unable to change dir to '$path'.";
  1619. return -1;
  1620. }
  1621. return 0;
  1622. }
  1623. sub create_bash_scripts
  1624. {
  1625. my ( $home_path, $bash_scripts_path, $precmd, $postcmd, @installcmds ) = @_;
  1626. $home_path =~ s/('+)/'\"$1\"'/g;
  1627. $bash_scripts_path =~ s/('+)/'\"$1\"'/g;
  1628. my @precmdlines = split /[\r\n]+/, $precmd;
  1629. my $precmdfile = 'preinstall.sh';
  1630. open FILE, '>', $precmdfile;
  1631. print FILE "cd '$home_path'\n";
  1632. foreach my $line (@precmdlines) {
  1633. print FILE "$line\n";
  1634. }
  1635. close FILE;
  1636. chmod 0755, $precmdfile;
  1637. my @postcmdlines = split /[\r\n]+/, $postcmd;
  1638. my $postcmdfile = 'postinstall.sh';
  1639. open FILE, '>', $postcmdfile;
  1640. print FILE "cd '$home_path'\n";
  1641. foreach my $line (@postcmdlines) {
  1642. print FILE "$line\n";
  1643. }
  1644. print FILE "cd '$home_path'\n".
  1645. "echo '".$SUDOPASSWD."' | sudo -S -p \"\" bash secure.sh\n".
  1646. "rm -f secure.sh\n".
  1647. "cd '$bash_scripts_path'\n".
  1648. "rm -f preinstall.sh\n".
  1649. "rm -f postinstall.sh\n".
  1650. "rm -f runinstall.sh\n";
  1651. close FILE;
  1652. chmod 0755, $postcmdfile;
  1653. my $installfile = 'runinstall.sh';
  1654. open FILE, '>', $installfile;
  1655. print FILE "#!/bin/bash\n".
  1656. "cd '$bash_scripts_path'\n".
  1657. "./$precmdfile\n";
  1658. foreach my $installcmd (@installcmds)
  1659. {
  1660. print FILE "$installcmd\n";
  1661. }
  1662. print FILE "wait ".'${!}'."\n".
  1663. "cd '$bash_scripts_path'\n".
  1664. "./$postcmdfile\n";
  1665. close FILE;
  1666. chmod 0755, $installfile;
  1667. return $installfile;
  1668. }
  1669. #### Run the rsync update ####
  1670. ### @return 1 If update started
  1671. ### @return 0 In error case.
  1672. sub start_rsync_install
  1673. {
  1674. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1675. my ($home_id, $home_path, $url, $exec_folder_path, $exec_path, $precmd, $postcmd, $filesToLockUnlock) = decrypt_params(@_);
  1676. if ( check_b4_chdir($home_path) != 0)
  1677. {
  1678. return 0;
  1679. }
  1680. secure_path_without_decrypt('chattr-i', $home_path);
  1681. create_secure_script($home_path, $exec_folder_path, $exec_path);
  1682. my $bash_scripts_path = MANUAL_TMP_DIR . "/home_id_" . $home_id;
  1683. if ( check_b4_chdir($bash_scripts_path) != 0)
  1684. {
  1685. return 0;
  1686. }
  1687. # Rsync install require the rsync binary to exist in the system
  1688. # to enable this functionality.
  1689. my $rsync_binary = Path::Class::File->new("/usr/bin", "rsync");
  1690. if (!-f $rsync_binary)
  1691. {
  1692. logger "Failed to start rsync update from "
  1693. . $url
  1694. . " to $home_path. Error: Rsync client not installed.";
  1695. return 0;
  1696. }
  1697. my $screen_id = create_screen_id(SCREEN_TYPE_UPDATE, $home_id);
  1698. my $log_file = Path::Class::File->new(SCREEN_LOGS_DIR, "screenlog.$screen_id");
  1699. if(defined $filesToLockUnlock && $filesToLockUnlock ne ""){
  1700. $postcmd .= "\n" . lock_additional_files_logic($home_path, $filesToLockUnlock, "lock", "str");
  1701. }
  1702. backup_home_log( $home_id, $log_file );
  1703. my $path = $home_path;
  1704. $path =~ s/('+)/'\"$1\"'/g;
  1705. my @installcmds = ("/usr/bin/rsync --archive --compress --copy-links --update --verbose rsync://$url '$path'");
  1706. my $installfile = create_bash_scripts( $home_path, $bash_scripts_path, $precmd, $postcmd, @installcmds );
  1707. my $screen_cmd = create_screen_cmd($screen_id, "./$installfile");
  1708. logger "Running rsync update: /usr/bin/rsync --archive --compress --copy-links --update --verbose rsync://$url '$home_path'";
  1709. system($screen_cmd);
  1710. chdir AGENT_RUN_DIR;
  1711. return 1;
  1712. }
  1713. ### @return PID of the download process if started succesfully.
  1714. ### @return -1 If could not create temporary download directory.
  1715. ### @return -2 If could not create destination directory.
  1716. ### @return -3 If resources unavailable.
  1717. sub master_server_update
  1718. {
  1719. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1720. my ($home_id,$home_path,$ms_home_id,$ms_home_path,$exec_folder_path,$exec_path,$precmd,$postcmd) = decrypt_params(@_);
  1721. if ( check_b4_chdir($home_path) != 0)
  1722. {
  1723. return 0;
  1724. }
  1725. secure_path_without_decrypt('chattr-i', $home_path);
  1726. create_secure_script($home_path, $exec_folder_path, $exec_path);
  1727. my $bash_scripts_path = MANUAL_TMP_DIR . "/home_id_" . $home_id;
  1728. if ( check_b4_chdir($bash_scripts_path) != 0)
  1729. {
  1730. return 0;
  1731. }
  1732. my $screen_id = create_screen_id(SCREEN_TYPE_UPDATE, $home_id);
  1733. my $log_file = Path::Class::File->new(SCREEN_LOGS_DIR, "screenlog.$screen_id");
  1734. backup_home_log( $home_id, $log_file );
  1735. my $my_home_path = $home_path;
  1736. $my_home_path =~ s/('+)/'\"$1\"'/g;
  1737. $exec_path =~ s/\Q$home_path\E//g;
  1738. $exec_path =~ s/^\///g;
  1739. $exec_path =~ s/('+)/'\"$1\"'/g;
  1740. $ms_home_path =~ s/('+)/'\"$1\"'/g;
  1741. my @installcmds = ("cd '$ms_home_path'");
  1742. ## Copy files that match the extensions listed at extPatterns.txt
  1743. open(EXT_PATTERNS, '<', Path::Class::File->new(AGENT_RUN_DIR, "extPatterns.txt"))
  1744. || logger "Error reading patterns file $!";
  1745. my @ext_paterns = <EXT_PATTERNS>;
  1746. foreach my $patern (@ext_paterns)
  1747. {
  1748. chop $patern;
  1749. push (@installcmds, "find -iname \\\*.$patern -exec cp -Rfp --parents {} '$my_home_path'/ \\\;");
  1750. }
  1751. close EXT_PATTERNS;
  1752. ## Copy the server executable so it can be secured with chattr +i
  1753. push (@installcmds, "cp -vf --parents '$exec_path' '$my_home_path'");
  1754. ## Do symlinks for each of the other files
  1755. push (@installcmds, "cp -vuRfs '$ms_home_path'/* '$my_home_path'");
  1756. my $installfile = create_bash_scripts( $home_path, $bash_scripts_path, $precmd, $postcmd, @installcmds );
  1757. my $screen_cmd = create_screen_cmd($screen_id, "./$installfile");
  1758. logger "Running master server update from home ID $home_id to home ID $ms_home_id";
  1759. system($screen_cmd);
  1760. chdir AGENT_RUN_DIR;
  1761. return 1;
  1762. }
  1763. #### Run the steam client ####
  1764. ### @return 1 If update started
  1765. ### @return 0 In error case.
  1766. sub steam_cmd
  1767. {
  1768. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1769. my ($home_id, $home_path, $mod, $modname, $betaname, $betapwd, $user, $pass, $guard, $exec_folder_path, $exec_path, $precmd, $postcmd, $cfg_os, $filesToLockUnlock) = decrypt_params(@_);
  1770. if ( check_b4_chdir($home_path) != 0)
  1771. {
  1772. return 0;
  1773. }
  1774. secure_path_without_decrypt('chattr-i', $home_path);
  1775. create_secure_script($home_path, $exec_folder_path, $exec_path);
  1776. my $bash_scripts_path = MANUAL_TMP_DIR . "/home_id_" . $home_id;
  1777. if ( check_b4_chdir($bash_scripts_path) != 0)
  1778. {
  1779. return 0;
  1780. }
  1781. my $screen_id = create_screen_id(SCREEN_TYPE_UPDATE, $home_id);
  1782. my $screen_id_for_txt_update = substr ($screen_id, rindex($screen_id, '_') + 1);
  1783. my $steam_binary = Path::Class::File->new(STEAMCMD_CLIENT_DIR, "steamcmd.sh");
  1784. my $installSteamFile = $screen_id_for_txt_update . "_install.txt";
  1785. my $installtxt = Path::Class::File->new(STEAMCMD_CLIENT_DIR, $installSteamFile);
  1786. open FILE, '>', $installtxt;
  1787. print FILE "\@ShutdownOnFailedCommand 1\n";
  1788. print FILE "\@NoPromptForPassword 1\n";
  1789. if($cfg_os eq 'windows')
  1790. {
  1791. print FILE "\@sSteamCmdForcePlatformType windows\n";
  1792. }
  1793. if($guard ne '')
  1794. {
  1795. print FILE "set_steam_guard_code $guard\n";
  1796. }
  1797. if($user ne '' && $user ne 'anonymous')
  1798. {
  1799. print FILE "login $user $pass\n";
  1800. }
  1801. else
  1802. {
  1803. print FILE "login anonymous\n";
  1804. }
  1805. print FILE "force_install_dir \"$home_path\"\n";
  1806. if($modname ne "")
  1807. {
  1808. print FILE "app_set_config $mod mod $modname\n";
  1809. print FILE "app_update $mod mod $modname validate\n";
  1810. }
  1811. if($betaname ne "" && $betapwd ne "")
  1812. {
  1813. print FILE "app_update $mod -beta $betaname -betapassword $betapwd\n";
  1814. }
  1815. elsif($betaname ne "" && $betapwd eq "")
  1816. {
  1817. print FILE "app_update $mod -beta $betaname\n";
  1818. }
  1819. else
  1820. {
  1821. print FILE "app_update $mod\n";
  1822. }
  1823. print FILE "exit\n";
  1824. close FILE;
  1825. my $log_file = Path::Class::File->new(SCREEN_LOGS_DIR, "screenlog.$screen_id");
  1826. backup_home_log( $home_id, $log_file );
  1827. my $postcmd_mod = $postcmd;
  1828. if(defined $filesToLockUnlock && $filesToLockUnlock ne ""){
  1829. $postcmd_mod .= "\n" . lock_additional_files_logic($home_path, $filesToLockUnlock, "lock", "str");
  1830. }
  1831. my @installcmds = ("$steam_binary +runscript $installtxt +exit");
  1832. my $installfile = create_bash_scripts( $home_path, $bash_scripts_path, $precmd, $postcmd_mod, @installcmds );
  1833. my $screen_cmd = create_screen_cmd($screen_id, "./$installfile");
  1834. logger "Running steam update: $steam_binary +runscript $installtxt +exit";
  1835. system($screen_cmd);
  1836. return 1;
  1837. }
  1838. sub rsync_progress
  1839. {
  1840. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1841. my ($running_home) = &decrypt_param(@_);
  1842. logger "User requested progress on rsync job on home $running_home.";
  1843. if (-r $running_home)
  1844. {
  1845. $running_home =~ s/('+)/'"$1"'/g;
  1846. my $progress = `du -sk '$running_home'`;
  1847. chomp($progress);
  1848. my ($bytes, $junk) = split(/\s+/, $progress);
  1849. logger("Found $bytes and $junk");
  1850. return $bytes;
  1851. }
  1852. return "0";
  1853. }
  1854. sub is_file_download_in_progress
  1855. {
  1856. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1857. my ($pid) = &decrypt_param(@_);
  1858. logger "User requested if download is in progress with pid $pid.";
  1859. my @pids = `ps -ef`;
  1860. @pids = grep(/$pid/, @pids);
  1861. logger "Number of pids for file download: @pids";
  1862. if (@pids > '0')
  1863. {
  1864. return 1;
  1865. }
  1866. return 0;
  1867. }
  1868. ### \return 1 If file is uncompressed succesfully.
  1869. ### \return 0 If file does not exist.
  1870. ### \return -1 If file could not be uncompressed.
  1871. sub uncompress_file
  1872. {
  1873. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1874. return uncompress_file_without_decrypt(decrypt_params(@_));
  1875. }
  1876. sub uncompress_file_without_decrypt
  1877. {
  1878. # File must include full path.
  1879. my ($file, $destination) = @_;
  1880. logger "Uncompression called for file $file to dir $destination.";
  1881. if (!-e $file)
  1882. {
  1883. logger "File $file could not be found for uncompression.";
  1884. return 0;
  1885. }
  1886. if (!-e $destination)
  1887. {
  1888. mkpath($destination, {error => \my $err});
  1889. if (@$err)
  1890. {
  1891. logger "Failed to create destination dir $destination.";
  1892. return 0;
  1893. }
  1894. }
  1895. my $ae = Archive::Extract->new(archive => $file);
  1896. if (!$ae)
  1897. {
  1898. logger "Could not create archive instance for file $file.";
  1899. return -1;
  1900. }
  1901. my $ok = $ae->extract(to => $destination);
  1902. if (!$ok)
  1903. {
  1904. logger "File $file could not be uncompressed.";
  1905. return -1;
  1906. }
  1907. logger "File uncompressed/extracted successfully.";
  1908. return 1;
  1909. }
  1910. ### \return 1 If files are compressed succesfully.
  1911. ### \return -1 If files could not be compressed.
  1912. sub compress_files
  1913. {
  1914. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1915. return compress_files_without_decrypt(decrypt_params(@_));
  1916. }
  1917. sub compress_files_without_decrypt
  1918. {
  1919. my ($files,$destination,$archive_name,$archive_type) = @_;
  1920. if (!-e $destination)
  1921. {
  1922. logger "compress_files: Destination path ( $destination ) could not be found.";
  1923. return -1;
  1924. }
  1925. chdir $destination;
  1926. my @items = split /\Q\n/, $files;
  1927. my @inventory;
  1928. if($archive_type eq "zip")
  1929. {
  1930. logger $archive_type." compression called, destination archive is: $destination$archive_name.$archive_type";
  1931. my $zip = Archive::Zip->new();
  1932. foreach my $item (@items) {
  1933. if(-e $item)
  1934. {
  1935. if (-f $item)
  1936. {
  1937. $zip->addFile( $item );
  1938. }
  1939. elsif (-d $item)
  1940. {
  1941. $zip->addTree( $item, $item );
  1942. }
  1943. }
  1944. }
  1945. # Save the file
  1946. unless ( $zip->writeToFileNamed($archive_name.'.zip') == AZ_OK ) {
  1947. logger "Write Error at $destination/$archive_name.$archive_type";
  1948. return -1
  1949. }
  1950. logger $archive_type." archive $destination$archive_name.$archive_type created successfully";
  1951. return 1;
  1952. }
  1953. elsif($archive_type eq "tbz")
  1954. {
  1955. logger $archive_type." compression called, destination archive is: $destination$archive_name.$archive_type";
  1956. my $tar = Archive::Tar->new;
  1957. foreach my $item (@items) {
  1958. if(-e $item)
  1959. {
  1960. if (-f $item)
  1961. {
  1962. $tar->add_files( $item );
  1963. }
  1964. elsif (-d $item)
  1965. {
  1966. @inventory = ();
  1967. find (sub { push @inventory, $File::Find::name }, $item);
  1968. $tar->add_files( @inventory );
  1969. }
  1970. }
  1971. }
  1972. # Save the file
  1973. unless ( $tar->write("$archive_name.$archive_type", COMPRESS_BZIP) ) {
  1974. logger "Write Error at $destination/$archive_name.$archive_type";
  1975. return -1
  1976. }
  1977. logger $archive_type." archive $destination$archive_name.$archive_type created successfully";
  1978. return 1;
  1979. }
  1980. elsif($archive_type eq "tgz")
  1981. {
  1982. logger $archive_type." compression called, destination archive is: $destination$archive_name.$archive_type";
  1983. my $tar = Archive::Tar->new;
  1984. foreach my $item (@items) {
  1985. if(-e $item)
  1986. {
  1987. if (-f $item)
  1988. {
  1989. $tar->add_files( $item );
  1990. }
  1991. elsif (-d $item)
  1992. {
  1993. @inventory = ();
  1994. find (sub { push @inventory, $File::Find::name }, $item);
  1995. $tar->add_files( @inventory );
  1996. }
  1997. }
  1998. }
  1999. # Save the file
  2000. unless ( $tar->write("$archive_name.$archive_type", COMPRESS_GZIP) ) {
  2001. logger "Write Error at $destination/$archive_name.$archive_type";
  2002. return -1
  2003. }
  2004. logger $archive_type." archive $destination$archive_name.$archive_type created successfully";
  2005. return 1;
  2006. }
  2007. elsif($archive_type eq "tar")
  2008. {
  2009. logger $archive_type." compression called, destination archive is: $destination$archive_name.$archive_type";
  2010. my $tar = Archive::Tar->new;
  2011. foreach my $item (@items) {
  2012. if(-e $item)
  2013. {
  2014. if (-f $item)
  2015. {
  2016. $tar->add_files( $item );
  2017. }
  2018. elsif (-d $item)
  2019. {
  2020. @inventory = ();
  2021. find (sub { push @inventory, $File::Find::name }, $item);
  2022. $tar->add_files( @inventory );
  2023. }
  2024. }
  2025. }
  2026. # Save the file
  2027. unless ( $tar->write("$archive_name.$archive_type") ) {
  2028. logger "Write Error at $destination/$archive_name.$archive_type";
  2029. return -1
  2030. }
  2031. logger $archive_type." archive $destination$archive_name.$archive_type created successfully";
  2032. return 1;
  2033. }
  2034. elsif($archive_type eq "bz2")
  2035. {
  2036. logger $archive_type." compression called.";
  2037. foreach my $item (@items) {
  2038. if(-e $item)
  2039. {
  2040. if (-f $item)
  2041. {
  2042. bzip2 $item => "$item.bz2";
  2043. }
  2044. elsif (-d $item)
  2045. {
  2046. @inventory = ();
  2047. find (sub { push @inventory, $File::Find::name }, $item);
  2048. foreach my $relative_item (@inventory) {
  2049. bzip2 $relative_item => "$relative_item.bz2";
  2050. }
  2051. }
  2052. }
  2053. }
  2054. logger $archive_type." archives created successfully at $destination";
  2055. return 1;
  2056. }
  2057. }
  2058. sub discover_ips
  2059. {
  2060. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2061. my ($check) = decrypt_params(@_);
  2062. if ($check ne "chk")
  2063. {
  2064. logger "Invalid parameter '$check' given for discover_ips function.";
  2065. return "";
  2066. }
  2067. my $iplist = "";
  2068. my $ipfound;
  2069. my $junk;
  2070. my @ipraw = `/sbin/ifconfig`;
  2071. while (<@ipraw>)
  2072. {
  2073. chomp;
  2074. next if $_ !~ /^inet:/ ;
  2075. logger "Found addr on line: $_";
  2076. ($junk, $ipfound) = split(":", $_);
  2077. next if $ipfound eq '';
  2078. next if $ipfound eq '127.0.0.1';
  2079. logger "Found an IP $ipfound";
  2080. $iplist .= "$ipfound,";
  2081. logger "IPlist is now $iplist";
  2082. }
  2083. while (<@ipraw>)
  2084. {
  2085. chomp;
  2086. next if $_ !~ /^addr:/ ;
  2087. logger "Found addr on line: $_";
  2088. ($junk, $ipfound) = split(":", $_);
  2089. next if $ipfound eq '';
  2090. next if $ipfound eq '127.0.0.1';
  2091. logger "Found an IP $ipfound";
  2092. $iplist .= "$ipfound,";
  2093. logger "IPlist is now $iplist";
  2094. }
  2095. chop $iplist;
  2096. return "$iplist";
  2097. }
  2098. ### Return -1 In case of invalid param
  2099. ### Return 1;content in case of success
  2100. sub mon_stats
  2101. {
  2102. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2103. my ($mon_stats) = decrypt_params(@_);
  2104. if ($mon_stats ne "mon_stats")
  2105. {
  2106. logger "Invalid parameter '$mon_stats' given for $mon_stats function.";
  2107. return -1;
  2108. }
  2109. my @disk = `df -hP -x tmpfs`;
  2110. my $encoded_content = encode_list(@disk);
  2111. my @uptime = `uptime`;
  2112. $encoded_content .= encode_list(@uptime);
  2113. return "1;$encoded_content";
  2114. }
  2115. sub exec
  2116. {
  2117. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2118. my ($command) = decrypt_params(@_);
  2119. my @cmdret = `$command 2>/dev/null`;
  2120. my $encoded_content = encode_list(@cmdret);
  2121. return "1;$encoded_content";
  2122. }
  2123. # used in conjunction with the clone_home feature in the web panel
  2124. # this actually does the file copies
  2125. sub clone_home
  2126. {
  2127. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2128. my ($source_home, $dest_home, $owner) = decrypt_params(@_);
  2129. my ($time_start, $time_stop, $time_diff);
  2130. logger "Copying from $source_home to $dest_home...";
  2131. # check size of source_home, make sure we have space to copy
  2132. if (!-e $source_home)
  2133. {
  2134. logger "ERROR - $source_home does not exist";
  2135. return 0;
  2136. }
  2137. logger "Game home $source_home exists...copy will proceed";
  2138. # start the copy, and a timer
  2139. $time_start = time();
  2140. if (!dircopy("$source_home", "$dest_home"))
  2141. {
  2142. $time_stop = time();
  2143. $time_diff = $time_stop - $time_start;
  2144. logger
  2145. "Error occured after $time_diff seconds during copy of $source_home to $dest_home - $!";
  2146. return 0;
  2147. }
  2148. else
  2149. {
  2150. $time_stop = time();
  2151. $time_diff = $time_stop - $time_start;
  2152. logger
  2153. "Home clone completed successfully to $dest_home in $time_diff seconds";
  2154. return 1;
  2155. }
  2156. }
  2157. # used to delete the game home from the file system when it's removed from the panel
  2158. sub remove_home
  2159. {
  2160. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2161. my ($home_path_del) = decrypt_params(@_);
  2162. if (!-e $home_path_del)
  2163. {
  2164. logger "ERROR - $home_path_del does not exist...nothing to do";
  2165. return 0;
  2166. }
  2167. secure_path_without_decrypt('chattr-i', $home_path_del);
  2168. sleep 1 while ( !pathrmdir("$home_path_del") );
  2169. logger "Deletetion of $home_path_del successful!";
  2170. return 1;
  2171. }
  2172. sub restart_server
  2173. {
  2174. chomp(@_);
  2175. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2176. return restart_server_without_decrypt(decrypt_params(@_));
  2177. }
  2178. ### Restart the server
  2179. ## return -2 CANT STOP
  2180. ## return -1 CANT START (no startup file found that mach the home_id, port and ip)
  2181. ## return 1 Restart OK
  2182. sub restart_server_without_decrypt
  2183. {
  2184. my ($home_id, $server_ip, $server_port, $control_protocol,
  2185. $control_password, $control_type, $home_path, $server_exe, $run_dir,
  2186. $cmd, $cpu, $nice, $preStart, $envVars) = @_;
  2187. if (stop_server_without_decrypt($home_id, $server_ip,
  2188. $server_port, $control_protocol,
  2189. $control_password, $control_type, $home_path) == 0)
  2190. {
  2191. if (universal_start_without_decrypt($home_id, $home_path, $server_exe, $run_dir,
  2192. $cmd, $server_port, $server_ip, $cpu, $nice, $preStart, $envVars) == 1)
  2193. {
  2194. return 1;
  2195. }
  2196. else
  2197. {
  2198. return -1;
  2199. }
  2200. }
  2201. else
  2202. {
  2203. return -2;
  2204. }
  2205. }
  2206. sub sudo_exec
  2207. {
  2208. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2209. my $sudo_exec = &decrypt_param(@_);
  2210. return sudo_exec_without_decrypt($sudo_exec);
  2211. }
  2212. sub sudo_exec_without_decrypt
  2213. {
  2214. my ($sudo_exec) = @_;
  2215. $sudo_exec =~ s/('+)/'"$1"'/g;
  2216. my $command = "echo '$SUDOPASSWD'|sudo -kS -p \"\" su -c '$sudo_exec;echo \$?' root 2>&1";
  2217. my @cmdret = qx($command);
  2218. chomp(@cmdret);
  2219. my $ret = pop(@cmdret);
  2220. chomp($ret);
  2221. if ("X$ret" eq "X0")
  2222. {
  2223. return "1;".encode_list(@cmdret);
  2224. }
  2225. return -1;
  2226. }
  2227. sub secure_path
  2228. {
  2229. chomp(@_);
  2230. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2231. return secure_path_without_decrypt(decrypt_params(@_));
  2232. }
  2233. sub secure_path_without_decrypt
  2234. {
  2235. my ($action, $file_path, $returnType) = @_;
  2236. if( -e $file_path )
  2237. {
  2238. my $uid = `id -u`;
  2239. chomp $uid;
  2240. my $gid = `id -g`;
  2241. chomp $gid;
  2242. $file_path =~ s/('+)/'\"$1\"'/g;
  2243. if($action eq "chattr+i")
  2244. {
  2245. if(defined $returnType && $returnType eq "str"){
  2246. return 'chown -Rf '.$uid.':'.$gid.' \''.$file_path.'\' && chattr -Rf +i \''.$file_path.'\'';
  2247. }else{
  2248. return sudo_exec_without_decrypt('chown -Rf '.$uid.':'.$gid.' \''.$file_path.'\' && chattr -Rf +i \''.$file_path.'\'');
  2249. }
  2250. }
  2251. elsif($action eq "chattr-i")
  2252. {
  2253. if(defined $returnType && $returnType eq "str"){
  2254. return 'chattr -Rf -i \''.$file_path.'\' && chown -Rf '.$uid.':'.$gid.' \''.$file_path.'\'';
  2255. }else{
  2256. return sudo_exec_without_decrypt('chattr -Rf -i \''.$file_path.'\' && chown -Rf '.$uid.':'.$gid.' \''.$file_path.'\'');
  2257. }
  2258. }
  2259. }
  2260. return -1;
  2261. }
  2262. sub get_chattr
  2263. {
  2264. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2265. my ($file_path) = decrypt_params(@_);
  2266. my $file = $file_path;
  2267. $file_path =~ s/('+)/'\"$1\"'/g;
  2268. return sudo_exec_without_decrypt('(lsattr \''.$file_path.'\' | sed -e "s#'.$file.'##g")|grep -o i');
  2269. }
  2270. sub ftp_mgr
  2271. {
  2272. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2273. my ($action, $login, $password, $home_path) = decrypt_params(@_);
  2274. my $uid = `id -u`;
  2275. chomp $uid;
  2276. my $gid = `id -g`;
  2277. chomp $gid;
  2278. $login =~ s/('+)/'\"$1\"'/g;
  2279. $password =~ s/('+)/'\"$1\"'/g;
  2280. $home_path =~ s/('+)/'\"$1\"'/g;
  2281. if(!defined($Cfg::Preferences{ogp_manages_ftp}) || (defined($Cfg::Preferences{ogp_manages_ftp}) && $Cfg::Preferences{ogp_manages_ftp} eq "1")){
  2282. if( defined($Cfg::Preferences{ftp_method}) && $Cfg::Preferences{ftp_method} eq "IspConfig")
  2283. {
  2284. use constant ISPCONFIG_DIR => Path::Class::Dir->new(AGENT_RUN_DIR, 'IspConfig');
  2285. use constant FTP_USERS_DIR => Path::Class::Dir->new(ISPCONFIG_DIR, 'ftp_users');
  2286. if (!-d FTP_USERS_DIR && !mkdir FTP_USERS_DIR)
  2287. {
  2288. print "Could not create " . FTP_USERS_DIR . " directory $!.";
  2289. return -1;
  2290. }
  2291. chdir ISPCONFIG_DIR;
  2292. if($action eq "list")
  2293. {
  2294. my $users_list;
  2295. opendir(USERS, FTP_USERS_DIR);
  2296. while (my $username = readdir(USERS))
  2297. {
  2298. # Skip . and ..
  2299. next if $username =~ /^\./;
  2300. $users_list .= `php-cgi -f sites_ftp_user_get.php username=\'$username\'`;
  2301. }
  2302. closedir(USERS);
  2303. if( defined($users_list) )
  2304. {
  2305. return "1;".encode_list($users_list);
  2306. }
  2307. }
  2308. elsif($action eq "userdel")
  2309. {
  2310. return "1;".encode_list(`php-cgi -f sites_ftp_user_delete.php username=\'$login\'`);
  2311. }
  2312. elsif($action eq "useradd")
  2313. {
  2314. return "1;".encode_list(`php-cgi -f sites_ftp_user_add.php username=\'$login\' password=\'$password\' dir=\'$home_path\' uid=$uid gid=$gid`);
  2315. }
  2316. elsif($action eq "passwd")
  2317. {
  2318. return "1;".encode_list(`php-cgi -f sites_ftp_user_update.php type=passwd username=\'$login\' password=\'$password\'`);
  2319. }
  2320. elsif($action eq "show")
  2321. {
  2322. return "1;".encode_list(`php-cgi -f sites_ftp_user_get.php type=detail username=\'$login\'`);
  2323. }
  2324. elsif($action eq "usermod")
  2325. {
  2326. return "1;".encode_list(`php-cgi -f sites_ftp_user_update.php username=\'$login\' password=\'$password\'`);
  2327. }
  2328. }
  2329. elsif(defined($Cfg::Preferences{ftp_method}) && $Cfg::Preferences{ftp_method} eq "EHCP" && -e "/etc/init.d/ehcp")
  2330. {
  2331. use constant EHCP_DIR => Path::Class::Dir->new(AGENT_RUN_DIR, 'EHCP');
  2332. chdir EHCP_DIR;
  2333. my $phpScript;
  2334. my $phpOut;
  2335. chmod 0777, 'ehcp_ftp_log.txt';
  2336. # In order to access the FTP files, the vsftpd user needs to be added to the ogp group
  2337. sudo_exec_without_decrypt("usermod -a -G '$gid' ftp");
  2338. sudo_exec_without_decrypt("usermod -a -G '$gid' vsftpd");
  2339. if($action eq "list")
  2340. {
  2341. return "1;".encode_list(`php-cgi -f listAllUsers.php`);
  2342. }
  2343. elsif($action eq "userdel")
  2344. {
  2345. $phpScript = `php-cgi -f delAccount.php username=\'$login\'`;
  2346. $phpOut = `php-cgi -f syncftp.php`;
  2347. return $phpScript;
  2348. }
  2349. elsif($action eq "useradd")
  2350. {
  2351. $phpScript = `php-cgi -f addAccount.php username=\'$login\' password=\'$password\' dir=\'$home_path\' uid=$uid gid=$gid`;
  2352. $phpOut = `php-cgi -f syncftp.php`;
  2353. return $phpScript;
  2354. }
  2355. elsif($action eq "passwd")
  2356. {
  2357. $phpScript = `php-cgi -f updatePass.php username=\'$login\' password=\'$password\'`;
  2358. $phpOut = `php-cgi -f syncftp.php`;
  2359. return $phpScript ;
  2360. }
  2361. elsif($action eq "show")
  2362. {
  2363. return "1;".encode_list(`php-cgi -f showAccount.php username=\'$login\'`);
  2364. }
  2365. elsif($action eq "usermod")
  2366. {
  2367. $phpScript = `php-cgi -f updateInfo.php username=\'$login\' password=\'$password\'`;
  2368. $phpOut = `php-cgi -f syncftp.php`;
  2369. return $phpScript;
  2370. }
  2371. }
  2372. elsif(defined($Cfg::Preferences{ftp_method}) && $Cfg::Preferences{ftp_method} eq "proftpd" && -e $Cfg::Preferences{proftpd_conf_path})
  2373. {
  2374. chdir $Cfg::Preferences{proftpd_conf_path};
  2375. if($action eq "list")
  2376. {
  2377. my $users;
  2378. open(PASSWD, 'ftpd.passwd');
  2379. while (<PASSWD>) {
  2380. chomp;
  2381. my($login, $passwd, $uid, $gid, $gcos, $home, $shell) = split(/:/);
  2382. $users .= "$login\t$home\n";
  2383. }
  2384. close(PASSWD);
  2385. return "1;".encode_list($users);
  2386. }
  2387. elsif($action eq "userdel")
  2388. {
  2389. return sudo_exec_without_decrypt("ftpasswd --passwd --delete-user --name='$login'");
  2390. }
  2391. elsif($action eq "useradd")
  2392. {
  2393. return sudo_exec_without_decrypt("echo '$password' | ftpasswd --passwd --name='$login' --home='$home_path' --shell=/bin/false --uid=$uid --gid=$gid --stdin");
  2394. }
  2395. elsif($action eq "passwd")
  2396. {
  2397. return sudo_exec_without_decrypt("echo '$password' | ftpasswd --passwd --change-password --name='$login' --stdin");
  2398. }
  2399. elsif($action eq "show")
  2400. {
  2401. return 1;
  2402. }
  2403. elsif($action eq "usermod")
  2404. {
  2405. return 1;
  2406. }
  2407. chdir AGENT_RUN_DIR;
  2408. }
  2409. else
  2410. {
  2411. if($action eq "list")
  2412. {
  2413. return sudo_exec_without_decrypt("pure-pw list");
  2414. }
  2415. elsif($action eq "userdel")
  2416. {
  2417. return sudo_exec_without_decrypt("pure-pw userdel '$login' && pure-pw mkdb");
  2418. }
  2419. elsif($action eq "useradd")
  2420. {
  2421. return sudo_exec_without_decrypt("(echo '$password'; echo '$password') | pure-pw useradd '$login' -u $uid -g $gid -d '$home_path' && pure-pw mkdb");
  2422. }
  2423. elsif($action eq "passwd")
  2424. {
  2425. return sudo_exec_without_decrypt("(echo '$password'; echo '$password') | pure-pw passwd '$login' && pure-pw mkdb");
  2426. }
  2427. elsif($action eq "show")
  2428. {
  2429. return sudo_exec_without_decrypt("pure-pw show '$login'");
  2430. }
  2431. elsif($action eq "usermod")
  2432. {
  2433. my $update_account = "pure-pw usermod '$login' -u $uid -g $gid";
  2434. my @account_settings = split /[\n]+/, $password;
  2435. foreach my $setting (@account_settings) {
  2436. my ($key, $value) = split /[\t]+/, $setting;
  2437. if( $key eq 'Directory' )
  2438. {
  2439. $value =~ s/('+)/'\"$1\"'/g;
  2440. $update_account .= " -d '$value'";
  2441. }
  2442. if( $key eq 'Full_name' )
  2443. {
  2444. if( $value ne "" )
  2445. {
  2446. $value =~ s/('+)/'\"$1\"'/g;
  2447. $update_account .= " -c '$value'";
  2448. }
  2449. else
  2450. {
  2451. $update_account .= ' -c ""';
  2452. }
  2453. }
  2454. if( $key eq 'Download_bandwidth' && $value ne "" )
  2455. {
  2456. my $Download_bandwidth;
  2457. if($value eq 0)
  2458. {
  2459. $Download_bandwidth = "\"\"";
  2460. }
  2461. else
  2462. {
  2463. $Download_bandwidth = $value;
  2464. }
  2465. $update_account .= " -t " . $Download_bandwidth;
  2466. }
  2467. if( $key eq 'Upload___bandwidth' && $value ne "" )
  2468. {
  2469. my $Upload___bandwidth;
  2470. if($value eq 0)
  2471. {
  2472. $Upload___bandwidth = "\"\"";
  2473. }
  2474. else
  2475. {
  2476. $Upload___bandwidth = $value;
  2477. }
  2478. $update_account .= " -T " . $Upload___bandwidth;
  2479. }
  2480. if( $key eq 'Max_files' )
  2481. {
  2482. if( $value eq "0" )
  2483. {
  2484. $update_account .= ' -n ""';
  2485. }
  2486. elsif( $value ne "" )
  2487. {
  2488. $update_account .= " -n " . $value;
  2489. }
  2490. else
  2491. {
  2492. $update_account .= ' -n ""';
  2493. }
  2494. }
  2495. if( $key eq 'Max_size' )
  2496. {
  2497. if( $value ne "" && $value ne "0" )
  2498. {
  2499. $update_account .= " -N " . $value;
  2500. }
  2501. else
  2502. {
  2503. $update_account .= ' -N ""';
  2504. }
  2505. }
  2506. if( $key eq 'Ratio' && $value ne "" )
  2507. {
  2508. my($upload_ratio,$download_ratio) = split/:/,$value;
  2509. if($upload_ratio eq "0")
  2510. {
  2511. $upload_ratio = "\"\"";
  2512. }
  2513. $update_account .= " -q " . $upload_ratio;
  2514. if($download_ratio eq "0")
  2515. {
  2516. $download_ratio = "\"\"";
  2517. }
  2518. $update_account .= " -Q " . $download_ratio;
  2519. }
  2520. if( $key eq 'Allowed_client_IPs' )
  2521. {
  2522. if( $value ne "" )
  2523. {
  2524. $update_account .= " -r " . $value;
  2525. }
  2526. else
  2527. {
  2528. $update_account .= ' -r ""';
  2529. }
  2530. }
  2531. if( $key eq 'Denied__client_IPs' )
  2532. {
  2533. if( $value ne "" )
  2534. {
  2535. $update_account .= " -R " . $value;
  2536. }
  2537. else
  2538. {
  2539. $update_account .= ' -R ""';
  2540. }
  2541. }
  2542. if( $key eq 'Allowed_local__IPs' )
  2543. {
  2544. if( $value ne "" )
  2545. {
  2546. $update_account .= " -i " . $value;
  2547. }
  2548. else
  2549. {
  2550. $update_account .= ' -i ""';
  2551. }
  2552. }
  2553. if( $key eq 'Denied__local__IPs' )
  2554. {
  2555. if( $value ne "" )
  2556. {
  2557. $update_account .= " -I " . $value;
  2558. }
  2559. else
  2560. {
  2561. $update_account .= ' -I ""';
  2562. }
  2563. }
  2564. if( $key eq 'Max_sim_sessions' && $value ne "" )
  2565. {
  2566. $update_account .= " -y " . $value;
  2567. }
  2568. if ( $key eq 'Time_restrictions' )
  2569. {
  2570. if( $value eq "0000-0000")
  2571. {
  2572. $update_account .= ' -z ""';
  2573. }
  2574. elsif( $value ne "" )
  2575. {
  2576. $update_account .= " -z " . $value;
  2577. }
  2578. else
  2579. {
  2580. $update_account .= ' -z ""';
  2581. }
  2582. }
  2583. }
  2584. $update_account .=" && pure-pw mkdb";
  2585. # print $update_account;
  2586. return sudo_exec_without_decrypt($update_account);
  2587. }
  2588. }
  2589. }
  2590. return 0;
  2591. }
  2592. sub start_fastdl
  2593. {
  2594. if(-e Path::Class::File->new(FD_DIR, 'Settings.pm'))
  2595. {
  2596. system('perl FastDownload/ForkedDaemon.pm &');
  2597. sleep(1);
  2598. return 1;
  2599. }
  2600. else
  2601. {
  2602. return -2;
  2603. }
  2604. }
  2605. sub stop_fastdl
  2606. {
  2607. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2608. return stop_fastdl_without_decrypt();
  2609. }
  2610. sub stop_fastdl_without_decrypt
  2611. {
  2612. my $pid;
  2613. open(PIDFILE, '<', FD_PID_FILE)
  2614. || logger "Error reading pid file $!",1;
  2615. while (<PIDFILE>)
  2616. {
  2617. $pid = $_;
  2618. chomp $pid;
  2619. }
  2620. close(PIDFILE);
  2621. my $cnt = kill 9, $pid;
  2622. if ($cnt == 1)
  2623. {
  2624. logger "Fast Download Daemon Stopped.",1;
  2625. return 1;
  2626. }
  2627. else
  2628. {
  2629. logger "Fast Download Daemon with pid $pid can not be stopped.",1;
  2630. return -1;
  2631. }
  2632. }
  2633. sub restart_fastdl
  2634. {
  2635. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2636. return restart_fastdl_without_decrypt();
  2637. }
  2638. sub restart_fastdl_without_decrypt
  2639. {
  2640. if((fastdl_status_without_decrypt() == -1) || (stop_fastdl_without_decrypt() == 1))
  2641. {
  2642. if(start_fastdl() == 1)
  2643. {
  2644. # Success
  2645. return 1;
  2646. }
  2647. # Cant start
  2648. return -2;
  2649. }
  2650. # Cant stop
  2651. return -3;
  2652. }
  2653. sub fastdl_status
  2654. {
  2655. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2656. return fastdl_status_without_decrypt();
  2657. }
  2658. sub fastdl_status_without_decrypt
  2659. {
  2660. my $pid;
  2661. if(!open(PIDFILE, '<', FD_PID_FILE))
  2662. {
  2663. logger "Error reading pid file $!";
  2664. return -1;
  2665. }
  2666. while (<PIDFILE>)
  2667. {
  2668. $pid = $_;
  2669. chomp $pid;
  2670. }
  2671. close(PIDFILE);
  2672. my $cnt = kill 0, $pid;
  2673. if ($cnt == 1)
  2674. {
  2675. return 1;
  2676. }
  2677. else
  2678. {
  2679. return -1;
  2680. }
  2681. }
  2682. sub fastdl_get_aliases
  2683. {
  2684. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2685. my %aliases;
  2686. my $i;
  2687. my @file_lines;
  2688. if(-d FD_ALIASES_DIR)
  2689. {
  2690. if( !opendir(ALIASES, FD_ALIASES_DIR) )
  2691. {
  2692. logger "Error openning aliases directory " . FD_ALIASES_DIR . ", $!";
  2693. }
  2694. else
  2695. {
  2696. while (my $alias = readdir(ALIASES))
  2697. {
  2698. # Skip . and ..
  2699. next if $alias =~ /^\./;
  2700. if( !open(ALIAS, '<', Path::Class::Dir->new(FD_ALIASES_DIR, $alias)) )
  2701. {
  2702. logger "Error reading alias '$alias', $!";
  2703. }
  2704. else
  2705. {
  2706. $i = 0;
  2707. @file_lines = ();
  2708. while (<ALIAS>)
  2709. {
  2710. chomp $_;
  2711. $file_lines[$i] = $_;
  2712. $i++;
  2713. }
  2714. close(ALIAS);
  2715. $aliases{$alias}{home} = $file_lines[0];
  2716. $aliases{$alias}{match_file_extension} = $file_lines[1];
  2717. $aliases{$alias}{match_client_ip} = $file_lines[2];
  2718. }
  2719. }
  2720. closedir(ALIASES);
  2721. }
  2722. }
  2723. else
  2724. {
  2725. logger "Aliases directory '" . FD_ALIASES_DIR . "' does not exist or is inaccessible.";
  2726. }
  2727. return {%aliases};
  2728. }
  2729. sub fastdl_del_alias
  2730. {
  2731. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2732. foreach my $alias (decrypt_params(@_))
  2733. {
  2734. unlink Path::Class::File->new(FD_ALIASES_DIR, $alias);
  2735. }
  2736. return restart_fastdl_without_decrypt();
  2737. }
  2738. sub fastdl_add_alias
  2739. {
  2740. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2741. my ($alias,$home,$match_file_extension,$match_client_ip) = decrypt_params(@_);
  2742. if(!-e FD_ALIASES_DIR)
  2743. {
  2744. if(!mkdir FD_ALIASES_DIR)
  2745. {
  2746. logger "ERROR - Failed to create " . FD_ALIASES_DIR . " directory.";
  2747. return -1;
  2748. }
  2749. }
  2750. my $alias_path = Path::Class::File->new(FD_ALIASES_DIR, $alias);
  2751. if (!open(ALIAS, '>', $alias_path))
  2752. {
  2753. logger "ERROR - Failed to open ".$alias_path." for writing.";
  2754. return -1;
  2755. }
  2756. else
  2757. {
  2758. print ALIAS "$home\n";
  2759. print ALIAS "$match_file_extension\n";
  2760. print ALIAS "$match_client_ip";
  2761. close(ALIAS);
  2762. return restart_fastdl_without_decrypt();
  2763. }
  2764. }
  2765. sub fastdl_get_info
  2766. {
  2767. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2768. if(-e Path::Class::File->new(FD_DIR, 'Settings.pm'))
  2769. {
  2770. delete $INC{"FastDownload/Settings.pm"};
  2771. require "FastDownload/Settings.pm"; # Settings for Fast Download Daemon.
  2772. if(not defined $FastDownload::Settings{autostart_on_agent_startup})
  2773. {
  2774. $FastDownload::Settings{autostart_on_agent_startup} = 0;
  2775. }
  2776. return {'port' => $FastDownload::Settings{port},
  2777. 'ip' => $FastDownload::Settings{ip},
  2778. 'listing' => $FastDownload::Settings{listing},
  2779. 'autostart_on_agent_startup'=> $FastDownload::Settings{autostart_on_agent_startup}};
  2780. }
  2781. return -1
  2782. }
  2783. sub fastdl_create_config
  2784. {
  2785. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2786. if(!-e FD_DIR)
  2787. {
  2788. if(!mkdir FD_DIR)
  2789. {
  2790. logger "ERROR - Failed to create " . FD_DIR . " directory.";
  2791. return -1;
  2792. }
  2793. }
  2794. my ($fd_address, $fd_port, $listing, $autostart_on_agent_startup) = decrypt_params(@_);
  2795. my $settings_string = "%FastDownload::Settings = (\n".
  2796. "\tport => $fd_port,\n".
  2797. "\tip => '$fd_address',\n".
  2798. "\tlisting => $listing,\n".
  2799. "\tautostart_on_agent_startup => $autostart_on_agent_startup,\n".
  2800. ");";
  2801. my $settings = Path::Class::File->new(FD_DIR, 'Settings.pm');
  2802. if (!open(SETTINGS, '>', $settings))
  2803. {
  2804. logger "ERROR - Failed to open $settings for writing.";
  2805. return -1;
  2806. }
  2807. else
  2808. {
  2809. print SETTINGS $settings_string;
  2810. close(SETTINGS);
  2811. }
  2812. logger "$settings file written successfully.";
  2813. return 1;
  2814. }
  2815. sub agent_restart
  2816. {
  2817. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2818. my $dec_check = decrypt_param(@_);
  2819. if ($dec_check eq 'restart')
  2820. {
  2821. chdir AGENT_RUN_DIR;
  2822. if(-e "ogp_agent_run.pid")
  2823. {
  2824. my $init_pid = `cat ogp_agent_run.pid`;
  2825. chomp($init_pid);
  2826. if(kill 0, $init_pid)
  2827. {
  2828. my $or_exist = "";
  2829. my $rm_pid_file = "";
  2830. if(-e "ogp_agent.pid")
  2831. {
  2832. $rm_pid_file = " ogp_agent.pid";
  2833. my $agent_pid = `cat ogp_agent.pid`;
  2834. chomp($agent_pid);
  2835. if( kill 0, $agent_pid )
  2836. {
  2837. $or_exist = " -o -e /proc/$agent_pid";
  2838. }
  2839. }
  2840. open (AGENT_RESTART_SCRIPT, '>', 'tmp_restart.sh');
  2841. my $restart = "echo -n \"Stopping OGP Agent...\"\n".
  2842. "kill $init_pid\n".
  2843. "while [ -e /proc/$init_pid $or_exist ];do echo -n .;sleep 1;done\n".
  2844. "rm -f ogp_agent_run.pid $rm_pid_file\necho \" [OK]\"\n".
  2845. "echo -n \"Starting OGP Agent...\"\n".
  2846. "screen -d -m -t \"ogp_agent\" -c \"" . SCREENRC_FILE . "\" -S ogp_agent bash ogp_agent_run -pidfile ogp_agent_run.pid\n".
  2847. "while [ ! -e ogp_agent_run.pid -o ! -e ogp_agent.pid ];do echo -n .;sleep 1;done\n".
  2848. "echo \" [OK]\"\n".
  2849. "rm -f tmp_restart.sh\n".
  2850. "exit 0\n";
  2851. print AGENT_RESTART_SCRIPT $restart;
  2852. close (AGENT_RESTART_SCRIPT);
  2853. if( -e 'tmp_restart.sh' )
  2854. {
  2855. system('screen -d -m -t "agent_restart" -c "' . SCREENRC_FILE . '" -S agent_restart bash tmp_restart.sh');
  2856. }
  2857. }
  2858. }
  2859. }
  2860. return -1;
  2861. }
  2862. # Subroutines to be called
  2863. sub scheduler_dispatcher {
  2864. my ($task, $args) = @_;
  2865. my $response = `$args`;
  2866. chomp($response);
  2867. my $log = "Executed command: $args";
  2868. if($response ne "")
  2869. {
  2870. $log .= ", response:\n$response";
  2871. }
  2872. scheduler_log_events($log);
  2873. }
  2874. sub scheduler_server_action
  2875. {
  2876. my ($task, $args) = @_;
  2877. my ($action, @server_args) = split('\|\%\|', $args);
  2878. if($action eq "%ACTION=start")
  2879. {
  2880. my ($home_id, $ip, $port) = ($server_args[0], $server_args[6], $server_args[5]);
  2881. my $ret = universal_start_without_decrypt(@server_args);
  2882. if($ret == 1)
  2883. {
  2884. scheduler_log_events("Started server home ID $home_id on address $ip:$port");
  2885. }
  2886. else
  2887. {
  2888. scheduler_log_events("Failed starting server home ID $home_id on address $ip:$port (Check agent log)");
  2889. }
  2890. }
  2891. elsif($action eq "%ACTION=stop")
  2892. {
  2893. my ($home_id, $ip, $port) = ($server_args[0], $server_args[1], $server_args[2]);
  2894. my $ret = stop_server_without_decrypt(@server_args);
  2895. if($ret == 0)
  2896. {
  2897. scheduler_log_events("Stopped server home ID $home_id on address $ip:$port");
  2898. }
  2899. elsif($ret == 1)
  2900. {
  2901. scheduler_log_events("Failed stopping server home ID $home_id on address $ip:$port (Invalid IP:Port given)");
  2902. }
  2903. }
  2904. elsif($action eq "%ACTION=restart")
  2905. {
  2906. my ($home_id, $ip, $port) = ($server_args[0], $server_args[1], $server_args[2]);
  2907. my $ret = restart_server_without_decrypt(@server_args);
  2908. if($ret == 1)
  2909. {
  2910. scheduler_log_events("Restarted server home ID $home_id on address $ip:$port");
  2911. }
  2912. elsif($ret == -1)
  2913. {
  2914. scheduler_log_events("Failed restarting server home ID $home_id on address $ip:$port (Server could not be started, check agent log)");
  2915. }
  2916. elsif($ret == -2)
  2917. {
  2918. scheduler_log_events("Failed restarting server home ID $home_id on address $ip:$port (Server could not be stopped, check agent log)");
  2919. }
  2920. }
  2921. return 1;
  2922. }
  2923. sub scheduler_log_events
  2924. {
  2925. my $logcmd = $_[0];
  2926. $logcmd = localtime() . " $logcmd\n";
  2927. logger "Can't open " . SCHED_LOG_FILE . " - $!" unless open(LOGFILE, '>>', SCHED_LOG_FILE);
  2928. logger "Failed to lock " . SCHED_LOG_FILE . "." unless flock(LOGFILE, LOCK_EX);
  2929. logger "Failed to seek to end of " . SCHED_LOG_FILE . "." unless seek(LOGFILE, 0, 2);
  2930. logger "Failed to write to " . SCHED_LOG_FILE . "." unless print LOGFILE "$logcmd";
  2931. logger "Failed to unlock " . SCHED_LOG_FILE . "." unless flock(LOGFILE, LOCK_UN);
  2932. logger "Failed to close " . SCHED_LOG_FILE . "." unless close(LOGFILE);
  2933. }
  2934. sub scheduler_add_task
  2935. {
  2936. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2937. my $new_task = decrypt_param(@_);
  2938. if (open(TASKS, '>>', SCHED_TASKS))
  2939. {
  2940. print TASKS "$new_task\n";
  2941. logger "Created new task: $new_task";
  2942. close(TASKS);
  2943. scheduler_stop();
  2944. # Create new object with default dispatcher for scheduled tasks
  2945. $cron = new Schedule::Cron( \&scheduler_dispatcher, {
  2946. nofork => 1,
  2947. loglevel => 0,
  2948. log => sub { print $_[1], "\n"; }
  2949. } );
  2950. $cron->add_entry( "* * * * * *", \&scheduler_read_tasks );
  2951. # Run scheduler
  2952. $cron->run( {detach=>1, pid_file=>SCHED_PID} );
  2953. return 1;
  2954. }
  2955. logger "Cannot create task: $new_task ( $! )";
  2956. return -1;
  2957. }
  2958. sub scheduler_del_task
  2959. {
  2960. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2961. my $name = decrypt_param(@_);
  2962. if( scheduler_read_tasks() == -1 )
  2963. {
  2964. return -1;
  2965. }
  2966. my @entries = $cron->list_entries();
  2967. if(open(TASKS, '>', SCHED_TASKS))
  2968. {
  2969. foreach my $task ( @entries ) {
  2970. next if $task->{args}[0] eq $name;
  2971. next unless $task->{args}[0] =~ /task_[0-9]*/;
  2972. if(defined $task->{args}[1])
  2973. {
  2974. print TASKS join(" ", $task->{time}, $task->{args}[1]) . "\n";
  2975. }
  2976. else
  2977. {
  2978. print TASKS $task->{time} . "\n";
  2979. }
  2980. }
  2981. close( TASKS );
  2982. scheduler_stop();
  2983. # Create new object with default dispatcher for scheduled tasks
  2984. $cron = new Schedule::Cron( \&scheduler_dispatcher, {
  2985. nofork => 1,
  2986. loglevel => 0,
  2987. log => sub { print $_[1], "\n"; }
  2988. } );
  2989. $cron->add_entry( "* * * * * *", \&scheduler_read_tasks );
  2990. # Run scheduler
  2991. $cron->run( {detach=>1, pid_file=>SCHED_PID} );
  2992. return 1;
  2993. }
  2994. logger "Cannot open file " . SCHED_TASKS . " for deleting task id: $name ( $! )",1;
  2995. return -1;
  2996. }
  2997. sub scheduler_edit_task
  2998. {
  2999. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3000. my ($name, $new_task) = decrypt_params(@_);
  3001. if( scheduler_read_tasks() == -1 )
  3002. {
  3003. return -1;
  3004. }
  3005. my @entries = $cron->list_entries();
  3006. if(open(TASKS, '>', SCHED_TASKS))
  3007. {
  3008. foreach my $task ( @entries ) {
  3009. next unless $task->{args}[0] =~ /task_[0-9]*/;
  3010. if($name eq $task->{args}[0])
  3011. {
  3012. print TASKS "$new_task\n";
  3013. }
  3014. else
  3015. {
  3016. if(defined $task->{args}[1])
  3017. {
  3018. print TASKS join(" ", $task->{time}, $task->{args}[1]) . "\n";
  3019. }
  3020. else
  3021. {
  3022. print TASKS $task->{time} . "\n";
  3023. }
  3024. }
  3025. }
  3026. close( TASKS );
  3027. scheduler_stop();
  3028. # Create new object with default dispatcher for scheduled tasks
  3029. $cron = new Schedule::Cron( \&scheduler_dispatcher, {
  3030. nofork => 1,
  3031. loglevel => 0,
  3032. log => sub { print $_[1], "\n"; }
  3033. } );
  3034. $cron->add_entry( "* * * * * *", \&scheduler_read_tasks );
  3035. # Run scheduler
  3036. $cron->run( {detach=>1, pid_file=>SCHED_PID} );
  3037. return 1;
  3038. }
  3039. logger "Cannot open file " . SCHED_TASKS . " for editing task id: $name ( $! )",1;
  3040. return -1;
  3041. }
  3042. sub scheduler_read_tasks
  3043. {
  3044. if( open(TASKS, '<', SCHED_TASKS) )
  3045. {
  3046. $cron->clean_timetable();
  3047. }
  3048. else
  3049. {
  3050. logger "Error reading tasks file $!";
  3051. scheduler_stop();
  3052. return -1;
  3053. }
  3054. my $i = 0;
  3055. while (<TASKS>)
  3056. {
  3057. next if $_ =~ /^(#.*|[\s|\t]*?\n)/;
  3058. my ($minute, $hour, $dayOfTheMonth, $month, $dayOfTheWeek, @args) = split(' ', $_);
  3059. my $time = "$minute $hour $dayOfTheMonth $month $dayOfTheWeek";
  3060. if("@args" =~ /^\%ACTION.*/)
  3061. {
  3062. $cron->add_entry($time, \&scheduler_server_action, 'task_' . $i++, "@args");
  3063. }
  3064. else
  3065. {
  3066. $cron->add_entry($time, 'task_' . $i++, "@args");
  3067. }
  3068. }
  3069. close(TASKS);
  3070. return 1;
  3071. }
  3072. sub scheduler_stop
  3073. {
  3074. my $pid;
  3075. if(open(PIDFILE, '<', SCHED_PID))
  3076. {
  3077. $pid = <PIDFILE>;
  3078. chomp $pid;
  3079. close(PIDFILE);
  3080. if($pid ne "")
  3081. {
  3082. if( kill 0, $pid )
  3083. {
  3084. my $cnt = kill 9, $pid;
  3085. if ($cnt == 1)
  3086. {
  3087. unlink SCHED_PID;
  3088. return 1;
  3089. }
  3090. }
  3091. }
  3092. }
  3093. return -1;
  3094. }
  3095. sub scheduler_list_tasks
  3096. {
  3097. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3098. if( scheduler_read_tasks() == -1 )
  3099. {
  3100. return -1;
  3101. }
  3102. my @entries = $cron->list_entries();
  3103. my %entries_array;
  3104. foreach my $task ( @entries ) {
  3105. if( defined $task->{args}[1] )
  3106. {
  3107. $entries_array{$task->{args}[0]} = encode_base64(join(" ", $task->{time}, $task->{args}[1]));
  3108. }
  3109. else
  3110. {
  3111. $entries_array{$task->{args}[0]} = encode_base64($task->{time});
  3112. }
  3113. }
  3114. if( %entries_array )
  3115. {
  3116. return {%entries_array};
  3117. }
  3118. return -1;
  3119. }
  3120. sub get_file_part
  3121. {
  3122. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3123. my ($file, $offset) = decrypt_params(@_);
  3124. if (!open(FILE, '<', $file))
  3125. {
  3126. logger "ERROR - Can't open file $file for reading.";
  3127. return -1;
  3128. }
  3129. binmode(FILE);
  3130. if($offset != 0)
  3131. {
  3132. return -1 unless seek FILE, $offset, 0;
  3133. }
  3134. my $data = "";
  3135. my ($n, $buf);
  3136. my $limit = $offset + 60 * 57 * 1000; #Max 3420Kb (1000 iterations) (top statistics ~ VIRT 116m, RES 47m)
  3137. while (($n = read FILE, $buf, 60 * 57) != 0 && $offset <= $limit ) {
  3138. $data .= $buf;
  3139. $offset += $n;
  3140. }
  3141. close(FILE);
  3142. if( $data ne "" )
  3143. {
  3144. my $b64zlib = encode_base64(compress($data,9));
  3145. return "$offset;$b64zlib";
  3146. }
  3147. else
  3148. {
  3149. return -1;
  3150. }
  3151. }
  3152. sub stop_update
  3153. {
  3154. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3155. my $home_id = decrypt_param(@_);
  3156. my $screen_id = create_screen_id(SCREEN_TYPE_UPDATE, $home_id);
  3157. system('screen -S '.$screen_id.' -p 0 -X stuff $\'\003\'');
  3158. if ($? == 0)
  3159. {
  3160. return 0;
  3161. }
  3162. return 1
  3163. }
  3164. sub shell_action
  3165. {
  3166. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3167. my ($action, $arguments) = decrypt_params(@_);
  3168. if($action eq 'remove_file')
  3169. {
  3170. chomp($arguments);
  3171. unlink($arguments);
  3172. return "1;";
  3173. }
  3174. elsif($action eq 'remove_recursive')
  3175. {
  3176. my @items = split(';', $arguments);
  3177. foreach my $item ( @items ) {
  3178. chomp($item);
  3179. if(-d $item)
  3180. {
  3181. pathrmdir($item);
  3182. }
  3183. else
  3184. {
  3185. unlink($item);
  3186. }
  3187. }
  3188. return "1;";
  3189. }
  3190. elsif($action eq 'create_dir')
  3191. {
  3192. chomp($arguments);
  3193. mkpath($arguments);
  3194. return "1;";
  3195. }
  3196. elsif($action eq 'move')
  3197. {
  3198. my($src, $dest) = split(';', $arguments);
  3199. chomp($src);
  3200. chomp($dest);
  3201. if(-d $src)
  3202. {
  3203. $dest = Path::Class::Dir->new($dest, basename($src));
  3204. dirmove($src, $dest);
  3205. }
  3206. else
  3207. {
  3208. fmove($src, $dest);
  3209. }
  3210. return "1;";
  3211. }
  3212. elsif($action eq 'copy')
  3213. {
  3214. my($src, $dest) = split(';', $arguments);
  3215. chomp($src);
  3216. chomp($dest);
  3217. if(-d $src)
  3218. {
  3219. $dest = Path::Class::Dir->new($dest, basename($src));
  3220. dircopy($src, $dest);
  3221. }
  3222. else
  3223. {
  3224. fcopy($src, $dest);
  3225. }
  3226. return "1;";
  3227. }
  3228. elsif($action eq 'touch')
  3229. {
  3230. chomp($arguments);
  3231. open(FH, '>', $arguments);
  3232. print FH "";
  3233. close(FH);
  3234. return "1;";
  3235. }
  3236. elsif($action eq 'size')
  3237. {
  3238. chomp($arguments);
  3239. my $size = 0;
  3240. if(-d $arguments)
  3241. {
  3242. find(sub { $size += -s }, $arguments ? $arguments : '.');
  3243. }
  3244. else
  3245. {
  3246. $size += (stat($arguments))[7];
  3247. }
  3248. return "1;" . encode_list($size);
  3249. }
  3250. elsif($action eq 'get_cpu_usage')
  3251. {
  3252. my %prev_idle;
  3253. my %prev_total;
  3254. open(STAT, '/proc/stat');
  3255. while (<STAT>) {
  3256. next unless /^cpu([0-9]+)/;
  3257. my @stat = split /\s+/, $_;
  3258. $prev_idle{$1} = $stat[4];
  3259. $prev_total{$1} = $stat[1] + $stat[2] + $stat[3] + $stat[4];
  3260. }
  3261. close STAT;
  3262. sleep 1;
  3263. my %idle;
  3264. my %total;
  3265. open(STAT, '/proc/stat');
  3266. while (<STAT>) {
  3267. next unless /^cpu([0-9]+)/;
  3268. my @stat = split /\s+/, $_;
  3269. $idle{$1} = $stat[4];
  3270. $total{$1} = $stat[1] + $stat[2] + $stat[3] + $stat[4];
  3271. }
  3272. close STAT;
  3273. my %cpu_percent_usage;
  3274. foreach my $key ( keys %idle )
  3275. {
  3276. my $diff_idle = $idle{$key} - $prev_idle{$key};
  3277. my $diff_total = $total{$key} - $prev_total{$key};
  3278. my $percent = (100 * ($diff_total - $diff_idle)) / $diff_total;
  3279. $percent = sprintf "%.2f", $percent unless $percent == 0;
  3280. $cpu_percent_usage{$key} = encode_base64($percent);
  3281. }
  3282. return {%cpu_percent_usage};
  3283. }
  3284. elsif($action eq 'get_ram_usage')
  3285. {
  3286. my($total, $buffers, $cached, $free) = qw(0 0 0 0);
  3287. open(STAT, '/proc/meminfo');
  3288. while (<STAT>) {
  3289. $total += $1 if /MemTotal\:\s+(\d+) kB/;
  3290. $buffers += $1 if /Buffers\:\s+(\d+) kB/;
  3291. $cached += $1 if /Cached\:\s+(\d+) kB/;
  3292. $free += $1 if /MemFree\:\s+(\d+) kB/;
  3293. }
  3294. close STAT;
  3295. my $used = $total - $free - $cached - $buffers;
  3296. my $percent = 100 * $used / $total;
  3297. my %mem_usage;
  3298. $mem_usage{'used'} = encode_base64($used * 1024);
  3299. $mem_usage{'total'} = encode_base64($total * 1024);
  3300. $mem_usage{'percent'} = encode_base64($percent);
  3301. return {%mem_usage};
  3302. }
  3303. elsif($action eq 'get_disk_usage')
  3304. {
  3305. my($total, $used, $free) = split(' ', `df -lP 2>/dev/null|grep "^/dev/.*"|awk '{total+=\$2}{used+=\$3}{free+=\$4} END {print total, used, free}'`);
  3306. my $percent = 100 * $used / $total;
  3307. my %disk_usage;
  3308. $disk_usage{'free'} = encode_base64($free * 1024);
  3309. $disk_usage{'used'} = encode_base64($used * 1024);
  3310. $disk_usage{'total'} = encode_base64($total * 1024);
  3311. $disk_usage{'percent'} = encode_base64($percent);
  3312. return {%disk_usage};
  3313. }
  3314. elsif($action eq 'get_uptime')
  3315. {
  3316. open(STAT, '/proc/uptime');
  3317. my $uptime = 0;
  3318. while (<STAT>) {
  3319. $uptime += $1 if /^([0-9]+)/;
  3320. }
  3321. close STAT;
  3322. my %upsince;
  3323. $upsince{'0'} = encode_base64($uptime);
  3324. $upsince{'1'} = encode_base64(time - $uptime);
  3325. return {%upsince};
  3326. }
  3327. elsif($action eq 'get_tasklist')
  3328. {
  3329. my %taskList;
  3330. $taskList{'task'} = encode_base64(`ps -Ao user,pid,pcpu,pmem,comm,args --sort=-pcpu | head -n 30`);
  3331. return {%taskList};
  3332. }
  3333. elsif($action eq 'get_timestamp')
  3334. {
  3335. return "1;" . encode_list(time);
  3336. }
  3337. return 0;
  3338. }
  3339. sub remote_query
  3340. {
  3341. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3342. my ($protocol, $game_type, $ip, $c_port, $q_port, $s_port) = decrypt_params(@_);
  3343. my $command = "which php-cgi 2>&1;echo \$?";
  3344. my @cmdret = qx($command);
  3345. chomp(@cmdret);
  3346. my $ret = pop(@cmdret);
  3347. chomp($ret);
  3348. if ("X$ret" ne "X0")
  3349. {
  3350. return -1;
  3351. }
  3352. my $PHP_CGI = "@cmdret";
  3353. my $php_query_dir = Path::Class::Dir->new(AGENT_RUN_DIR, 'php-query');
  3354. if($protocol eq 'lgsl')
  3355. {
  3356. chdir($php_query_dir->subdir('lgsl'));
  3357. my $cmd = $PHP_CGI .
  3358. " -f lgsl_feed.php" .
  3359. " lgsl_type=" . $game_type .
  3360. " ip=" . $ip .
  3361. " c_port=" . $c_port .
  3362. " q_port=" . $q_port .
  3363. " s_port=" . $s_port .
  3364. " request=sp";
  3365. my $response = `$cmd`;
  3366. chomp($response);
  3367. chdir(AGENT_RUN_DIR);
  3368. if($response eq "FAILURE")
  3369. {
  3370. return -1;
  3371. }
  3372. return encode_base64($response, "");
  3373. }
  3374. elsif($protocol eq 'gameq')
  3375. {
  3376. chdir($php_query_dir->subdir('gameq'));
  3377. my $cmd = $PHP_CGI .
  3378. " -f gameq_feed.php" .
  3379. " game_type=" . $game_type .
  3380. " ip=" . $ip .
  3381. " c_port=" . $c_port .
  3382. " q_port=" . $q_port .
  3383. " s_port=" . $s_port;
  3384. my $response = `$cmd`;
  3385. chomp($response);
  3386. chdir(AGENT_RUN_DIR);
  3387. if($response eq "FAILURE")
  3388. {
  3389. return -1;
  3390. }
  3391. return encode_base64($response, "");
  3392. }
  3393. return -1;
  3394. }