ogp_agent.pl 125 KB

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