ogp_agent.pl 102 KB

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