ogp_agent.pl 101 KB

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