ogp_agent.pl 97 KB

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