ogp_agent.pl 117 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395
  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. my @server_pids;
  1124. # 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
  1125. if ($usedProtocolToStop == 1 && is_screen_running_without_decrypt(SCREEN_TYPE_HOME, $home_id) == 1){
  1126. @server_pids = get_home_pids($home_id);
  1127. my $timeWaited = 0;
  1128. my $pidSize = @server_pids;
  1129. my $maxWaitTime = 5;
  1130. # Maximum time to wait can now be configured as a preference
  1131. if(defined($Cfg::Preferences{protocol_shutdown_waittime}) && $Cfg::Preferences{protocol_shutdown_waittime} =~ /^\d+?$/){
  1132. $maxWaitTime = $Cfg::Preferences{protocol_shutdown_waittime};
  1133. }
  1134. while ($pidSize > 0 && $timeWaited < $maxWaitTime && is_screen_running_without_decrypt(SCREEN_TYPE_HOME, $home_id) == 1) {
  1135. select(undef, undef, undef, 0.25); # Sleeps for 250ms
  1136. # Add to time waited
  1137. $timeWaited += 0.25;
  1138. # Recheck server home PIDs
  1139. @server_pids = get_home_pids($home_id);
  1140. $pidSize = @server_pids;
  1141. }
  1142. }
  1143. if (is_screen_running_without_decrypt(SCREEN_TYPE_HOME, $home_id) == 0)
  1144. {
  1145. logger "Stopped server $server_ip:$server_port with rcon quit.";
  1146. return 0;
  1147. }
  1148. else
  1149. {
  1150. logger "Failed to send rcon quit. Stopping server with kill command.";
  1151. }
  1152. @server_pids = get_home_pids($home_id);
  1153. my $cnt;
  1154. foreach my $pid (@server_pids)
  1155. {
  1156. chomp($pid);
  1157. $cnt = kill 15, $pid;
  1158. if ($cnt != 1)
  1159. {
  1160. $cnt = kill 9, $pid;
  1161. if ($cnt == 1)
  1162. {
  1163. logger "Stopped process with pid $pid successfully using kill 9.";
  1164. }
  1165. else
  1166. {
  1167. logger "Process $pid can not be stopped.";
  1168. }
  1169. }
  1170. else
  1171. {
  1172. logger "Stopped process with pid $pid successfully using kill 15.";
  1173. }
  1174. }
  1175. system('screen -wipe > /dev/null 2>&1');
  1176. return 0;
  1177. }
  1178. else
  1179. {
  1180. logger "Remote control protocol not available or PASSWORD NOT SET. Using kill signal instead.";
  1181. my @server_pids = get_home_pids($home_id);
  1182. my $cnt;
  1183. foreach my $pid (@server_pids)
  1184. {
  1185. chomp($pid);
  1186. $cnt = kill 15, $pid;
  1187. if ($cnt != 1)
  1188. {
  1189. $cnt = kill 9, $pid;
  1190. if ($cnt == 1)
  1191. {
  1192. logger "Stopped process with pid $pid successfully using kill 9.";
  1193. }
  1194. else
  1195. {
  1196. logger "Process $pid can not be stopped.";
  1197. }
  1198. }
  1199. else
  1200. {
  1201. logger "Stopped process with pid $pid successfully using kill 15.";
  1202. }
  1203. }
  1204. system('screen -wipe > /dev/null 2>&1');
  1205. return 0;
  1206. }
  1207. }
  1208. ##### Send RCON command
  1209. ### Return 0 when error occurred on decryption.
  1210. ### Return 1 on success
  1211. sub send_rcon_command
  1212. {
  1213. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1214. my ($home_id, $server_ip, $server_port, $control_protocol,
  1215. $control_password, $control_type, $rconCommand) = decrypt_params(@_);
  1216. # legacy console
  1217. if ($control_protocol eq "lcon")
  1218. {
  1219. my $screen_id = create_screen_id(SCREEN_TYPE_HOME, $home_id);
  1220. system('screen -S '.$screen_id.' -p 0 -X stuff "'.$rconCommand.'$(printf \\\\r)"');
  1221. logger "Sending legacy console command to ".$screen_id.": \n$rconCommand \n .";
  1222. if ($? == -1)
  1223. {
  1224. my(@modedlines) = "$rconCommand";
  1225. my $encoded_content = encode_list(@modedlines);
  1226. return "1;" . $encoded_content;
  1227. }
  1228. return 0;
  1229. }
  1230. # Some validation checks for the variables.
  1231. if ($server_ip =~ /^\s*$/ || $server_port < 0 || $server_port > 65535)
  1232. {
  1233. logger("Invalid IP:Port given $server_ip:$server_port.");
  1234. return 0;
  1235. }
  1236. if ($control_password !~ /^\s*$/)
  1237. {
  1238. if ($control_protocol eq "rcon")
  1239. {
  1240. use KKrcon::KKrcon;
  1241. my $rcon = new KKrcon(
  1242. Password => $control_password,
  1243. Host => $server_ip,
  1244. Port => $server_port,
  1245. Type => $control_type
  1246. );
  1247. logger "Sending RCON command to $server_ip:$server_port: \n$rconCommand \n .";
  1248. my(@modedlines) = $rcon->execute($rconCommand);
  1249. my $encoded_content = encode_list(@modedlines);
  1250. return "1;" . $encoded_content;
  1251. }
  1252. elsif ($control_protocol eq "rcon2")
  1253. {
  1254. use KKrcon::HL2;
  1255. my $rcon2 = new HL2(
  1256. hostname => $server_ip,
  1257. port => $server_port,
  1258. password => $control_password,
  1259. timeout => 2
  1260. );
  1261. logger "Sending RCON command to $server_ip:$server_port: \n $rconCommand \n .";
  1262. my(@modedlines) = $rcon2->run($rconCommand);
  1263. my $encoded_content = encode_list(@modedlines);
  1264. return "1;" . $encoded_content;
  1265. }
  1266. elsif ($control_protocol eq "armabe")
  1267. {
  1268. use ArmaBE::ArmaBE;
  1269. my $armabe = new ArmaBE(
  1270. hostname => $server_ip,
  1271. port => $server_port, # Uses server port for now (Arma 2), Arma 3 BE uses a different, user definable port
  1272. password => $control_password,
  1273. timeout => 2
  1274. );
  1275. logger "Sending RCON command to $server_ip:$server_port: \n $rconCommand \n .";
  1276. my(@modedlines) = $armabe->run($rconCommand);
  1277. my $encoded_content = encode_list(@modedlines);
  1278. return "1;" . $encoded_content;
  1279. }
  1280. }
  1281. else
  1282. {
  1283. logger "Control protocol PASSWORD NOT SET.";
  1284. return -10;
  1285. }
  1286. }
  1287. ##### Returns a directory listing
  1288. ### @return List of directories if everything OK.
  1289. ### @return 0 If the directory is not found.
  1290. ### @return -1 If cannot open the directory.
  1291. sub dirlist
  1292. {
  1293. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1294. my ($datadir) = &decrypt_param(@_);
  1295. logger "Asked for dirlist of $datadir directory.";
  1296. if (!-d $datadir)
  1297. {
  1298. logger "ERROR - Directory [ $datadir ] not found!";
  1299. return -1;
  1300. }
  1301. if (!opendir(DIR, $datadir))
  1302. {
  1303. logger "ERROR - Can't open $datadir: $!";
  1304. return -2;
  1305. }
  1306. my @dirlist = readdir(DIR);
  1307. closedir(DIR);
  1308. return join(";", @dirlist);
  1309. }
  1310. ##### Returns a directory listing with extra info the filemanager
  1311. ### @return List of directories if everything OK.
  1312. ### @return 1 If the directory is empty.
  1313. ### @return -1 If the directory is not found.
  1314. ### @return -2 If cannot open the directory.
  1315. sub dirlistfm
  1316. {
  1317. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1318. my $datadir = &decrypt_param(@_);
  1319. logger "Asked for dirlist of $datadir directory.";
  1320. if (!-d $datadir)
  1321. {
  1322. logger "ERROR - Directory [ $datadir ] not found!";
  1323. return -1;
  1324. }
  1325. if (!opendir(DIR, $datadir))
  1326. {
  1327. logger "ERROR - Can't open $datadir: $!";
  1328. return -2;
  1329. }
  1330. my $dir = $datadir;
  1331. $dir =~ s/('+)/'"$1"'/g;
  1332. my $lsattr = `lsattr '$dir' 2>/dev/null`;
  1333. my @attr_all = split /\n+/, $lsattr;
  1334. my %attr = ();
  1335. my ($a, $p, @f);
  1336. foreach (@attr_all)
  1337. {
  1338. ($a, $p) = split(/\s/, $_, 2);
  1339. @f = split /\//, $p;
  1340. $attr{$f[-1]} = $a;
  1341. }
  1342. my %dirfiles = ();
  1343. my (
  1344. $dev, $ino, $mode, $nlink, $uid, $gid, $rdev,
  1345. $size, $atime, $mtime, $ctime, $blksize, $blocks
  1346. );
  1347. my $count = 0;
  1348. chdir($datadir);
  1349. while (my $item = readdir(DIR))
  1350. {
  1351. #skip the . and .. special dirs
  1352. next if $item eq '.';
  1353. next if $item eq '..';
  1354. #print "Dir list is" . $item."\n";
  1355. #Stat the file to get ownership and size
  1356. (
  1357. $dev, $ino, $mode, $nlink, $uid, $gid, $rdev,
  1358. $size, $atime, $mtime, $ctime, $blksize, $blocks
  1359. ) = stat($item);
  1360. if(defined $uid)
  1361. {
  1362. $uid = getpwuid($uid);
  1363. }
  1364. else
  1365. {
  1366. $uid = '';
  1367. }
  1368. if(defined $gid)
  1369. {
  1370. $gid = getgrgid($gid);
  1371. }
  1372. else
  1373. {
  1374. $gid = '';
  1375. }
  1376. #This if else logic determines what it is, File, Directory, other
  1377. if (-T $item)
  1378. {
  1379. # print "File\n";
  1380. $dirfiles{'files'}{$count}{'filename'} = encode_base64($item);
  1381. $dirfiles{'files'}{$count}{'size'} = $size;
  1382. $dirfiles{'files'}{$count}{'user'} = $uid;
  1383. $dirfiles{'files'}{$count}{'group'} = $gid;
  1384. $dirfiles{'files'}{$count}{'attr'} = $attr{$item};
  1385. }
  1386. elsif (-d $item)
  1387. {
  1388. # print "Dir\n";
  1389. $dirfiles{'directorys'}{$count}{'filename'} = encode_base64($item);
  1390. $dirfiles{'directorys'}{$count}{'size'} = $size;
  1391. $dirfiles{'directorys'}{$count}{'user'} = $uid;
  1392. $dirfiles{'directorys'}{$count}{'group'} = $gid;
  1393. }
  1394. elsif (-B $item)
  1395. {
  1396. #print "File\n";
  1397. $dirfiles{'binarys'}{$count}{'filename'} = encode_base64($item);
  1398. $dirfiles{'binarys'}{$count}{'size'} = $size;
  1399. $dirfiles{'binarys'}{$count}{'user'} = $uid;
  1400. $dirfiles{'binarys'}{$count}{'group'} = $gid;
  1401. $dirfiles{'binarys'}{$count}{'attr'} = $attr{$item};
  1402. }
  1403. else
  1404. {
  1405. #print "Unknown\n"
  1406. #will be listed as common files;
  1407. $dirfiles{'files'}{$count}{'filename'} = encode_base64($item);
  1408. $dirfiles{'files'}{$count}{'size'} = $size;
  1409. $dirfiles{'files'}{$count}{'user'} = $uid;
  1410. $dirfiles{'files'}{$count}{'group'} = $gid;
  1411. $dirfiles{'files'}{$count}{'attr'} = $attr{$item};
  1412. }
  1413. $count++;
  1414. }
  1415. closedir(DIR);
  1416. if ($count eq 0)
  1417. {
  1418. logger "Empty directory $datadir.";
  1419. return 1;
  1420. }
  1421. chdir AGENT_RUN_DIR;
  1422. #Now we return it to the webpage, as array
  1423. return {%dirfiles};
  1424. }
  1425. ###### Returns the contents of a text file
  1426. sub readfile
  1427. {
  1428. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1429. chdir AGENT_RUN_DIR;
  1430. my $userfile = &decrypt_param(@_);
  1431. unless ( -e $userfile )
  1432. {
  1433. if (open(BLANK, '>', $userfile))
  1434. {
  1435. close(BLANK);
  1436. }
  1437. }
  1438. if (!open(USERFILE, '<', $userfile))
  1439. {
  1440. logger "ERROR - Can't open file $userfile for reading.";
  1441. return -1;
  1442. }
  1443. my ($wholefile, $buf);
  1444. while (read(USERFILE, $buf, 60 * 57))
  1445. {
  1446. $wholefile .= encode_base64($buf);
  1447. }
  1448. close(USERFILE);
  1449. if(!defined $wholefile)
  1450. {
  1451. return "1; ";
  1452. }
  1453. return "1;" . $wholefile;
  1454. }
  1455. ###### Backs up file, then writes data to new file
  1456. ### @return 1 On success
  1457. ### @return 0 In case of a failure
  1458. sub writefile
  1459. {
  1460. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1461. chdir AGENT_RUN_DIR;
  1462. # $writefile = file we're editing, $filedata = the contents were writing to it
  1463. my ($writefile, $filedata) = &decrypt_params(@_);
  1464. if (!-e $writefile)
  1465. {
  1466. open FILE, ">", $writefile;
  1467. }
  1468. else
  1469. {
  1470. # backup the existing file
  1471. logger
  1472. "Backing up file $writefile to $writefile.bak before writing new data.";
  1473. if (!copy("$writefile", "$writefile.bak"))
  1474. {
  1475. logger
  1476. "ERROR - Failed to backup $writefile to $writefile.bak. Error: $!";
  1477. return 0;
  1478. }
  1479. }
  1480. if (!-w $writefile)
  1481. {
  1482. logger "ERROR - File [ $writefile ] is not writeable!";
  1483. return 0;
  1484. }
  1485. if (!open(WRITER, '>', $writefile))
  1486. {
  1487. logger "ERROR - Failed to open $writefile for writing.";
  1488. return 0;
  1489. }
  1490. $filedata = decode_base64($filedata);
  1491. $filedata =~ s/\r//g;
  1492. print WRITER "$filedata";
  1493. close(WRITER);
  1494. logger "Wrote $writefile successfully!";
  1495. return 1;
  1496. }
  1497. ###### Reboots the server remotely through panel
  1498. ### @return 1 On success
  1499. ### @return 0 In case of a failure
  1500. sub rebootnow
  1501. {
  1502. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1503. sudo_exec_without_decrypt('sleep 10s; shutdown -r now');
  1504. logger "Scheduled system reboot to occur in 10 seconds successfully!";
  1505. return 1;
  1506. }
  1507. # Determine the os of the agent machine.
  1508. sub what_os
  1509. {
  1510. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1511. logger "Asking for OS type";
  1512. my $which_uname = `which uname`;
  1513. chomp $which_uname;
  1514. if ($which_uname ne "")
  1515. {
  1516. my $os;
  1517. my $os_name;
  1518. my $os_arch;
  1519. my $wine_ver = "";
  1520. $os_name = `$which_uname`;
  1521. chomp $os_name;
  1522. $os_arch = `$which_uname -m`;
  1523. chomp $os_arch;
  1524. my $which_wine = `which wine`;
  1525. chomp $which_wine;
  1526. if ($which_wine ne "")
  1527. {
  1528. $wine_ver = `$which_wine --version`;
  1529. chomp $wine_ver;
  1530. $wine_ver = "|".$wine_ver;
  1531. }
  1532. $os = $os_name." ".$os_arch.$wine_ver;
  1533. logger "OS is $os";
  1534. return "$os";
  1535. }
  1536. else
  1537. {
  1538. logger "Cannot determine OS..that is odd";
  1539. return "Unknown";
  1540. }
  1541. }
  1542. ### @return PID of the download process if started succesfully.
  1543. ### @return -1 If could not create temporary download directory.
  1544. ### @return -2 If could not create destination directory.
  1545. ### @return -3 If resources unavailable.
  1546. sub start_file_download
  1547. {
  1548. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1549. my ($url, $destination, $filename, $action, $post_script) = &decrypt_params(@_);
  1550. logger
  1551. "Starting to download URL $url. Destination: $destination - Filename: $filename";
  1552. if (!-e $destination)
  1553. {
  1554. logger "Creating destination directory.";
  1555. if (!mkpath $destination )
  1556. {
  1557. logger "Could not create destination '$destination' directory : $!";
  1558. return -2;
  1559. }
  1560. }
  1561. my $download_file_path = Path::Class::File->new($destination, "$filename");
  1562. my $pid = fork();
  1563. if (not defined $pid)
  1564. {
  1565. logger "Could not allocate resources for download.";
  1566. return -3;
  1567. }
  1568. # Only the forked child goes here.
  1569. elsif ($pid == 0)
  1570. {
  1571. my $ua = LWP::UserAgent->new( ssl_opts => { verify_hostname => 0,
  1572. SSL_verify_mode => 0x00 } );
  1573. $ua->agent('Mozilla/5.0');
  1574. my $response = $ua->get($url, ':content_file' => "$download_file_path");
  1575. if ($response->is_success)
  1576. {
  1577. logger "Successfully fetched $url and stored it to $download_file_path. Retval: ".$response->status_line;
  1578. if (!-e $download_file_path)
  1579. {
  1580. logger "File $download_file_path does not exist.";
  1581. exit(0);
  1582. }
  1583. if ($action eq "uncompress")
  1584. {
  1585. logger "Starting file uncompress as ordered.";
  1586. uncompress_file_without_decrypt($download_file_path,
  1587. $destination);
  1588. }
  1589. # Run post scripts if any
  1590. if ($post_script ne "")
  1591. {
  1592. logger "Running postscript commands.";
  1593. my @postcmdlines = split /[\r\n]+/, $post_script;
  1594. my $postcmdfile = $destination."/".'postinstall.sh';
  1595. open FILE, '>', $postcmdfile;
  1596. print FILE "cd $destination\n";
  1597. foreach my $line (@postcmdlines) {
  1598. logger "Postscript command received \"" . $line ."\".";
  1599. if(handle_lock_command_line($line) == 0){
  1600. print FILE "$line\n";
  1601. }else{
  1602. logger "Lock command completed successfully";
  1603. }
  1604. }
  1605. print FILE "rm -f $destination/postinstall.sh\n";
  1606. close FILE;
  1607. chmod 0755, $postcmdfile;
  1608. my $screen_id = create_screen_id("post_script", $$);
  1609. my $cli_bin = create_screen_cmd($screen_id, "bash $postcmdfile");
  1610. system($cli_bin);
  1611. }
  1612. }
  1613. else
  1614. {
  1615. logger
  1616. "Unable to fetch $url, or save to $download_file_path. Retval: ".$response->status_line;
  1617. exit(0);
  1618. }
  1619. # Child process must exit.
  1620. exit(0);
  1621. }
  1622. else
  1623. {
  1624. logger "Download process for $download_file_path has pid number $pid.";
  1625. return "$pid";
  1626. }
  1627. }
  1628. sub lock_additional_files{
  1629. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1630. my ($homedir, $files, $action) = &decrypt_params(@_);
  1631. return lock_additional_files_logic($homedir, $files, $action);
  1632. }
  1633. sub lock_additional_files_logic{
  1634. my ($homedir, $filesToLock, $action, $returnType) = @_;
  1635. logger "Locking additional files specified in the XML.";
  1636. my $commandStr = "";
  1637. $filesToLock = startup_comma_format_to_multiline($filesToLock);
  1638. $filesToLock = replace_OGP_Env_Vars("", "", $homedir, $filesToLock);
  1639. my @filesToProcess = split /[\r\n]+/, $filesToLock;
  1640. foreach my $line (@filesToProcess) {
  1641. my $fullPath = $homedir . "/" . $line;
  1642. if($action eq "lock"){
  1643. if(defined $returnType && $returnType eq "str"){
  1644. $commandStr .= "echo '".$SUDOPASSWD."' | sudo -S -p \" \" sh -c \"" . secure_path_without_decrypt("chattr+i", $fullPath, $returnType) . "\" > /dev/null 2>&1" . "\n";
  1645. $commandStr .= "echo '".$SUDOPASSWD."' | sudo -S -p \" \" sh -c \"" . secure_path_without_decrypt("chattr+i", $line, $returnType) . "\" > /dev/null 2>&1" . "\n";
  1646. }else{
  1647. secure_path_without_decrypt("chattr+i", $fullPath);
  1648. secure_path_without_decrypt("chattr+i", $line);
  1649. }
  1650. }else{
  1651. if(defined $returnType && $returnType eq "str"){
  1652. $commandStr .= "echo '".$SUDOPASSWD."' | sudo -S -p \" \" sh -c \"" . secure_path_without_decrypt("chattr-i", $fullPath, $returnType) . "\" > /dev/null 2>&1" . "\n";
  1653. $commandStr .= "echo '".$SUDOPASSWD."' | sudo -S -p \" \" sh -c \"" . secure_path_without_decrypt("chattr-i", $line, $returnType) . "\" > /dev/null 2>&1" . "\n";
  1654. }else{
  1655. secure_path_without_decrypt("chattr-i", $fullPath);
  1656. secure_path_without_decrypt("chattr-i", $line);
  1657. }
  1658. }
  1659. }
  1660. if($commandStr ne ""){
  1661. return $commandStr;
  1662. }
  1663. return "";
  1664. }
  1665. sub run_before_start_commands
  1666. {
  1667. #return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1668. my ($server_id, $homedir, $beforestartcmd) = @_;
  1669. if ($homedir ne "" && $server_id ne ""){
  1670. # Run any prestart scripts
  1671. if (defined $beforestartcmd && $beforestartcmd ne "")
  1672. {
  1673. logger "Running pre-start XML commands before starting server ID $server_id with a home directory of $homedir.";
  1674. my @prestartcmdlines = split /[\r\n]+/, $beforestartcmd;
  1675. my $prestartcmdfile = $homedir."/".'prestart_ogp.sh';
  1676. open FILE, '>', $prestartcmdfile;
  1677. print FILE "#!/bin/bash" . "\n";
  1678. print FILE "cd $homedir\n";
  1679. foreach my $line (@prestartcmdlines) {
  1680. print FILE "$line\n";
  1681. }
  1682. print FILE "rm -f $prestartcmdfile\n";
  1683. close FILE;
  1684. chmod 0755, $prestartcmdfile;
  1685. system("bash $prestartcmdfile");
  1686. }
  1687. }else{
  1688. return -2;
  1689. }
  1690. return 1;
  1691. }
  1692. sub multiline_to_startup_comma_format{
  1693. my ($multiLineVar) = @_;
  1694. $multiLineVar =~ s/,//g; # commas are invalid anyways in bash
  1695. $multiLineVar =~ s/[\r]+//g;
  1696. $multiLineVar =~ s/[\n]+/{OGPNEWLINE}/g;
  1697. return $multiLineVar;
  1698. }
  1699. sub multiline_to_bash_commands{
  1700. my ($multiLineVar) = @_;
  1701. $multiLineVar =~ s/[\n]+/ && /g;
  1702. return $multiLineVar;
  1703. }
  1704. sub startup_comma_format_to_multiline{
  1705. my ($multiLineVar) = @_;
  1706. $multiLineVar =~ s/{OGPNEWLINE}/\n/g;
  1707. return $multiLineVar;
  1708. }
  1709. sub create_secure_script
  1710. {
  1711. my ($home_path, $exec_folder_path, $exec_path) = @_;
  1712. secure_path_without_decrypt('chattr-i', $home_path);
  1713. my $secure = "$home_path/secure.sh";
  1714. $home_path =~ s/('+)/'\"$1\"'/g;
  1715. $exec_folder_path =~ s/('+)/'\"$1\"'/g;
  1716. $exec_path =~ s/('+)/'\"$1\"'/g;
  1717. my $sec = $secure;
  1718. $sec =~ s/('+)/'\"$1\"'/g;
  1719. open FILE, '>', $secure;
  1720. print FILE "chmod 771 '$exec_folder_path'\n".
  1721. "chmod 750 '$exec_path'\n".
  1722. "chmod +x '$exec_path'\n".
  1723. "chattr +i '$exec_path'\n".
  1724. "rm -f '$sec'";
  1725. close FILE;
  1726. chmod 0770, $secure;
  1727. sudo_exec_without_decrypt("chown 0:0 '$sec'");
  1728. return 0;
  1729. }
  1730. sub check_b4_chdir
  1731. {
  1732. my ( $path ) = @_;
  1733. my $uid = `id -u`;
  1734. chomp $uid;
  1735. my $gid = `id -g`;
  1736. chomp $gid;
  1737. if (!-e $path)
  1738. {
  1739. logger "$path does not exist yet. Trying to create it...";
  1740. eval { mkpath($path); 1 } or logger "Error creating $path with Perl mkpath command. Errno: $! - Trying again with sudo...";
  1741. if (!-e $path)
  1742. {
  1743. sudo_exec_without_decrypt('mkdir -p ' . $path);
  1744. }
  1745. if (!-e $path)
  1746. {
  1747. return -1;
  1748. }
  1749. # Set perms on it as well
  1750. sudo_exec_without_decrypt('chown -Rf '.$uid.':'.$gid.' \''.$path.'\'');
  1751. }
  1752. else
  1753. {
  1754. # File or directory already exists
  1755. # Make sure it's owned by the agent
  1756. secure_path_without_decrypt('chattr-i', $path);
  1757. }
  1758. if (!chdir $path)
  1759. {
  1760. logger "Unable to change dir to '$path'.";
  1761. return -1;
  1762. }
  1763. return 0;
  1764. }
  1765. sub create_bash_scripts
  1766. {
  1767. my ( $home_path, $bash_scripts_path, $precmd, $postcmd, @installcmds ) = @_;
  1768. $home_path =~ s/('+)/'\"$1\"'/g;
  1769. $bash_scripts_path =~ s/('+)/'\"$1\"'/g;
  1770. my @precmdlines = split /[\r\n]+/, $precmd;
  1771. my $precmdfile = 'preinstall.sh';
  1772. open FILE, '>', $precmdfile;
  1773. print FILE "cd '$home_path'\n";
  1774. foreach my $line (@precmdlines) {
  1775. print FILE "$line\n";
  1776. }
  1777. close FILE;
  1778. chmod 0755, $precmdfile;
  1779. my @postcmdlines = split /[\r\n]+/, $postcmd;
  1780. my $postcmdfile = 'postinstall.sh';
  1781. open FILE, '>', $postcmdfile;
  1782. print FILE "cd '$home_path'\n";
  1783. foreach my $line (@postcmdlines) {
  1784. print FILE "$line\n";
  1785. }
  1786. print FILE "cd '$home_path'\n".
  1787. "echo '".$SUDOPASSWD."' | sudo -S -p \" \" bash secure.sh\n".
  1788. "rm -f secure.sh\n".
  1789. "cd '$bash_scripts_path'\n".
  1790. "rm -f preinstall.sh\n".
  1791. "rm -f postinstall.sh\n".
  1792. "rm -f runinstall.sh\n";
  1793. close FILE;
  1794. chmod 0755, $postcmdfile;
  1795. my $installfile = 'runinstall.sh';
  1796. open FILE, '>', $installfile;
  1797. print FILE "#!/bin/bash\n".
  1798. "cd '$bash_scripts_path'\n".
  1799. "./$precmdfile\n";
  1800. foreach my $installcmd (@installcmds)
  1801. {
  1802. print FILE "$installcmd\n";
  1803. }
  1804. print FILE "wait ".'${!}'."\n".
  1805. "cd '$bash_scripts_path'\n".
  1806. "./$postcmdfile\n";
  1807. close FILE;
  1808. chmod 0755, $installfile;
  1809. return $installfile;
  1810. }
  1811. #### Run the rsync update ####
  1812. ### @return 1 If update started
  1813. ### @return 0 In error case.
  1814. sub start_rsync_install
  1815. {
  1816. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1817. my ($home_id, $home_path, $url, $exec_folder_path, $exec_path, $precmd, $postcmd, $filesToLockUnlock) = decrypt_params(@_);
  1818. if ( check_b4_chdir($home_path) != 0)
  1819. {
  1820. return 0;
  1821. }
  1822. secure_path_without_decrypt('chattr-i', $home_path);
  1823. create_secure_script($home_path, $exec_folder_path, $exec_path);
  1824. my $bash_scripts_path = MANUAL_TMP_DIR . "/home_id_" . $home_id;
  1825. if ( check_b4_chdir($bash_scripts_path) != 0)
  1826. {
  1827. return 0;
  1828. }
  1829. # Rsync install require the rsync binary to exist in the system
  1830. # to enable this functionality.
  1831. my $rsync_binary = Path::Class::File->new("/usr/bin", "rsync");
  1832. if (!-f $rsync_binary)
  1833. {
  1834. logger "Failed to start rsync update from "
  1835. . $url
  1836. . " to $home_path. Error: Rsync client not installed.";
  1837. return 0;
  1838. }
  1839. my $screen_id = create_screen_id(SCREEN_TYPE_UPDATE, $home_id);
  1840. my $log_file = Path::Class::File->new(SCREEN_LOGS_DIR, "screenlog.$screen_id");
  1841. if(defined $filesToLockUnlock && $filesToLockUnlock ne ""){
  1842. $postcmd .= "\n" . lock_additional_files_logic($home_path, $filesToLockUnlock, "lock", "str");
  1843. }
  1844. backup_home_log( $home_id, $log_file );
  1845. my $path = $home_path;
  1846. $path =~ s/('+)/'\"$1\"'/g;
  1847. my @installcmds = ("/usr/bin/rsync --log-file='" . AGENT_RSYNC_GENERIC_LOG . "' --archive --compress --copy-links --update --verbose rsync://$url '$path'");
  1848. my $installfile = create_bash_scripts( $home_path, $bash_scripts_path, $precmd, $postcmd, @installcmds );
  1849. my $screen_cmd = create_screen_cmd($screen_id, "./$installfile");
  1850. logger "Running rsync update: /usr/bin/rsync --log-file='" . AGENT_RSYNC_GENERIC_LOG . "' --archive --compress --copy-links --update --verbose rsync://$url '$home_path'";
  1851. system($screen_cmd);
  1852. chdir AGENT_RUN_DIR;
  1853. return 1;
  1854. }
  1855. ### @return PID of the download process if started succesfully.
  1856. ### @return -1 If could not create temporary download directory.
  1857. ### @return -2 If could not create destination directory.
  1858. ### @return -3 If resources unavailable.
  1859. sub master_server_update
  1860. {
  1861. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1862. my ($home_id,$home_path,$ms_home_id,$ms_home_path,$exec_folder_path,$exec_path,$precmd,$postcmd) = decrypt_params(@_);
  1863. if ( check_b4_chdir($home_path) != 0)
  1864. {
  1865. return 0;
  1866. }
  1867. secure_path_without_decrypt('chattr-i', $home_path);
  1868. create_secure_script($home_path, $exec_folder_path, $exec_path);
  1869. my $bash_scripts_path = MANUAL_TMP_DIR . "/home_id_" . $home_id;
  1870. if ( check_b4_chdir($bash_scripts_path) != 0)
  1871. {
  1872. return 0;
  1873. }
  1874. my $screen_id = create_screen_id(SCREEN_TYPE_UPDATE, $home_id);
  1875. my $log_file = Path::Class::File->new(SCREEN_LOGS_DIR, "screenlog.$screen_id");
  1876. backup_home_log( $home_id, $log_file );
  1877. my $my_home_path = $home_path;
  1878. $my_home_path =~ s/('+)/'\"$1\"'/g;
  1879. $exec_path =~ s/\Q$home_path\E//g;
  1880. $exec_path =~ s/^\///g;
  1881. $exec_path =~ s/('+)/'\"$1\"'/g;
  1882. $ms_home_path =~ s/('+)/'\"$1\"'/g;
  1883. my @installcmds = ("cd '$ms_home_path'");
  1884. ## Copy files that match the extensions listed at extPatterns.txt
  1885. open(EXT_PATTERNS, '<', Path::Class::File->new(AGENT_RUN_DIR, "extPatterns.txt"))
  1886. || logger "Error reading patterns file $!";
  1887. my @ext_paterns = <EXT_PATTERNS>;
  1888. foreach my $patern (@ext_paterns)
  1889. {
  1890. chop $patern;
  1891. push (@installcmds, "find -iname \\\*.$patern -exec cp -Rfp --parents {} '$my_home_path'/ \\\;");
  1892. }
  1893. close EXT_PATTERNS;
  1894. ## Copy the server executable so it can be secured with chattr +i
  1895. push (@installcmds, "cp -vf --parents '$exec_path' '$my_home_path'");
  1896. ## Do symlinks for each of the other files
  1897. push (@installcmds, "cp -vuRfs '$ms_home_path'/* '$my_home_path'");
  1898. my $installfile = create_bash_scripts( $home_path, $bash_scripts_path, $precmd, $postcmd, @installcmds );
  1899. my $screen_cmd = create_screen_cmd($screen_id, "./$installfile");
  1900. logger "Running master server update from home ID $home_id to home ID $ms_home_id";
  1901. system($screen_cmd);
  1902. chdir AGENT_RUN_DIR;
  1903. return 1;
  1904. }
  1905. sub steam_cmd
  1906. {
  1907. chomp(@_);
  1908. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1909. return steam_cmd_without_decrypt(decrypt_params(@_));
  1910. }
  1911. #### Run the steam client ####
  1912. ### @return 1 If update started
  1913. ### @return 0 In error case.
  1914. sub steam_cmd_without_decrypt
  1915. {
  1916. my ($home_id, $home_path, $mod, $modname, $betaname, $betapwd, $user, $pass, $guard, $exec_folder_path, $exec_path, $precmd, $postcmd, $cfg_os, $filesToLockUnlock, $arch_bits) = @_;
  1917. if ( check_b4_chdir($home_path) != 0)
  1918. {
  1919. return 0;
  1920. }
  1921. secure_path_without_decrypt('chattr-i', $home_path);
  1922. create_secure_script($home_path, $exec_folder_path, $exec_path);
  1923. my $bash_scripts_path = MANUAL_TMP_DIR . "/home_id_" . $home_id;
  1924. if ( check_b4_chdir($bash_scripts_path) != 0)
  1925. {
  1926. return 0;
  1927. }
  1928. my $screen_id = create_screen_id(SCREEN_TYPE_UPDATE, $home_id);
  1929. my $screen_id_for_txt_update = substr ($screen_id, rindex($screen_id, '_') + 1);
  1930. my $steam_binary = Path::Class::File->new(STEAMCMD_CLIENT_DIR, "steamcmd.sh");
  1931. my $installSteamFile = $screen_id_for_txt_update . "_install.txt";
  1932. my $installtxt = Path::Class::File->new(STEAMCMD_CLIENT_DIR, $installSteamFile);
  1933. open FILE, '>', $installtxt;
  1934. print FILE "\@ShutdownOnFailedCommand 1\n";
  1935. print FILE "\@NoPromptForPassword 1\n";
  1936. if($cfg_os eq 'windows')
  1937. {
  1938. print FILE "\@sSteamCmdForcePlatformType windows\n";
  1939. }
  1940. # Handle requested SteamCMD architecture
  1941. if(defined $arch_bits && $arch_bits ne ""){
  1942. print FILE "\@sSteamCmdForcePlatformBitness " . $arch_bits . "\n";
  1943. }
  1944. if(defined STEAM_DL_LIMIT && STEAM_DL_LIMIT ne "" && is_integer(STEAM_DL_LIMIT) && STEAM_DL_LIMIT > 0){
  1945. print FILE "set_download_throttle " . STEAM_DL_LIMIT . "\n";
  1946. }
  1947. if($guard ne '')
  1948. {
  1949. print FILE "set_steam_guard_code $guard\n";
  1950. }
  1951. if($user ne '' && $user ne 'anonymous')
  1952. {
  1953. print FILE "login $user $pass\n";
  1954. }
  1955. else
  1956. {
  1957. print FILE "login anonymous\n";
  1958. }
  1959. print FILE "force_install_dir \"$home_path\"\n";
  1960. if($modname ne "")
  1961. {
  1962. print FILE "app_set_config $mod mod $modname\n";
  1963. print FILE "app_update $mod mod $modname validate\n";
  1964. }
  1965. if($betaname ne "" && $betapwd ne "")
  1966. {
  1967. print FILE "app_update $mod -beta $betaname -betapassword $betapwd\n";
  1968. }
  1969. elsif($betaname ne "" && $betapwd eq "")
  1970. {
  1971. print FILE "app_update $mod -beta $betaname\n";
  1972. }
  1973. else
  1974. {
  1975. print FILE "app_update $mod\n";
  1976. }
  1977. print FILE "exit\n";
  1978. close FILE;
  1979. my $log_file = Path::Class::File->new(SCREEN_LOGS_DIR, "screenlog.$screen_id");
  1980. backup_home_log( $home_id, $log_file );
  1981. my $postcmd_mod = $postcmd;
  1982. if(defined $filesToLockUnlock && $filesToLockUnlock ne ""){
  1983. $postcmd_mod .= "\n" . lock_additional_files_logic($home_path, $filesToLockUnlock, "lock", "str");
  1984. }
  1985. my @installcmds = ("$steam_binary +runscript $installtxt +exit");
  1986. my $installfile = create_bash_scripts( $home_path, $bash_scripts_path, $precmd, $postcmd_mod, @installcmds );
  1987. my $screen_cmd = create_screen_cmd($screen_id, "./$installfile");
  1988. logger "Running steam update: $steam_binary +runscript $installtxt +exit";
  1989. system($screen_cmd);
  1990. return 1;
  1991. }
  1992. sub fetch_steam_version
  1993. {
  1994. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1995. my ($appId, $pureOutput) = &decrypt_params(@_);
  1996. my $steam_binary = Path::Class::File->new(STEAMCMD_CLIENT_DIR, "steamcmd.sh");
  1997. my $steam_options = "+login anonymous +app_info_update 1 +app_info_print \"$appId\" +quit";
  1998. 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';
  1999. logger "Getting latest version info for AppId $appId";
  2000. my $response = `$steam_binary $steam_options $grep`;
  2001. return $response;
  2002. }
  2003. sub installed_steam_version
  2004. {
  2005. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2006. my ($game_home, $mod, $pureOutput) = &decrypt_params(@_);
  2007. my $appFile = $game_home."/steamapps/appmanifest_$mod.acf";
  2008. my $grep = $pureOutput != "0" ? "" : '| grep buildid | tr \'[:blank:]"\' \' \' | tr -s \' \' | cut -d\' \' -f3';
  2009. if ( ! -f $appFile)
  2010. {
  2011. return "-10";
  2012. }
  2013. return `cat $appFile $grep`;
  2014. }
  2015. sub automatic_steam_update
  2016. {
  2017. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2018. my ($home_id, $game_home, $server_ip, $server_port, $exec_path, $exec_folder_path,
  2019. $control_protocol, $control_password, $control_type,
  2020. $appId, $modname, $betaname, $betapwd, $user, $pass, $guard, $precmd, $postcmd, $cfg_os, $filesToLockUnlock,
  2021. $startup_cmd, $cpu, $nice, $preStart, $envVars, $game_key, $arch_bits, $console_log) = &decrypt_params(@_);
  2022. # Is the server currently running? if it is, we'll try to start it after updating.
  2023. my $isServerRunning = is_screen_running_without_decrypt(SCREEN_TYPE_HOME, $home_id) == 1 ? 1 : 0;
  2024. # Check if an update is already happening.
  2025. if (is_screen_running_without_decrypt(SCREEN_TYPE_UPDATE, $home_id) == 1)
  2026. {
  2027. logger("Update already running for server $home_id, unable to start automatic update.");
  2028. return -10;
  2029. }
  2030. # Stop the server if it's running.
  2031. if ($isServerRunning == 1)
  2032. {
  2033. logger("Stopping server $home_id for automatic update.");
  2034. if (stop_server_without_decrypt($home_id, $server_ip, $server_port, $control_protocol, $control_password, $control_type, $game_home) != 0)
  2035. {
  2036. logger("Failed to stop server $home_id for automatic update. Exiting update procedure.");
  2037. return -9
  2038. }
  2039. }
  2040. # 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.
  2041. 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)
  2042. {
  2043. logger("Failed to start steam_cmd for server $home_id.");
  2044. return -8;
  2045. } else {
  2046. if ($isServerRunning == 1)
  2047. {
  2048. while (1)
  2049. {
  2050. # If the update screen for $home_id isn't running, attempt to start the server.
  2051. if (is_screen_running_without_decrypt(SCREEN_TYPE_UPDATE, $home_id) == 0)
  2052. {
  2053. 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)
  2054. {
  2055. logger("Failed to start server $home_id after automatic update.");
  2056. return -7;
  2057. } else {
  2058. logger("Starting server $home_id after automatic update.");
  2059. return 1;
  2060. }
  2061. last;
  2062. }
  2063. sleep 5;
  2064. }
  2065. } else {
  2066. # Update was started, but server wasn't initially running.
  2067. return 2;
  2068. }
  2069. }
  2070. }
  2071. sub rsync_progress
  2072. {
  2073. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2074. my ($running_home) = &decrypt_param(@_);
  2075. logger "User requested progress on rsync job on home $running_home.";
  2076. if (-r $running_home)
  2077. {
  2078. $running_home =~ s/('+)/'"$1"'/g;
  2079. my $progress = `du -sk '$running_home'`;
  2080. chomp($progress);
  2081. my ($bytes, $junk) = split(/\s+/, $progress);
  2082. logger("Found $bytes and $junk");
  2083. return $bytes;
  2084. }
  2085. return "0";
  2086. }
  2087. sub is_file_download_in_progress
  2088. {
  2089. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2090. my ($pid) = &decrypt_param(@_);
  2091. logger "User requested if download is in progress with pid $pid.";
  2092. my @pids = `ps -ef`;
  2093. @pids = grep(/$pid/, @pids);
  2094. logger "Number of pids for file download: @pids";
  2095. if (@pids > '0')
  2096. {
  2097. return 1;
  2098. }
  2099. return 0;
  2100. }
  2101. ### \return 1 If file is uncompressed succesfully.
  2102. ### \return 0 If file does not exist.
  2103. ### \return -1 If file could not be uncompressed.
  2104. sub uncompress_file
  2105. {
  2106. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2107. return uncompress_file_without_decrypt(decrypt_params(@_));
  2108. }
  2109. sub uncompress_file_without_decrypt
  2110. {
  2111. # Globals
  2112. $Archive::Extract::PREFER_BIN = 1;
  2113. # File must include full path.
  2114. my ($file, $destination) = @_;
  2115. logger "Uncompression called for file $file to dir $destination.";
  2116. if (!-e $file)
  2117. {
  2118. logger "File $file could not be found for uncompression.";
  2119. return 0;
  2120. }
  2121. if (!-e $destination)
  2122. {
  2123. mkpath($destination, {error => \my $err});
  2124. if (@$err)
  2125. {
  2126. logger "Failed to create destination dir $destination.";
  2127. return 0;
  2128. }
  2129. }
  2130. my $filesize = (stat($file))[7];
  2131. if($filesize >= 3221225472 && $file =~ /\.zip$/i){
  2132. # Archive::Extract seems to have problems with large zip files, so for files greater than 3GB in size, let the system handle it
  2133. logger "Using system call to unzip.";
  2134. system("unzip -o $file -d $destination");
  2135. if($? != 0){
  2136. logger "Done.";
  2137. return -1;
  2138. }
  2139. }else{
  2140. my $ae = Archive::Extract->new(archive => $file);
  2141. if (!$ae)
  2142. {
  2143. logger "Could not create archive instance for file $file.";
  2144. return -1;
  2145. }
  2146. my $ok = $ae->extract(to => $destination);
  2147. if (!$ok)
  2148. {
  2149. logger "File $file could not be uncompressed.";
  2150. return -1;
  2151. }
  2152. logger "File uncompressed/extracted successfully.";
  2153. }
  2154. return 1;
  2155. }
  2156. ### \return 1 If files are compressed succesfully.
  2157. ### \return -1 If files could not be compressed.
  2158. sub compress_files
  2159. {
  2160. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2161. return compress_files_without_decrypt(decrypt_params(@_));
  2162. }
  2163. sub compress_files_without_decrypt
  2164. {
  2165. my ($files,$destination,$archive_name,$archive_type) = @_;
  2166. if (!-e $destination)
  2167. {
  2168. logger "compress_files: Destination path ( $destination ) could not be found.";
  2169. return -1;
  2170. }
  2171. chdir $destination;
  2172. my @items = split /\Q\n/, $files;
  2173. my @inventory;
  2174. if($archive_type eq "zip")
  2175. {
  2176. logger $archive_type." compression called, destination archive is: $destination$archive_name.$archive_type";
  2177. my $zip = Archive::Zip->new();
  2178. foreach my $item (@items) {
  2179. if(-e $item)
  2180. {
  2181. if (-f $item)
  2182. {
  2183. $zip->addFile( $item );
  2184. }
  2185. elsif (-d $item)
  2186. {
  2187. $zip->addTree( $item, $item );
  2188. }
  2189. }
  2190. }
  2191. # Save the file
  2192. unless ( $zip->writeToFileNamed($archive_name.'.zip') == AZ_OK ) {
  2193. logger "Write Error at $destination/$archive_name.$archive_type";
  2194. return -1
  2195. }
  2196. logger $archive_type." archive $destination$archive_name.$archive_type created successfully";
  2197. return 1;
  2198. }
  2199. elsif($archive_type eq "tbz")
  2200. {
  2201. logger $archive_type." compression called, destination archive is: $destination$archive_name.$archive_type";
  2202. my $tar = Archive::Tar->new;
  2203. foreach my $item (@items) {
  2204. if(-e $item)
  2205. {
  2206. if (-f $item)
  2207. {
  2208. $tar->add_files( $item );
  2209. }
  2210. elsif (-d $item)
  2211. {
  2212. @inventory = ();
  2213. find (sub { push @inventory, $File::Find::name }, $item);
  2214. $tar->add_files( @inventory );
  2215. }
  2216. }
  2217. }
  2218. # Save the file
  2219. unless ( $tar->write("$archive_name.$archive_type", COMPRESS_BZIP) ) {
  2220. logger "Write Error at $destination/$archive_name.$archive_type";
  2221. return -1
  2222. }
  2223. logger $archive_type." archive $destination$archive_name.$archive_type created successfully";
  2224. return 1;
  2225. }
  2226. elsif($archive_type eq "tgz")
  2227. {
  2228. logger $archive_type." compression called, destination archive is: $destination$archive_name.$archive_type";
  2229. my $tar = Archive::Tar->new;
  2230. foreach my $item (@items) {
  2231. if(-e $item)
  2232. {
  2233. if (-f $item)
  2234. {
  2235. $tar->add_files( $item );
  2236. }
  2237. elsif (-d $item)
  2238. {
  2239. @inventory = ();
  2240. find (sub { push @inventory, $File::Find::name }, $item);
  2241. $tar->add_files( @inventory );
  2242. }
  2243. }
  2244. }
  2245. # Save the file
  2246. unless ( $tar->write("$archive_name.$archive_type", COMPRESS_GZIP) ) {
  2247. logger "Write Error at $destination/$archive_name.$archive_type";
  2248. return -1
  2249. }
  2250. logger $archive_type." archive $destination$archive_name.$archive_type created successfully";
  2251. return 1;
  2252. }
  2253. elsif($archive_type eq "tar")
  2254. {
  2255. logger $archive_type." compression called, destination archive is: $destination$archive_name.$archive_type";
  2256. my $tar = Archive::Tar->new;
  2257. foreach my $item (@items) {
  2258. if(-e $item)
  2259. {
  2260. if (-f $item)
  2261. {
  2262. $tar->add_files( $item );
  2263. }
  2264. elsif (-d $item)
  2265. {
  2266. @inventory = ();
  2267. find (sub { push @inventory, $File::Find::name }, $item);
  2268. $tar->add_files( @inventory );
  2269. }
  2270. }
  2271. }
  2272. # Save the file
  2273. unless ( $tar->write("$archive_name.$archive_type") ) {
  2274. logger "Write Error at $destination/$archive_name.$archive_type";
  2275. return -1
  2276. }
  2277. logger $archive_type." archive $destination$archive_name.$archive_type created successfully";
  2278. return 1;
  2279. }
  2280. elsif($archive_type eq "bz2")
  2281. {
  2282. logger $archive_type." compression called.";
  2283. foreach my $item (@items) {
  2284. if(-e $item)
  2285. {
  2286. if (-f $item)
  2287. {
  2288. bzip2 $item => "$item.bz2";
  2289. }
  2290. elsif (-d $item)
  2291. {
  2292. @inventory = ();
  2293. find (sub { push @inventory, $File::Find::name }, $item);
  2294. foreach my $relative_item (@inventory) {
  2295. bzip2 $relative_item => "$relative_item.bz2";
  2296. }
  2297. }
  2298. }
  2299. }
  2300. logger $archive_type." archives created successfully at $destination";
  2301. return 1;
  2302. }
  2303. }
  2304. sub discover_ips
  2305. {
  2306. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2307. my ($check) = decrypt_params(@_);
  2308. if ($check ne "chk")
  2309. {
  2310. logger "Invalid parameter '$check' given for discover_ips function.";
  2311. return "";
  2312. }
  2313. my $iplist = "";
  2314. my $ipfound;
  2315. my $junk;
  2316. my @ipraw = `/sbin/ifconfig`;
  2317. while (<@ipraw>)
  2318. {
  2319. chomp;
  2320. next if $_ !~ /^inet:/ ;
  2321. logger "Found addr on line: $_";
  2322. ($junk, $ipfound) = split(":", $_);
  2323. next if $ipfound eq '';
  2324. next if $ipfound eq '127.0.0.1';
  2325. logger "Found an IP $ipfound";
  2326. $iplist .= "$ipfound,";
  2327. logger "IPlist is now $iplist";
  2328. }
  2329. while (<@ipraw>)
  2330. {
  2331. chomp;
  2332. next if $_ !~ /^addr:/ ;
  2333. logger "Found addr on line: $_";
  2334. ($junk, $ipfound) = split(":", $_);
  2335. next if $ipfound eq '';
  2336. next if $ipfound eq '127.0.0.1';
  2337. logger "Found an IP $ipfound";
  2338. $iplist .= "$ipfound,";
  2339. logger "IPlist is now $iplist";
  2340. }
  2341. chop $iplist;
  2342. return "$iplist";
  2343. }
  2344. ### Return -1 In case of invalid param
  2345. ### Return 1;content in case of success
  2346. sub mon_stats
  2347. {
  2348. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2349. my ($mon_stats) = decrypt_params(@_);
  2350. if ($mon_stats ne "mon_stats")
  2351. {
  2352. logger "Invalid parameter '$mon_stats' given for $mon_stats function.";
  2353. return -1;
  2354. }
  2355. my @disk = `df -hP -x tmpfs`;
  2356. my $encoded_content = encode_list(@disk);
  2357. my @uptime = `uptime`;
  2358. $encoded_content .= encode_list(@uptime);
  2359. return "1;$encoded_content";
  2360. }
  2361. sub exec
  2362. {
  2363. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2364. my ($command) = decrypt_params(@_);
  2365. my @cmdret = `$command 2>/dev/null`;
  2366. my $encoded_content = encode_list(@cmdret);
  2367. return "1;$encoded_content";
  2368. }
  2369. # used in conjunction with the clone_home feature in the web panel
  2370. # this actually does the file copies
  2371. sub clone_home
  2372. {
  2373. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2374. my ($source_home, $dest_home, $owner) = decrypt_params(@_);
  2375. my ($time_start, $time_stop, $time_diff);
  2376. logger "Copying from $source_home to $dest_home...";
  2377. # check size of source_home, make sure we have space to copy
  2378. if (!-e $source_home)
  2379. {
  2380. logger "ERROR - $source_home does not exist";
  2381. return 0;
  2382. }
  2383. logger "Game home $source_home exists...copy will proceed";
  2384. # start the copy, and a timer
  2385. $time_start = time();
  2386. if (!dircopy("$source_home", "$dest_home"))
  2387. {
  2388. $time_stop = time();
  2389. $time_diff = $time_stop - $time_start;
  2390. logger
  2391. "Error occured after $time_diff seconds during copy of $source_home to $dest_home - $!";
  2392. return 0;
  2393. }
  2394. else
  2395. {
  2396. $time_stop = time();
  2397. $time_diff = $time_stop - $time_start;
  2398. logger
  2399. "Home clone completed successfully to $dest_home in $time_diff seconds";
  2400. return 1;
  2401. }
  2402. }
  2403. # used to delete the game home from the file system when it's removed from the panel
  2404. sub remove_home
  2405. {
  2406. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2407. my ($home_path_del) = decrypt_params(@_);
  2408. if (!-e $home_path_del)
  2409. {
  2410. logger "ERROR - $home_path_del does not exist...nothing to do";
  2411. return 0;
  2412. }
  2413. secure_path_without_decrypt('chattr-i', $home_path_del);
  2414. sleep 1 while ( !pathrmdir("$home_path_del") );
  2415. logger "Deletetion of $home_path_del successful!";
  2416. return 1;
  2417. }
  2418. sub restart_server
  2419. {
  2420. chomp(@_);
  2421. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2422. return restart_server_without_decrypt(decrypt_params(@_));
  2423. }
  2424. ### Restart the server
  2425. ## return -2 CANT STOP
  2426. ## return -1 CANT START (no startup file found that mach the home_id, port and ip)
  2427. ## return 1 Restart OK
  2428. sub restart_server_without_decrypt
  2429. {
  2430. my ($home_id, $server_ip, $server_port, $control_protocol,
  2431. $control_password, $control_type, $home_path, $server_exe, $run_dir,
  2432. $cmd, $cpu, $nice, $preStart, $envVars, $game_key, $console_log) = @_;
  2433. if (stop_server_without_decrypt($home_id, $server_ip,
  2434. $server_port, $control_protocol,
  2435. $control_password, $control_type, $home_path) == 0)
  2436. {
  2437. if (universal_start_without_decrypt($home_id, $home_path, $server_exe, $run_dir,
  2438. $cmd, $server_port, $server_ip, $cpu, $nice, $preStart, $envVars, $game_key, $console_log) == 1)
  2439. {
  2440. return 1;
  2441. }
  2442. else
  2443. {
  2444. return -1;
  2445. }
  2446. }
  2447. else
  2448. {
  2449. return -2;
  2450. }
  2451. }
  2452. sub sudo_exec
  2453. {
  2454. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2455. my $sudo_exec = &decrypt_param(@_);
  2456. return sudo_exec_without_decrypt($sudo_exec);
  2457. }
  2458. sub sudo_exec_without_decrypt
  2459. {
  2460. my ($sudo_exec) = @_;
  2461. $sudo_exec =~ s/('+)/'"$1"'/g;
  2462. logger "Running the following command \"" . $sudo_exec . "\" with sudo.";
  2463. my $command = "echo '$SUDOPASSWD'|sudo -kS -p \"<prompt>\" su -c '$sudo_exec;echo \$?' root 2>&1";
  2464. my @cmdret = qx($command);
  2465. $cmdret[0] =~ s/^<prompt>//g if defined $cmdret[0];
  2466. chomp(@cmdret);
  2467. my $ret = pop(@cmdret);
  2468. chomp($ret);
  2469. if ("X$ret" eq "X0")
  2470. {
  2471. logger "Command \"" . $sudo_exec . "\" was successfully run with sudo.";
  2472. return "1;".encode_list(@cmdret);
  2473. }
  2474. logger "Command \"" . $sudo_exec . "\" run with sudo failed with exit code $ret.";
  2475. return -1;
  2476. }
  2477. sub secure_path
  2478. {
  2479. chomp(@_);
  2480. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2481. return secure_path_without_decrypt(decrypt_params(@_));
  2482. }
  2483. sub secure_path_without_decrypt
  2484. {
  2485. my ($action, $file_path, $returnType) = @_;
  2486. my $checkIfFileExists = 1;
  2487. if(defined $returnType && $returnType eq "str"){
  2488. $checkIfFileExists = 0;
  2489. }
  2490. if($checkIfFileExists){
  2491. if(! -e $file_path){
  2492. return -1;
  2493. }
  2494. }
  2495. my $uid = `id -u`;
  2496. chomp $uid;
  2497. my $gid = `id -g`;
  2498. chomp $gid;
  2499. $file_path =~ s/('+)/'\"$1\"'/g;
  2500. if($action eq "chattr+i")
  2501. {
  2502. if(defined $returnType && $returnType eq "str"){
  2503. return 'chown -Rf '.$uid.':'.$gid.' \''.$file_path.'\' && chattr -Rf +i \''.$file_path.'\'';
  2504. }else{
  2505. return sudo_exec_without_decrypt('chown -Rf '.$uid.':'.$gid.' \''.$file_path.'\' && chattr -Rf +i \''.$file_path.'\'');
  2506. }
  2507. }
  2508. elsif($action eq "chattr-i")
  2509. {
  2510. if(defined $returnType && $returnType eq "str"){
  2511. return 'chattr -Rf -i \''.$file_path.'\' && chown -Rf '.$uid.':'.$gid.' \''.$file_path.'\'';
  2512. }else{
  2513. return sudo_exec_without_decrypt('chattr -Rf -i \''.$file_path.'\' && chown -Rf '.$uid.':'.$gid.' \''.$file_path.'\'');
  2514. }
  2515. }
  2516. return -1;
  2517. }
  2518. sub get_chattr
  2519. {
  2520. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2521. my ($file_path) = decrypt_params(@_);
  2522. my $file = $file_path;
  2523. $file_path =~ s/('+)/'\"$1\"'/g;
  2524. return sudo_exec_without_decrypt('(lsattr \''.$file_path.'\' | sed -e "s#'.$file.'##g")|grep -o i');
  2525. }
  2526. sub ftp_mgr
  2527. {
  2528. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2529. my ($action, $login, $password, $home_path) = decrypt_params(@_);
  2530. my $uid = `id -u`;
  2531. chomp $uid;
  2532. my $gid = `id -g`;
  2533. chomp $gid;
  2534. $login =~ s/('+)/'\"$1\"'/g;
  2535. $password =~ s/('+)/'\"$1\"'/g;
  2536. $home_path =~ s/('+)/'\"$1\"'/g;
  2537. if(!defined($Cfg::Preferences{ogp_manages_ftp}) || (defined($Cfg::Preferences{ogp_manages_ftp}) && $Cfg::Preferences{ogp_manages_ftp} eq "1")){
  2538. if( defined($Cfg::Preferences{ftp_method}) && $Cfg::Preferences{ftp_method} eq "IspConfig")
  2539. {
  2540. use constant ISPCONFIG_DIR => Path::Class::Dir->new(AGENT_RUN_DIR, 'IspConfig');
  2541. use constant FTP_USERS_DIR => Path::Class::Dir->new(ISPCONFIG_DIR, 'ftp_users');
  2542. if (!-d FTP_USERS_DIR && !mkdir FTP_USERS_DIR)
  2543. {
  2544. print "Could not create " . FTP_USERS_DIR . " directory $!.";
  2545. return -1;
  2546. }
  2547. chdir ISPCONFIG_DIR;
  2548. if($action eq "list")
  2549. {
  2550. my $users_list;
  2551. opendir(USERS, FTP_USERS_DIR);
  2552. while (my $username = readdir(USERS))
  2553. {
  2554. # Skip . and ..
  2555. next if $username =~ /^\./;
  2556. $users_list .= `php-cgi -f sites_ftp_user_get.php username=\'$username\'`;
  2557. }
  2558. closedir(USERS);
  2559. if( defined($users_list) )
  2560. {
  2561. return "1;".encode_list($users_list);
  2562. }
  2563. }
  2564. elsif($action eq "userdel")
  2565. {
  2566. return "1;".encode_list(`php-cgi -f sites_ftp_user_delete.php username=\'$login\'`);
  2567. }
  2568. elsif($action eq "useradd")
  2569. {
  2570. return "1;".encode_list(`php-cgi -f sites_ftp_user_add.php username=\'$login\' password=\'$password\' dir=\'$home_path\' uid=$uid gid=$gid`);
  2571. }
  2572. elsif($action eq "passwd")
  2573. {
  2574. return "1;".encode_list(`php-cgi -f sites_ftp_user_update.php type=passwd username=\'$login\' password=\'$password\'`);
  2575. }
  2576. elsif($action eq "show")
  2577. {
  2578. return "1;".encode_list(`php-cgi -f sites_ftp_user_get.php type=detail username=\'$login\'`);
  2579. }
  2580. elsif($action eq "usermod")
  2581. {
  2582. return "1;".encode_list(`php-cgi -f sites_ftp_user_update.php username=\'$login\' password=\'$password\'`);
  2583. }
  2584. }
  2585. 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" ))
  2586. {
  2587. use constant EHCP_DIR => Path::Class::Dir->new(AGENT_RUN_DIR, 'EHCP');
  2588. chdir EHCP_DIR;
  2589. my $phpScript;
  2590. my $phpOut;
  2591. chmod 0777, 'ehcp_ftp_log.txt';
  2592. # In order to access the FTP files, the vsftpd user needs to be added to the ogp group
  2593. sudo_exec_without_decrypt("usermod -a -G '$gid' ftp");
  2594. sudo_exec_without_decrypt("usermod -a -G '$gid' vsftpd");
  2595. if($action eq "list")
  2596. {
  2597. return "1;".encode_list(`php-cgi -f listAllUsers.php`);
  2598. }
  2599. elsif($action eq "userdel")
  2600. {
  2601. $phpScript = `php-cgi -f delAccount.php username=\'$login\'`;
  2602. $phpOut = `php-cgi -f syncftp.php`;
  2603. return $phpScript;
  2604. }
  2605. elsif($action eq "useradd")
  2606. {
  2607. $phpScript = `php-cgi -f addAccount.php username=\'$login\' password=\'$password\' dir=\'$home_path\' uid=$uid gid=$gid`;
  2608. $phpOut = `php-cgi -f syncftp.php`;
  2609. return $phpScript;
  2610. }
  2611. elsif($action eq "passwd")
  2612. {
  2613. $phpScript = `php-cgi -f updatePass.php username=\'$login\' password=\'$password\'`;
  2614. $phpOut = `php-cgi -f syncftp.php`;
  2615. return $phpScript ;
  2616. }
  2617. elsif($action eq "show")
  2618. {
  2619. return "1;".encode_list(`php-cgi -f showAccount.php username=\'$login\'`);
  2620. }
  2621. elsif($action eq "usermod")
  2622. {
  2623. $phpScript = `php-cgi -f updateInfo.php username=\'$login\' password=\'$password\'`;
  2624. $phpOut = `php-cgi -f syncftp.php`;
  2625. return $phpScript;
  2626. }
  2627. }
  2628. elsif(defined($Cfg::Preferences{ftp_method}) && $Cfg::Preferences{ftp_method} eq "proftpd" && -e $Cfg::Preferences{proftpd_conf_path})
  2629. {
  2630. chdir $Cfg::Preferences{proftpd_conf_path};
  2631. if($action eq "list")
  2632. {
  2633. my $users;
  2634. open(PASSWD, 'ftpd.passwd');
  2635. while (<PASSWD>) {
  2636. chomp;
  2637. my($login, $passwd, $uid, $gid, $gcos, $home, $shell) = split(/:/);
  2638. $users .= "$login\t$home\n";
  2639. }
  2640. close(PASSWD);
  2641. return "1;".encode_list($users);
  2642. }
  2643. elsif($action eq "userdel")
  2644. {
  2645. return sudo_exec_without_decrypt("ftpasswd --passwd --delete-user --name='$login'");
  2646. }
  2647. elsif($action eq "useradd")
  2648. {
  2649. return sudo_exec_without_decrypt("echo '$password' | ftpasswd --passwd --name='$login' --home='$home_path' --shell=/bin/false --uid=$uid --gid=$gid --stdin");
  2650. }
  2651. elsif($action eq "passwd")
  2652. {
  2653. return sudo_exec_without_decrypt("echo '$password' | ftpasswd --passwd --change-password --name='$login' --stdin");
  2654. }
  2655. elsif($action eq "show")
  2656. {
  2657. return 1;
  2658. }
  2659. elsif($action eq "usermod")
  2660. {
  2661. return 1;
  2662. }
  2663. chdir AGENT_RUN_DIR;
  2664. }
  2665. else
  2666. {
  2667. if($action eq "list")
  2668. {
  2669. return sudo_exec_without_decrypt("pure-pw list");
  2670. }
  2671. elsif($action eq "userdel")
  2672. {
  2673. return sudo_exec_without_decrypt("pure-pw userdel '$login' && pure-pw mkdb");
  2674. }
  2675. elsif($action eq "useradd")
  2676. {
  2677. return sudo_exec_without_decrypt("(echo '$password'; echo '$password') | pure-pw useradd '$login' -u $uid -g $gid -d '$home_path' && pure-pw mkdb");
  2678. }
  2679. elsif($action eq "passwd")
  2680. {
  2681. return sudo_exec_without_decrypt("(echo '$password'; echo '$password') | pure-pw passwd '$login' && pure-pw mkdb");
  2682. }
  2683. elsif($action eq "show")
  2684. {
  2685. return sudo_exec_without_decrypt("pure-pw show '$login'");
  2686. }
  2687. elsif($action eq "usermod")
  2688. {
  2689. my $update_account = "pure-pw usermod '$login' -u $uid -g $gid";
  2690. my @account_settings = split /[\n]+/, $password;
  2691. foreach my $setting (@account_settings) {
  2692. my ($key, $value) = split /[\t]+/, $setting;
  2693. if( $key eq 'Directory' )
  2694. {
  2695. $value =~ s/('+)/'\"$1\"'/g;
  2696. $update_account .= " -d '$value'";
  2697. }
  2698. if( $key eq 'Full_name' )
  2699. {
  2700. if( $value ne "" )
  2701. {
  2702. $value =~ s/('+)/'\"$1\"'/g;
  2703. $update_account .= " -c '$value'";
  2704. }
  2705. else
  2706. {
  2707. $update_account .= ' -c ""';
  2708. }
  2709. }
  2710. if( $key eq 'Download_bandwidth' && $value ne "" )
  2711. {
  2712. my $Download_bandwidth;
  2713. if($value eq 0)
  2714. {
  2715. $Download_bandwidth = "\"\"";
  2716. }
  2717. else
  2718. {
  2719. $Download_bandwidth = $value;
  2720. }
  2721. $update_account .= " -t " . $Download_bandwidth;
  2722. }
  2723. if( $key eq 'Upload___bandwidth' && $value ne "" )
  2724. {
  2725. my $Upload___bandwidth;
  2726. if($value eq 0)
  2727. {
  2728. $Upload___bandwidth = "\"\"";
  2729. }
  2730. else
  2731. {
  2732. $Upload___bandwidth = $value;
  2733. }
  2734. $update_account .= " -T " . $Upload___bandwidth;
  2735. }
  2736. if( $key eq 'Max_files' )
  2737. {
  2738. if( $value eq "0" )
  2739. {
  2740. $update_account .= ' -n ""';
  2741. }
  2742. elsif( $value ne "" )
  2743. {
  2744. $update_account .= " -n " . $value;
  2745. }
  2746. else
  2747. {
  2748. $update_account .= ' -n ""';
  2749. }
  2750. }
  2751. if( $key eq 'Max_size' )
  2752. {
  2753. if( $value ne "" && $value ne "0" )
  2754. {
  2755. $update_account .= " -N " . $value;
  2756. }
  2757. else
  2758. {
  2759. $update_account .= ' -N ""';
  2760. }
  2761. }
  2762. if( $key eq 'Ratio' && $value ne "" )
  2763. {
  2764. my($upload_ratio,$download_ratio) = split/:/,$value;
  2765. if($upload_ratio eq "0")
  2766. {
  2767. $upload_ratio = "\"\"";
  2768. }
  2769. $update_account .= " -q " . $upload_ratio;
  2770. if($download_ratio eq "0")
  2771. {
  2772. $download_ratio = "\"\"";
  2773. }
  2774. $update_account .= " -Q " . $download_ratio;
  2775. }
  2776. if( $key eq 'Allowed_client_IPs' )
  2777. {
  2778. if( $value ne "" )
  2779. {
  2780. $update_account .= " -r " . $value;
  2781. }
  2782. else
  2783. {
  2784. $update_account .= ' -r ""';
  2785. }
  2786. }
  2787. if( $key eq 'Denied__client_IPs' )
  2788. {
  2789. if( $value ne "" )
  2790. {
  2791. $update_account .= " -R " . $value;
  2792. }
  2793. else
  2794. {
  2795. $update_account .= ' -R ""';
  2796. }
  2797. }
  2798. if( $key eq 'Allowed_local__IPs' )
  2799. {
  2800. if( $value ne "" )
  2801. {
  2802. $update_account .= " -i " . $value;
  2803. }
  2804. else
  2805. {
  2806. $update_account .= ' -i ""';
  2807. }
  2808. }
  2809. if( $key eq 'Denied__local__IPs' )
  2810. {
  2811. if( $value ne "" )
  2812. {
  2813. $update_account .= " -I " . $value;
  2814. }
  2815. else
  2816. {
  2817. $update_account .= ' -I ""';
  2818. }
  2819. }
  2820. if( $key eq 'Max_sim_sessions' && $value ne "" )
  2821. {
  2822. $update_account .= " -y " . $value;
  2823. }
  2824. if ( $key eq 'Time_restrictions' )
  2825. {
  2826. if( $value eq "0000-0000")
  2827. {
  2828. $update_account .= ' -z ""';
  2829. }
  2830. elsif( $value ne "" )
  2831. {
  2832. $update_account .= " -z " . $value;
  2833. }
  2834. else
  2835. {
  2836. $update_account .= ' -z ""';
  2837. }
  2838. }
  2839. }
  2840. $update_account .=" && pure-pw mkdb";
  2841. # print $update_account;
  2842. return sudo_exec_without_decrypt($update_account);
  2843. }
  2844. }
  2845. }
  2846. return 0;
  2847. }
  2848. sub start_fastdl
  2849. {
  2850. if(-e Path::Class::File->new(FD_DIR, 'Settings.pm'))
  2851. {
  2852. system('perl FastDownload/ForkedDaemon.pm &');
  2853. sleep(1);
  2854. return 1;
  2855. }
  2856. else
  2857. {
  2858. return -2;
  2859. }
  2860. }
  2861. sub stop_fastdl
  2862. {
  2863. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2864. return stop_fastdl_without_decrypt();
  2865. }
  2866. sub stop_fastdl_without_decrypt
  2867. {
  2868. my $pid;
  2869. open(PIDFILE, '<', FD_PID_FILE)
  2870. || logger "Error reading pid file $!",1;
  2871. while (<PIDFILE>)
  2872. {
  2873. $pid = $_;
  2874. chomp $pid;
  2875. }
  2876. close(PIDFILE);
  2877. my $cnt = kill 9, $pid;
  2878. if ($cnt == 1)
  2879. {
  2880. logger "Fast Download Daemon Stopped.",1;
  2881. return 1;
  2882. }
  2883. else
  2884. {
  2885. logger "Fast Download Daemon with pid $pid can not be stopped.",1;
  2886. return -1;
  2887. }
  2888. }
  2889. sub restart_fastdl
  2890. {
  2891. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2892. return restart_fastdl_without_decrypt();
  2893. }
  2894. sub restart_fastdl_without_decrypt
  2895. {
  2896. if((fastdl_status_without_decrypt() == -1) || (stop_fastdl_without_decrypt() == 1))
  2897. {
  2898. if(start_fastdl() == 1)
  2899. {
  2900. # Success
  2901. return 1;
  2902. }
  2903. # Cant start
  2904. return -2;
  2905. }
  2906. # Cant stop
  2907. return -3;
  2908. }
  2909. sub fastdl_status
  2910. {
  2911. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2912. return fastdl_status_without_decrypt();
  2913. }
  2914. sub fastdl_status_without_decrypt
  2915. {
  2916. my $pid;
  2917. if(!open(PIDFILE, '<', FD_PID_FILE))
  2918. {
  2919. logger "Error reading pid file $!";
  2920. return -1;
  2921. }
  2922. while (<PIDFILE>)
  2923. {
  2924. $pid = $_;
  2925. chomp $pid;
  2926. }
  2927. close(PIDFILE);
  2928. my $cnt = kill 0, $pid;
  2929. if ($cnt == 1)
  2930. {
  2931. return 1;
  2932. }
  2933. else
  2934. {
  2935. return -1;
  2936. }
  2937. }
  2938. sub fastdl_get_aliases
  2939. {
  2940. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2941. my %aliases;
  2942. my $i;
  2943. my @file_lines;
  2944. if(-d FD_ALIASES_DIR)
  2945. {
  2946. if( !opendir(ALIASES, FD_ALIASES_DIR) )
  2947. {
  2948. logger "Error openning aliases directory " . FD_ALIASES_DIR . ", $!";
  2949. }
  2950. else
  2951. {
  2952. while (my $alias = readdir(ALIASES))
  2953. {
  2954. # Skip . and ..
  2955. next if $alias =~ /^\./;
  2956. if( !open(ALIAS, '<', Path::Class::Dir->new(FD_ALIASES_DIR, $alias)) )
  2957. {
  2958. logger "Error reading alias '$alias', $!";
  2959. }
  2960. else
  2961. {
  2962. $i = 0;
  2963. @file_lines = ();
  2964. while (<ALIAS>)
  2965. {
  2966. chomp $_;
  2967. $file_lines[$i] = $_;
  2968. $i++;
  2969. }
  2970. close(ALIAS);
  2971. $aliases{$alias}{home} = $file_lines[0];
  2972. $aliases{$alias}{match_file_extension} = $file_lines[1];
  2973. $aliases{$alias}{match_client_ip} = $file_lines[2];
  2974. }
  2975. }
  2976. closedir(ALIASES);
  2977. }
  2978. }
  2979. else
  2980. {
  2981. logger "Aliases directory '" . FD_ALIASES_DIR . "' does not exist or is inaccessible.";
  2982. }
  2983. return {%aliases};
  2984. }
  2985. sub fastdl_del_alias
  2986. {
  2987. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2988. foreach my $alias (decrypt_params(@_))
  2989. {
  2990. unlink Path::Class::File->new(FD_ALIASES_DIR, $alias);
  2991. }
  2992. return restart_fastdl_without_decrypt();
  2993. }
  2994. sub fastdl_add_alias
  2995. {
  2996. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2997. my ($alias,$home,$match_file_extension,$match_client_ip) = decrypt_params(@_);
  2998. if(!-e FD_ALIASES_DIR)
  2999. {
  3000. if(!mkdir FD_ALIASES_DIR)
  3001. {
  3002. logger "ERROR - Failed to create " . FD_ALIASES_DIR . " directory.";
  3003. return -1;
  3004. }
  3005. }
  3006. my $alias_path = Path::Class::File->new(FD_ALIASES_DIR, $alias);
  3007. if (!open(ALIAS, '>', $alias_path))
  3008. {
  3009. logger "ERROR - Failed to open ".$alias_path." for writing.";
  3010. return -1;
  3011. }
  3012. else
  3013. {
  3014. print ALIAS "$home\n";
  3015. print ALIAS "$match_file_extension\n";
  3016. print ALIAS "$match_client_ip";
  3017. close(ALIAS);
  3018. return restart_fastdl_without_decrypt();
  3019. }
  3020. }
  3021. sub fastdl_get_info
  3022. {
  3023. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3024. if(-e Path::Class::File->new(FD_DIR, 'Settings.pm'))
  3025. {
  3026. delete $INC{"FastDownload/Settings.pm"};
  3027. require "FastDownload/Settings.pm"; # Settings for Fast Download Daemon.
  3028. if(not defined $FastDownload::Settings{autostart_on_agent_startup})
  3029. {
  3030. $FastDownload::Settings{autostart_on_agent_startup} = 0;
  3031. }
  3032. return {'port' => $FastDownload::Settings{port},
  3033. 'ip' => $FastDownload::Settings{ip},
  3034. 'listing' => $FastDownload::Settings{listing},
  3035. 'autostart_on_agent_startup'=> $FastDownload::Settings{autostart_on_agent_startup}};
  3036. }
  3037. return -1
  3038. }
  3039. sub fastdl_create_config
  3040. {
  3041. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3042. if(!-e FD_DIR)
  3043. {
  3044. if(!mkdir FD_DIR)
  3045. {
  3046. logger "ERROR - Failed to create " . FD_DIR . " directory.";
  3047. return -1;
  3048. }
  3049. }
  3050. my ($fd_address, $fd_port, $listing, $autostart_on_agent_startup) = decrypt_params(@_);
  3051. my $settings_string = "%FastDownload::Settings = (\n".
  3052. "\tport => $fd_port,\n".
  3053. "\tip => '$fd_address',\n".
  3054. "\tlisting => $listing,\n".
  3055. "\tautostart_on_agent_startup => $autostart_on_agent_startup,\n".
  3056. ");";
  3057. my $settings = Path::Class::File->new(FD_DIR, 'Settings.pm');
  3058. if (!open(SETTINGS, '>', $settings))
  3059. {
  3060. logger "ERROR - Failed to open $settings for writing.";
  3061. return -1;
  3062. }
  3063. else
  3064. {
  3065. print SETTINGS $settings_string;
  3066. close(SETTINGS);
  3067. }
  3068. logger "$settings file written successfully.";
  3069. return 1;
  3070. }
  3071. sub agent_restart
  3072. {
  3073. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3074. my $dec_check = decrypt_param(@_);
  3075. if ($dec_check eq 'restart')
  3076. {
  3077. chdir AGENT_RUN_DIR;
  3078. if(-e "ogp_agent_run.pid")
  3079. {
  3080. my $init_pid = `cat ogp_agent_run.pid`;
  3081. chomp($init_pid);
  3082. if(kill 0, $init_pid)
  3083. {
  3084. my $or_exist = "";
  3085. my $rm_pid_file = "";
  3086. if(-e "ogp_agent.pid")
  3087. {
  3088. $rm_pid_file = " ogp_agent.pid";
  3089. my $agent_pid = `cat ogp_agent.pid`;
  3090. chomp($agent_pid);
  3091. if( kill 0, $agent_pid )
  3092. {
  3093. $or_exist = " -o -e /proc/$agent_pid";
  3094. }
  3095. }
  3096. open (AGENT_RESTART_SCRIPT, '>', 'tmp_restart.sh');
  3097. my $restart = "echo -n \"Stopping OGP Agent...\"\n".
  3098. "kill $init_pid\n".
  3099. "while [ -e /proc/$init_pid $or_exist ];do echo -n .;sleep 1;done\n".
  3100. "rm -f ogp_agent_run.pid $rm_pid_file\necho \" [OK]\"\n".
  3101. "echo -n \"Starting OGP Agent...\"\n".
  3102. "screen -d -m -t \"ogp_agent\" -c \"" . SCREENRC_FILE . "\" -S ogp_agent bash ogp_agent_run -pidfile ogp_agent_run.pid\n".
  3103. "while [ ! -e ogp_agent_run.pid -o ! -e ogp_agent.pid ];do echo -n .;sleep 1;done\n".
  3104. "echo \" [OK]\"\n".
  3105. "rm -f tmp_restart.sh\n".
  3106. "exit 0\n";
  3107. print AGENT_RESTART_SCRIPT $restart;
  3108. close (AGENT_RESTART_SCRIPT);
  3109. if( -e 'tmp_restart.sh' )
  3110. {
  3111. system('screen -d -m -t "agent_restart" -c "' . SCREENRC_FILE . '" -S agent_restart bash tmp_restart.sh');
  3112. }
  3113. }
  3114. }
  3115. }
  3116. return -1;
  3117. }
  3118. # Subroutines to be called
  3119. sub scheduler_dispatcher {
  3120. my ($task, $args) = @_;
  3121. my $response = `$args`;
  3122. chomp($response);
  3123. my $log = "Executed command: $args";
  3124. if($response ne "")
  3125. {
  3126. $log .= ", response:\n$response";
  3127. }
  3128. scheduler_log_events($log);
  3129. }
  3130. sub scheduler_server_action
  3131. {
  3132. my ($task, $args) = @_;
  3133. my ($action, @server_args) = split('\|\%\|', $args);
  3134. if($action eq "%ACTION=start")
  3135. {
  3136. my ($home_id, $ip, $port) = ($server_args[0], $server_args[6], $server_args[5]);
  3137. my $ret = universal_start_without_decrypt(@server_args);
  3138. if($ret == 1)
  3139. {
  3140. scheduler_log_events("Started server home ID $home_id on address $ip:$port");
  3141. }
  3142. else
  3143. {
  3144. scheduler_log_events("Failed starting server home ID $home_id on address $ip:$port (Check agent log)");
  3145. }
  3146. }
  3147. elsif($action eq "%ACTION=stop")
  3148. {
  3149. my ($home_id, $ip, $port) = ($server_args[0], $server_args[1], $server_args[2]);
  3150. my $ret = stop_server_without_decrypt(@server_args);
  3151. if($ret == 0)
  3152. {
  3153. scheduler_log_events("Stopped server home ID $home_id on address $ip:$port");
  3154. }
  3155. elsif($ret == 1)
  3156. {
  3157. scheduler_log_events("Failed stopping server home ID $home_id on address $ip:$port (Invalid IP:Port given)");
  3158. }
  3159. }
  3160. elsif($action eq "%ACTION=restart")
  3161. {
  3162. my ($home_id, $ip, $port) = ($server_args[0], $server_args[1], $server_args[2]);
  3163. my $ret = restart_server_without_decrypt(@server_args);
  3164. if($ret == 1)
  3165. {
  3166. scheduler_log_events("Restarted server home ID $home_id on address $ip:$port");
  3167. }
  3168. elsif($ret == -1)
  3169. {
  3170. scheduler_log_events("Failed restarting server home ID $home_id on address $ip:$port (Server could not be started, check agent log)");
  3171. }
  3172. elsif($ret == -2)
  3173. {
  3174. scheduler_log_events("Failed restarting server home ID $home_id on address $ip:$port (Server could not be stopped, check agent log)");
  3175. }
  3176. }
  3177. return 1;
  3178. }
  3179. sub scheduler_log_events
  3180. {
  3181. my $logcmd = $_[0];
  3182. $logcmd = localtime() . " $logcmd\n";
  3183. logger "Can't open " . SCHED_LOG_FILE . " - $!" unless open(LOGFILE, '>>', SCHED_LOG_FILE);
  3184. logger "Failed to lock " . SCHED_LOG_FILE . "." unless flock(LOGFILE, LOCK_EX);
  3185. logger "Failed to seek to end of " . SCHED_LOG_FILE . "." unless seek(LOGFILE, 0, 2);
  3186. logger "Failed to write to " . SCHED_LOG_FILE . "." unless print LOGFILE "$logcmd";
  3187. logger "Failed to unlock " . SCHED_LOG_FILE . "." unless flock(LOGFILE, LOCK_UN);
  3188. logger "Failed to close " . SCHED_LOG_FILE . "." unless close(LOGFILE);
  3189. }
  3190. sub scheduler_add_task
  3191. {
  3192. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3193. my $new_task = decrypt_param(@_);
  3194. if (open(TASKS, '>>', SCHED_TASKS))
  3195. {
  3196. print TASKS "$new_task\n";
  3197. logger "Created new task: $new_task";
  3198. close(TASKS);
  3199. scheduler_stop();
  3200. # Create new object with default dispatcher for scheduled tasks
  3201. $cron = new Schedule::Cron( \&scheduler_dispatcher, {
  3202. nofork => 1,
  3203. loglevel => 0,
  3204. log => sub { print $_[1], "\n"; }
  3205. } );
  3206. $cron->add_entry( "* * * * * *", \&scheduler_read_tasks );
  3207. # Run scheduler
  3208. $cron->run( {detach=>1, pid_file=>SCHED_PID} );
  3209. return 1;
  3210. }
  3211. logger "Cannot create task: $new_task ( $! )";
  3212. return -1;
  3213. }
  3214. sub scheduler_del_task
  3215. {
  3216. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3217. my $name = decrypt_param(@_);
  3218. my @cronJobIDs = split(',', $name);
  3219. if( scheduler_read_tasks() == -1 )
  3220. {
  3221. return -1;
  3222. }
  3223. my @entries = $cron->list_entries();
  3224. if(open(TASKS, '>', SCHED_TASKS))
  3225. {
  3226. foreach my $task ( @entries ) {
  3227. next if ( grep { $_ eq $task->{args}[0]} @cronJobIDs );
  3228. next unless $task->{args}[0] =~ /task_[0-9]*/;
  3229. if(defined $task->{args}[1])
  3230. {
  3231. print TASKS join(" ", $task->{time}, $task->{args}[1]) . "\n";
  3232. }
  3233. else
  3234. {
  3235. print TASKS $task->{time} . "\n";
  3236. }
  3237. }
  3238. close( TASKS );
  3239. scheduler_stop();
  3240. # Create new object with default dispatcher for scheduled tasks
  3241. $cron = new Schedule::Cron( \&scheduler_dispatcher, {
  3242. nofork => 1,
  3243. loglevel => 0,
  3244. log => sub { print $_[1], "\n"; }
  3245. } );
  3246. $cron->add_entry( "* * * * * *", \&scheduler_read_tasks );
  3247. # Run scheduler
  3248. $cron->run( {detach=>1, pid_file=>SCHED_PID} );
  3249. return 1;
  3250. }
  3251. logger "Cannot open file " . SCHED_TASKS . " for deleting task(s) id: $name ( $! )",1;
  3252. return -1;
  3253. }
  3254. sub scheduler_edit_task
  3255. {
  3256. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3257. my ($name, $new_task) = decrypt_params(@_);
  3258. if( scheduler_read_tasks() == -1 )
  3259. {
  3260. return -1;
  3261. }
  3262. my @entries = $cron->list_entries();
  3263. if(open(TASKS, '>', SCHED_TASKS))
  3264. {
  3265. foreach my $task ( @entries ) {
  3266. next unless $task->{args}[0] =~ /task_[0-9]*/;
  3267. if($name eq $task->{args}[0])
  3268. {
  3269. print TASKS "$new_task\n";
  3270. }
  3271. else
  3272. {
  3273. if(defined $task->{args}[1])
  3274. {
  3275. print TASKS join(" ", $task->{time}, $task->{args}[1]) . "\n";
  3276. }
  3277. else
  3278. {
  3279. print TASKS $task->{time} . "\n";
  3280. }
  3281. }
  3282. }
  3283. close( TASKS );
  3284. scheduler_stop();
  3285. # Create new object with default dispatcher for scheduled tasks
  3286. $cron = new Schedule::Cron( \&scheduler_dispatcher, {
  3287. nofork => 1,
  3288. loglevel => 0,
  3289. log => sub { print $_[1], "\n"; }
  3290. } );
  3291. $cron->add_entry( "* * * * * *", \&scheduler_read_tasks );
  3292. # Run scheduler
  3293. $cron->run( {detach=>1, pid_file=>SCHED_PID} );
  3294. return 1;
  3295. }
  3296. logger "Cannot open file " . SCHED_TASKS . " for editing task id: $name ( $! )",1;
  3297. return -1;
  3298. }
  3299. sub scheduler_read_tasks
  3300. {
  3301. if( open(TASKS, '<', SCHED_TASKS) )
  3302. {
  3303. $cron->clean_timetable();
  3304. }
  3305. else
  3306. {
  3307. logger "Error reading tasks file $!";
  3308. scheduler_stop();
  3309. return -1;
  3310. }
  3311. my $i = 0;
  3312. while (<TASKS>)
  3313. {
  3314. next if $_ =~ /^(#.*|[\s|\t]*?\n)/;
  3315. my ($minute, $hour, $dayOfTheMonth, $month, $dayOfTheWeek, @args) = split(' ', $_);
  3316. my $time = "$minute $hour $dayOfTheMonth $month $dayOfTheWeek";
  3317. if("@args" =~ /^\%ACTION.*/)
  3318. {
  3319. $cron->add_entry($time, \&scheduler_server_action, 'task_' . $i++, "@args");
  3320. }
  3321. else
  3322. {
  3323. $cron->add_entry($time, 'task_' . $i++, "@args");
  3324. }
  3325. }
  3326. close(TASKS);
  3327. return 1;
  3328. }
  3329. sub scheduler_stop
  3330. {
  3331. my $pid;
  3332. if(open(PIDFILE, '<', SCHED_PID))
  3333. {
  3334. $pid = <PIDFILE>;
  3335. chomp $pid;
  3336. close(PIDFILE);
  3337. if($pid ne "")
  3338. {
  3339. if( kill 0, $pid )
  3340. {
  3341. my $cnt = kill 9, $pid;
  3342. if ($cnt == 1)
  3343. {
  3344. unlink SCHED_PID;
  3345. return 1;
  3346. }
  3347. }
  3348. }
  3349. }
  3350. return -1;
  3351. }
  3352. sub scheduler_list_tasks
  3353. {
  3354. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3355. if( scheduler_read_tasks() == -1 )
  3356. {
  3357. return -1;
  3358. }
  3359. my @entries = $cron->list_entries();
  3360. my %entries_array;
  3361. foreach my $task ( @entries ) {
  3362. if( defined $task->{args}[1] )
  3363. {
  3364. $entries_array{$task->{args}[0]} = encode_base64(join(" ", $task->{time}, $task->{args}[1]));
  3365. }
  3366. else
  3367. {
  3368. $entries_array{$task->{args}[0]} = encode_base64($task->{time});
  3369. }
  3370. }
  3371. if( %entries_array )
  3372. {
  3373. return {%entries_array};
  3374. }
  3375. return -1;
  3376. }
  3377. sub get_file_part
  3378. {
  3379. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3380. my ($file, $offset) = decrypt_params(@_);
  3381. if (!open(FILE, '<', $file))
  3382. {
  3383. logger "ERROR - Can't open file $file for reading.";
  3384. return -1;
  3385. }
  3386. binmode(FILE);
  3387. if($offset != 0)
  3388. {
  3389. return -1 unless seek FILE, $offset, 0;
  3390. }
  3391. my $data = "";
  3392. my ($n, $buf);
  3393. my $limit = $offset + 60 * 57 * 1000; #Max 3420Kb (1000 iterations) (top statistics ~ VIRT 116m, RES 47m)
  3394. while (($n = read FILE, $buf, 60 * 57) != 0 && $offset <= $limit ) {
  3395. $data .= $buf;
  3396. $offset += $n;
  3397. }
  3398. close(FILE);
  3399. if( $data ne "" )
  3400. {
  3401. my $b64zlib = encode_base64(compress($data,9));
  3402. return "$offset;$b64zlib";
  3403. }
  3404. else
  3405. {
  3406. return -1;
  3407. }
  3408. }
  3409. sub stop_update
  3410. {
  3411. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3412. my $home_id = decrypt_param(@_);
  3413. my $screen_id = create_screen_id(SCREEN_TYPE_UPDATE, $home_id);
  3414. system('screen -S '.$screen_id.' -p 0 -X stuff $\'\003\'');
  3415. if ($? == 0)
  3416. {
  3417. return 0;
  3418. }
  3419. return 1
  3420. }
  3421. sub shell_action
  3422. {
  3423. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3424. my ($action, $arguments) = decrypt_params(@_);
  3425. if($action eq 'remove_file')
  3426. {
  3427. chomp($arguments);
  3428. unlink($arguments);
  3429. return "1;";
  3430. }
  3431. elsif($action eq 'remove_recursive')
  3432. {
  3433. my @items = split(';', $arguments);
  3434. foreach my $item ( @items ) {
  3435. chomp($item);
  3436. if(-d $item)
  3437. {
  3438. pathrmdir($item);
  3439. }
  3440. else
  3441. {
  3442. unlink($item);
  3443. }
  3444. }
  3445. return "1;";
  3446. }
  3447. elsif($action eq 'create_dir')
  3448. {
  3449. chomp($arguments);
  3450. mkpath($arguments);
  3451. return "1;";
  3452. }
  3453. elsif($action eq 'move')
  3454. {
  3455. my($src, $dest) = split(';', $arguments);
  3456. chomp($src);
  3457. chomp($dest);
  3458. if(-d $src)
  3459. {
  3460. $dest = Path::Class::Dir->new($dest, basename($src));
  3461. dirmove($src, $dest);
  3462. }
  3463. else
  3464. {
  3465. fmove($src, $dest);
  3466. }
  3467. return "1;";
  3468. }
  3469. elsif($action eq 'rename')
  3470. {
  3471. my($src, $dest) = split(';', $arguments);
  3472. chomp($src);
  3473. chomp($dest);
  3474. if(-d $src)
  3475. {
  3476. dirmove($src, $dest);
  3477. }
  3478. else
  3479. {
  3480. fmove($src, $dest);
  3481. }
  3482. return "1;";
  3483. }
  3484. elsif($action eq 'copy')
  3485. {
  3486. my($src, $dest) = split(';', $arguments);
  3487. chomp($src);
  3488. chomp($dest);
  3489. if(-d $src)
  3490. {
  3491. $dest = Path::Class::Dir->new($dest, basename($src));
  3492. dircopy($src, $dest);
  3493. }
  3494. else
  3495. {
  3496. fcopy($src, $dest);
  3497. }
  3498. return "1;";
  3499. }
  3500. elsif($action eq 'touch')
  3501. {
  3502. chomp($arguments);
  3503. open(FH, '>', $arguments);
  3504. print FH "";
  3505. close(FH);
  3506. return "1;";
  3507. }
  3508. elsif($action eq 'size')
  3509. {
  3510. chomp($arguments);
  3511. my $size = 0;
  3512. if(-d $arguments)
  3513. {
  3514. find(sub { $size += -s }, $arguments ? $arguments : '.');
  3515. }
  3516. else
  3517. {
  3518. $size += (stat($arguments))[7];
  3519. }
  3520. return "1;" . encode_list($size);
  3521. }
  3522. elsif($action eq 'get_cpu_usage')
  3523. {
  3524. my %prev_idle;
  3525. my %prev_total;
  3526. open(STAT, '/proc/stat');
  3527. while (<STAT>) {
  3528. next unless /^cpu([0-9]+)/;
  3529. my @stat = split /\s+/, $_;
  3530. $prev_idle{$1} = $stat[4];
  3531. $prev_total{$1} = $stat[1] + $stat[2] + $stat[3] + $stat[4];
  3532. }
  3533. close STAT;
  3534. sleep 1;
  3535. my %idle;
  3536. my %total;
  3537. open(STAT, '/proc/stat');
  3538. while (<STAT>) {
  3539. next unless /^cpu([0-9]+)/;
  3540. my @stat = split /\s+/, $_;
  3541. $idle{$1} = $stat[4];
  3542. $total{$1} = $stat[1] + $stat[2] + $stat[3] + $stat[4];
  3543. }
  3544. close STAT;
  3545. my %cpu_percent_usage;
  3546. foreach my $key ( keys %idle )
  3547. {
  3548. my $diff_idle = $idle{$key} - $prev_idle{$key};
  3549. my $diff_total = $total{$key} - $prev_total{$key};
  3550. my $percent = (100 * ($diff_total - $diff_idle)) / $diff_total;
  3551. $percent = sprintf "%.2f", $percent unless $percent == 0;
  3552. $cpu_percent_usage{$key} = encode_base64($percent);
  3553. }
  3554. return {%cpu_percent_usage};
  3555. }
  3556. elsif($action eq 'get_ram_usage')
  3557. {
  3558. my($total, $buffers, $cached, $free) = qw(0 0 0 0);
  3559. open(STAT, '/proc/meminfo');
  3560. while (<STAT>) {
  3561. $total += $1 if /MemTotal\:\s+(\d+) kB/;
  3562. $buffers += $1 if /Buffers\:\s+(\d+) kB/;
  3563. $cached += $1 if /Cached\:\s+(\d+) kB/;
  3564. $free += $1 if /MemFree\:\s+(\d+) kB/;
  3565. }
  3566. close STAT;
  3567. my $used = $total - $free - $cached - $buffers;
  3568. my $percent = 100 * $used / $total;
  3569. my %mem_usage;
  3570. $mem_usage{'used'} = encode_base64($used * 1024);
  3571. $mem_usage{'total'} = encode_base64($total * 1024);
  3572. $mem_usage{'percent'} = encode_base64($percent);
  3573. return {%mem_usage};
  3574. }
  3575. elsif($action eq 'get_disk_usage')
  3576. {
  3577. my($total, $used, $free) = split(' ', `df -lP 2>/dev/null|grep "^/dev/.*"|awk '{total+=\$2}{used+=\$3}{free+=\$4} END {print total, used, free}'`);
  3578. my $percent = 100 * $used / $total;
  3579. my %disk_usage;
  3580. $disk_usage{'free'} = encode_base64($free * 1024);
  3581. $disk_usage{'used'} = encode_base64($used * 1024);
  3582. $disk_usage{'total'} = encode_base64($total * 1024);
  3583. $disk_usage{'percent'} = encode_base64($percent);
  3584. return {%disk_usage};
  3585. }
  3586. elsif($action eq 'get_uptime')
  3587. {
  3588. open(STAT, '/proc/uptime');
  3589. my $uptime = 0;
  3590. while (<STAT>) {
  3591. $uptime += $1 if /^([0-9]+)/;
  3592. }
  3593. close STAT;
  3594. my %upsince;
  3595. $upsince{'0'} = encode_base64($uptime);
  3596. $upsince{'1'} = encode_base64(time - $uptime);
  3597. return {%upsince};
  3598. }
  3599. elsif($action eq 'get_tasklist')
  3600. {
  3601. my %taskList;
  3602. $taskList{'task'} = encode_base64(qx[top -b -c -i -w512 -n2 -o+%CPU|awk '/^top/{i++}i==2'|grep 'PID' -A 30]);
  3603. return {%taskList};
  3604. }
  3605. elsif($action eq 'get_timestamp')
  3606. {
  3607. return "1;" . encode_list(time);
  3608. }
  3609. return 0;
  3610. }
  3611. sub remote_query
  3612. {
  3613. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3614. my ($protocol, $game_type, $ip, $c_port, $q_port, $s_port) = decrypt_params(@_);
  3615. my $command = "which php-cgi 2>&1;echo \$?";
  3616. my @cmdret = qx($command);
  3617. chomp(@cmdret);
  3618. my $ret = pop(@cmdret);
  3619. chomp($ret);
  3620. if ("X$ret" ne "X0")
  3621. {
  3622. return -1;
  3623. }
  3624. my $PHP_CGI = "@cmdret";
  3625. my $php_query_dir = Path::Class::Dir->new(AGENT_RUN_DIR, 'php-query');
  3626. if($protocol eq 'lgsl')
  3627. {
  3628. chdir($php_query_dir->subdir('lgsl'));
  3629. my $cmd = $PHP_CGI .
  3630. " -f lgsl_feed.php" .
  3631. " lgsl_type=" . $game_type .
  3632. " ip=" . $ip .
  3633. " c_port=" . $c_port .
  3634. " q_port=" . $q_port .
  3635. " s_port=" . $s_port .
  3636. " request=sp";
  3637. my $response = `$cmd`;
  3638. chomp($response);
  3639. chdir(AGENT_RUN_DIR);
  3640. if($response eq "FAILURE")
  3641. {
  3642. return -1;
  3643. }
  3644. return encode_base64($response, "");
  3645. }
  3646. elsif($protocol eq 'gameq')
  3647. {
  3648. chdir($php_query_dir->subdir('gameq'));
  3649. my $cmd = $PHP_CGI .
  3650. " -f gameq_feed.php" .
  3651. " game_type=" . $game_type .
  3652. " ip=" . $ip .
  3653. " c_port=" . $c_port .
  3654. " q_port=" . $q_port .
  3655. " s_port=" . $s_port;
  3656. my $response = `$cmd`;
  3657. chomp($response);
  3658. chdir(AGENT_RUN_DIR);
  3659. if($response eq "FAILURE")
  3660. {
  3661. return -1;
  3662. }
  3663. return encode_base64($response, "");
  3664. }
  3665. return -1;
  3666. }
  3667. sub send_steam_guard_code
  3668. {
  3669. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3670. my ($home_id, $sgc) = decrypt_params(@_);
  3671. my $screen_id = create_screen_id(SCREEN_TYPE_UPDATE, $home_id);
  3672. system('screen -S '.$screen_id.' -p 0 -X stuff "'.$sgc.'$(printf \\\\r)"');
  3673. if ($? == 0)
  3674. {
  3675. return 0;
  3676. }
  3677. return 1
  3678. }
  3679. sub steam_workshop
  3680. {
  3681. chomp(@_);
  3682. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3683. return steam_workshop_without_decrypt(decrypt_params(@_));
  3684. }
  3685. #### Run the steam client ####
  3686. ### @return 1 If installation started
  3687. ### @return -1 In error case.
  3688. sub steam_workshop_without_decrypt
  3689. {
  3690. my ($home_id, $mods_full_path,
  3691. $workshop_id, $mods_list,
  3692. $regex, $mods_backreference_index,
  3693. $variable, $place_after, $mod_string,
  3694. $string_separator, $config_file_path,
  3695. $post_install, $mod_names_list,
  3696. $anonymous_login, $user, $pass,
  3697. $download_method, $url_list, $filename_list) = @_;
  3698. # Creates mods path if it doesn't exist
  3699. if ( check_b4_chdir($mods_full_path) != 0)
  3700. {
  3701. return -1;
  3702. }
  3703. my $secure = "$mods_full_path/secure.sh";
  3704. my $home_path = $mods_full_path;
  3705. $home_path =~ s/('+)/'\"$1\"'/g;
  3706. my $sec = $secure;
  3707. $sec =~ s/('+)/'\"$1\"'/g;
  3708. open FILE, '>', $secure;
  3709. print FILE "chmod 771 '$home_path'\n".
  3710. "rm -f '$sec'";
  3711. close FILE;
  3712. my $screen_id = create_screen_id(SCREEN_TYPE_UPDATE, $home_id);
  3713. my @workshop_mods = split /,/, $mods_list;
  3714. my @installcmds;
  3715. if($download_method eq 'steamcmd')
  3716. {
  3717. my $steam_binary = STEAMCMD_CLIENT_BIN;
  3718. my $installSteamFile = $screen_id . "_workshop.txt";
  3719. my $installtxt = Path::Class::File->new(STEAMCMD_CLIENT_DIR, $installSteamFile);
  3720. open FILE, '>', $installtxt;
  3721. print FILE "\@ShutdownOnFailedCommand 1\n";
  3722. print FILE "\@NoPromptForPassword 1\n";
  3723. if($anonymous_login eq "0")
  3724. {
  3725. print FILE "login $user $pass\n";
  3726. }
  3727. else
  3728. {
  3729. print FILE "login anonymous\n";
  3730. }
  3731. print FILE "force_install_dir \"$mods_full_path\"\n";
  3732. foreach my $workshop_mod (@workshop_mods)
  3733. {
  3734. print FILE "workshop_download_item $workshop_id $workshop_mod\n";
  3735. }
  3736. print FILE "exit\n";
  3737. close FILE;
  3738. @installcmds = ("$steam_binary +runscript $installtxt +exit");
  3739. }
  3740. if($download_method eq 'steamapi')
  3741. {
  3742. my @urls = split /,/, $url_list;
  3743. my @filenames = split /,/, $filename_list;
  3744. my $index = 0;
  3745. foreach my $workshop_mod_id (@workshop_mods)
  3746. {
  3747. my $steamcmd_download_path = '/steamapps/workshop/content/'.$workshop_id.'/'.$workshop_mod_id.'/';
  3748. my $workshop_mod_path = $mods_full_path.$steamcmd_download_path;
  3749. if(!-d $workshop_mod_path && !mkpath $workshop_mod_path)
  3750. {
  3751. logger "Folder $workshop_mod_path could not be created.";
  3752. $index++;
  3753. next;
  3754. }
  3755. my $url = $urls[$index];
  3756. my $filename = $filenames[$index];
  3757. my $download_file_path = Path::Class::File->new($workshop_mod_path, "$filename");
  3758. $installcmds[$index] = "wget -O \"$download_file_path\" \"$url\"";
  3759. $index++;
  3760. }
  3761. }
  3762. my $log_file = Path::Class::File->new(SCREEN_LOGS_DIR, "screenlog.$screen_id");
  3763. backup_home_log($home_id, $log_file);
  3764. my $precmd = "";
  3765. my $postcmd = "";
  3766. $postcmd .= generate_post_install_scripts($mods_full_path, $workshop_id, $mods_list,
  3767. $regex, $mods_backreference_index,
  3768. $variable, $place_after, $mod_string,
  3769. $string_separator, $config_file_path,
  3770. $post_install, $mod_names_list);
  3771. my $bash_scripts_path = MANUAL_TMP_DIR . "/home_id_" . $home_id;
  3772. if ( check_b4_chdir($bash_scripts_path) != 0)
  3773. {
  3774. return -1;
  3775. }
  3776. my $installfile = create_bash_scripts($mods_full_path, $bash_scripts_path, $precmd, $postcmd, @installcmds);
  3777. my $screen_cmd = create_screen_cmd($screen_id, "./$installfile");
  3778. logger "Installing Steam Workshop content on server Home ID " . $home_id;
  3779. system($screen_cmd);
  3780. return 1;
  3781. }
  3782. sub generate_post_install_scripts
  3783. {
  3784. my ($mods_full_path, $workshop_id, $mods_list,
  3785. $regex, $mods_backreference_index,
  3786. $variable, $place_after, $mod_string,
  3787. $string_separator, $config_file_path,
  3788. $post_install, $mod_names_list) = @_;
  3789. my $post_install_scripts = "";
  3790. my $mods_info_path = Path::Class::Dir->new(AGENT_RUN_DIR, 'WorkshopModsInfo');
  3791. $post_install_scripts .= "mods_full_path=\"$mods_full_path\"\n".
  3792. "workshop_id=\"$workshop_id\"\n".
  3793. "regex=\"$regex\"\n".
  3794. "mods_backreference_index=\"$mods_backreference_index\"\n".
  3795. "variable=\"$variable\"\n".
  3796. "place_after=\"$place_after\"\n".
  3797. "string_separator=\"$string_separator\"\n".
  3798. "config_file_path=\"$config_file_path\"\n".
  3799. "mods_info_path=\"$mods_info_path/\"\n";
  3800. my @workshop_mods = split /,/, $mods_list;
  3801. my @mod_names = split /,/, $mod_names_list;
  3802. my $index = 0;
  3803. foreach my $workshop_mod_id (@workshop_mods)
  3804. {
  3805. my $steamcmd_download_path = '/steamapps/workshop/content/'.$workshop_id.'/'.$workshop_mod_id.'/';
  3806. my $workshop_mod_path = $mods_full_path.$steamcmd_download_path;
  3807. my $this_mod_string = $mod_string;
  3808. $this_mod_string =~ s/\%workshop_mod_id\%/$workshop_mod_id/g;
  3809. $post_install_scripts .= "mod_string[$index]=\"$this_mod_string\"\n".
  3810. "mod_name[$index]=\"".$mod_names[$index]."\"\n".
  3811. "workshop_mod_id[$index]=\"$workshop_mod_id\"\n".
  3812. "workshop_mod_path[$index]=\"$workshop_mod_path\"\n";
  3813. $index++;
  3814. }
  3815. $post_install_scripts .= 'if [ ! -e $config_file_path ];then'."\n".
  3816. ' if [ ! -d "$(dirname $config_file_path)" ];then mkdir -p "$(dirname $config_file_path)";fi'."\n".
  3817. ' echo -e "${place_after}\n${variable}" > $config_file_path'."\n".
  3818. 'fi'."\n".
  3819. 'i=0'."\n".
  3820. 'for mod_id in "${workshop_mod_id[@]}"'."\n".
  3821. 'do'."\n".
  3822. ' first_file="$(ls "${workshop_mod_path[$i]}"| sort -n | head -1)"'."\n";
  3823. my @post_install_lines = split /[\r\n]+/, $post_install;
  3824. foreach my $line (@post_install_lines) {
  3825. if($line ne ""){
  3826. $line =~ s/\%mods_full_path\%/\$mods_full_path/g;
  3827. $line =~ s/\%workshop_mod_id\%/\$mod_id/g;
  3828. $line =~ s/\%first_file\%/\$first_file/g;
  3829. $post_install_scripts .= "\t".$line."\n";
  3830. }
  3831. }
  3832. $post_install_scripts .= ' file_content=$(cat $config_file_path)'."\n".
  3833. ' if [[ $file_content =~ $regex ]]; then'."\n".
  3834. ' full_match="${BASH_REMATCH[0]}"'."\n".
  3835. ' mods_match="${BASH_REMATCH[$mods_backreference_index]}"'."\n".
  3836. ' found=1'."\n".
  3837. ' else'."\n".
  3838. ' found=0'."\n".
  3839. ' fi'."\n".
  3840. ' first_file_string="\%first_file%"'."\n".
  3841. ' if [ -z "${mod_string[$i]##*$first_file_string*}" ];then'."\n".
  3842. ' mod_string[$i]="${mod_string[$i]/$first_file_string/$first_file}"'."\n".
  3843. ' fi'."\n".
  3844. ' if [ $found == 1 ] && [ "X$full_match" != "X" ];then'."\n".
  3845. ' if [ "X$mods_match" == "X" ];then'."\n".
  3846. ' new_mods=$(echo -e "${full_match}${mod_string[$i]}")'."\n".
  3847. ' echo -e "${file_content/$full_match/$new_mods}">"$config_file_path"'."\n".
  3848. ' else'."\n".
  3849. ' if [ ! -z "${mods_match##*${mod_string[$i]}*}" ];then'."\n".
  3850. ' new_mods=$(echo -e "${full_match}${string_separator}${mod_string[$i]}")'."\n".
  3851. ' echo -e "${file_content/$full_match/$new_mods}">"$config_file_path"'."\n".
  3852. ' fi'."\n".
  3853. ' fi'."\n".
  3854. ' else'."\n".
  3855. ' if [ "X$place_after" == "X" ];then'."\n".
  3856. ' echo -e "${file_content}${variable}${mod_string[$i]}">"$config_file_path"'."\n".
  3857. ' else'."\n".
  3858. ' if [ -z "${file_content##*${place_after}*}" ];then'."\n".
  3859. ' new_var="${variable}${mod_string[$i]}"'."\n".
  3860. ' place_after_esc=$(echo -e "$place_after"|sed -e \'s/[]\\/$*.^[]/\\\\&/g\')'."\n".
  3861. ' echo -e "$file_content"|sed \'/\'$place_after_esc\'/a \'$new_var>"$config_file_path"'."\n".
  3862. ' else'."\n".
  3863. ' echo -e "${file_content}${place_after}\n${variable}${mod_string[$i]}">"$config_file_path"'."\n".
  3864. ' fi'."\n".
  3865. ' fi'."\n".
  3866. ' fi'."\n".
  3867. ' if [ ! -d "${mods_info_path}" ];then mkdir -p "${mods_info_path}";fi'."\n".
  3868. ' echo "${mod_name[$i]}" > "${mods_info_path}${mod_string[$i]}.ogpmod"'."\n".
  3869. ' i=$(expr $i + 1)'."\n".
  3870. 'done'."\n";
  3871. return "$post_install_scripts";
  3872. }
  3873. sub get_workshop_mods_info()
  3874. {
  3875. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3876. my $mods_info_dir_path = Path::Class::Dir->new(AGENT_RUN_DIR, 'WorkshopModsInfo');
  3877. if(-d $mods_info_dir_path)
  3878. {
  3879. opendir(MODS_INFO_DIR, $mods_info_dir_path) or return -1;
  3880. my @mods_info;
  3881. while(my $mod_info_file = readdir(MODS_INFO_DIR))
  3882. {
  3883. if($mod_info_file =~ /\.ogpmod$/)
  3884. {
  3885. my $mod_info_file_path = Path::Class::File->new($mods_info_dir_path, $mod_info_file);
  3886. if(open(my $fh, '<:encoding(UTF-8)', $mod_info_file_path))
  3887. {
  3888. my $row = <$fh>;
  3889. chomp $row;
  3890. if($row ne "")
  3891. {
  3892. my ($string_name, $ext) = split(/\.ogp/, $mod_info_file);
  3893. push @mods_info, "$string_name:$row";
  3894. }
  3895. close($fh);
  3896. }
  3897. }
  3898. }
  3899. closedir(MODS_INFO_DIR);
  3900. return "1;".encode_list(@mods_info);
  3901. }
  3902. return -1;
  3903. }
  3904. sub get_setting_using_api
  3905. {
  3906. my ($setting_name) = @_;
  3907. if(defined WEB_API_URL && WEB_API_URL ne "" && defined WEB_ADMIN_API_KEY && WEB_ADMIN_API_KEY ne ""){
  3908. my $url = WEB_API_URL . "?setting/get&setting_name=" . $setting_name . "&token=" . WEB_ADMIN_API_KEY;
  3909. my $ua = LWP::UserAgent->new;
  3910. $ua->agent('Mozilla/5.0');
  3911. $ua->timeout(5);
  3912. $ua->ssl_opts( verify_hostname => 0 ,SSL_verify_mode => 0x00);
  3913. my $response = $ua->get($url);
  3914. return $response->decoded_content();
  3915. }
  3916. return -1;
  3917. }
  3918. sub is_integer {
  3919. defined $_[0] && $_[0] =~ /^[+-]?\d+$/;
  3920. }