ogp_agent.pl 115 KB

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