ogp_agent.pl 116 KB

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