ogp_agent.pl 102 KB

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