ogp_agent.pl 118 KB

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