ogp_agent.pl 119 KB

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