ogp_agent.pl 109 KB

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