ogp_agent.pl 102 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918
  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. print FILE "rm -f $destination/postinstall.sh\n";
  1482. close FILE;
  1483. chmod 0755, $postcmdfile;
  1484. my $screen_id = create_screen_id("post_script", $pid);
  1485. my $cli_bin = create_screen_cmd($screen_id, "bash $postcmdfile");
  1486. system($cli_bin);
  1487. }
  1488. }
  1489. else
  1490. {
  1491. logger
  1492. "Unable to fetch $url, or save to $download_file_path. Retval: ".$response->status_line;
  1493. exit(0);
  1494. }
  1495. # Child process must exit.
  1496. exit(0);
  1497. }
  1498. else
  1499. {
  1500. logger "Download process for $download_file_path has pid number $pid.";
  1501. return "$pid";
  1502. }
  1503. }
  1504. sub lock_additional_files{
  1505. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1506. my ($homedir, $files, $action) = &decrypt_params(@_);
  1507. return lock_additional_files_logic($homedir, $files, $action);
  1508. }
  1509. sub lock_additional_files_logic{
  1510. my ($homedir, $filesToLock, $action, $returnType) = @_;
  1511. logger "Locking additional files specified in the XML.";
  1512. my $commandStr = "";
  1513. $filesToLock = startup_comma_format_to_multiline($filesToLock);
  1514. $filesToLock = replace_OGP_Env_Vars("", $homedir, $filesToLock);
  1515. my @filesToProcess = split /[\r\n]+/, $filesToLock;
  1516. foreach my $line (@filesToProcess) {
  1517. my $fullPath = $homedir . "/" . $line;
  1518. if($action eq "lock"){
  1519. if(defined $returnType && $returnType eq "str"){
  1520. $commandStr .= "echo '".$SUDOPASSWD."' | sudo -S -p \"\" sh -c \"" . secure_path_without_decrypt("chattr+i", $fullPath, $returnType) . "\" > /dev/null 2>&1" . "\n";
  1521. $commandStr .= "echo '".$SUDOPASSWD."' | sudo -S -p \"\" sh -c \"" . secure_path_without_decrypt("chattr+i", $line, $returnType) . "\" > /dev/null 2>&1" . "\n";
  1522. }else{
  1523. secure_path_without_decrypt("chattr+i", $fullPath);
  1524. secure_path_without_decrypt("chattr+i", $line);
  1525. }
  1526. }else{
  1527. if(defined $returnType && $returnType eq "str"){
  1528. $commandStr .= "echo '".$SUDOPASSWD."' | sudo -S -p \"\" sh -c \"" . secure_path_without_decrypt("chattr-i", $fullPath, $returnType) . "\" > /dev/null 2>&1" . "\n";
  1529. $commandStr .= "echo '".$SUDOPASSWD."' | sudo -S -p \"\" sh -c \"" . secure_path_without_decrypt("chattr-i", $line, $returnType) . "\" > /dev/null 2>&1" . "\n";
  1530. }else{
  1531. secure_path_without_decrypt("chattr-i", $fullPath);
  1532. secure_path_without_decrypt("chattr-i", $line);
  1533. }
  1534. }
  1535. }
  1536. if($commandStr ne ""){
  1537. return $commandStr;
  1538. }
  1539. return "";
  1540. }
  1541. sub run_before_start_commands
  1542. {
  1543. #return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1544. my ($server_id, $homedir, $beforestartcmd) = @_;
  1545. if ($homedir ne "" && $server_id ne ""){
  1546. # Run any prestart scripts
  1547. if (defined $beforestartcmd && $beforestartcmd ne "")
  1548. {
  1549. logger "Running pre-start XML commands before starting server ID $server_id with a home directory of $homedir.";
  1550. my @prestartcmdlines = split /[\r\n]+/, $beforestartcmd;
  1551. my $prestartcmdfile = $homedir."/".'prestart_ogp.sh';
  1552. open FILE, '>', $prestartcmdfile;
  1553. print FILE "#!/bin/bash" . "\n";
  1554. print FILE "cd $homedir\n";
  1555. foreach my $line (@prestartcmdlines) {
  1556. print FILE "$line\n";
  1557. }
  1558. print FILE "rm -f $prestartcmdfile\n";
  1559. close FILE;
  1560. chmod 0755, $prestartcmdfile;
  1561. system("bash $prestartcmdfile");
  1562. }
  1563. }else{
  1564. return -2;
  1565. }
  1566. return 1;
  1567. }
  1568. sub multiline_to_startup_comma_format{
  1569. my ($multiLineVar) = @_;
  1570. $multiLineVar =~ s/,//g; # commas are invalid anyways in bash
  1571. $multiLineVar =~ s/[\r]+//g;
  1572. $multiLineVar =~ s/[\n]+/{OGPNEWLINE}/g;
  1573. return $multiLineVar;
  1574. }
  1575. sub multiline_to_bash_commands{
  1576. my ($multiLineVar) = @_;
  1577. $multiLineVar =~ s/[\n]+/ && /g;
  1578. return $multiLineVar;
  1579. }
  1580. sub startup_comma_format_to_multiline{
  1581. my ($multiLineVar) = @_;
  1582. $multiLineVar =~ s/{OGPNEWLINE}/\n/g;
  1583. return $multiLineVar;
  1584. }
  1585. sub create_secure_script
  1586. {
  1587. my ($home_path, $exec_folder_path, $exec_path) = @_;
  1588. secure_path_without_decrypt('chattr-i', $home_path);
  1589. my $secure = "$home_path/secure.sh";
  1590. $home_path =~ s/('+)/'\"$1\"'/g;
  1591. $exec_folder_path =~ s/('+)/'\"$1\"'/g;
  1592. $exec_path =~ s/('+)/'\"$1\"'/g;
  1593. my $sec = $secure;
  1594. $sec =~ s/('+)/'\"$1\"'/g;
  1595. open FILE, '>', $secure;
  1596. print FILE "chmod 771 '$exec_folder_path'\n".
  1597. "chmod 750 '$exec_path'\n".
  1598. "chmod +x '$exec_path'\n".
  1599. "chattr +i '$exec_path'\n".
  1600. "rm -f '$sec'";
  1601. close FILE;
  1602. chmod 0770, $secure;
  1603. sudo_exec_without_decrypt("chown 0:0 '$sec'");
  1604. return 0;
  1605. }
  1606. sub check_b4_chdir
  1607. {
  1608. my ( $path ) = @_;
  1609. my $uid = `id -u`;
  1610. chomp $uid;
  1611. my $gid = `id -g`;
  1612. chomp $gid;
  1613. if (!-e $path)
  1614. {
  1615. logger "$path does not exist yet. Trying to create it...";
  1616. if (!mkpath($path))
  1617. {
  1618. logger "Error creating $path . Errno: $!";
  1619. return -1;
  1620. }
  1621. # Set perms on it as well
  1622. sudo_exec_without_decrypt('chown -Rf '.$uid.':'.$gid.' \''.$path.'\'');
  1623. }
  1624. else
  1625. {
  1626. # File or directory already exists
  1627. # Make sure it's owned by the agent
  1628. secure_path_without_decrypt('chattr-i', $path);
  1629. }
  1630. if (!chdir $path)
  1631. {
  1632. logger "Unable to change dir to '$path'.";
  1633. return -1;
  1634. }
  1635. return 0;
  1636. }
  1637. sub create_bash_scripts
  1638. {
  1639. my ( $home_path, $bash_scripts_path, $precmd, $postcmd, @installcmds ) = @_;
  1640. $home_path =~ s/('+)/'\"$1\"'/g;
  1641. $bash_scripts_path =~ s/('+)/'\"$1\"'/g;
  1642. my @precmdlines = split /[\r\n]+/, $precmd;
  1643. my $precmdfile = 'preinstall.sh';
  1644. open FILE, '>', $precmdfile;
  1645. print FILE "cd '$home_path'\n";
  1646. foreach my $line (@precmdlines) {
  1647. print FILE "$line\n";
  1648. }
  1649. close FILE;
  1650. chmod 0755, $precmdfile;
  1651. my @postcmdlines = split /[\r\n]+/, $postcmd;
  1652. my $postcmdfile = 'postinstall.sh';
  1653. open FILE, '>', $postcmdfile;
  1654. print FILE "cd '$home_path'\n";
  1655. foreach my $line (@postcmdlines) {
  1656. print FILE "$line\n";
  1657. }
  1658. print FILE "cd '$home_path'\n".
  1659. "echo '".$SUDOPASSWD."' | sudo -S -p \"\" bash secure.sh\n".
  1660. "rm -f secure.sh\n".
  1661. "cd '$bash_scripts_path'\n".
  1662. "rm -f preinstall.sh\n".
  1663. "rm -f postinstall.sh\n".
  1664. "rm -f runinstall.sh\n";
  1665. close FILE;
  1666. chmod 0755, $postcmdfile;
  1667. my $installfile = 'runinstall.sh';
  1668. open FILE, '>', $installfile;
  1669. print FILE "#!/bin/bash\n".
  1670. "cd '$bash_scripts_path'\n".
  1671. "./$precmdfile\n";
  1672. foreach my $installcmd (@installcmds)
  1673. {
  1674. print FILE "$installcmd\n";
  1675. }
  1676. print FILE "wait ".'${!}'."\n".
  1677. "cd '$bash_scripts_path'\n".
  1678. "./$postcmdfile\n";
  1679. close FILE;
  1680. chmod 0755, $installfile;
  1681. return $installfile;
  1682. }
  1683. #### Run the rsync update ####
  1684. ### @return 1 If update started
  1685. ### @return 0 In error case.
  1686. sub start_rsync_install
  1687. {
  1688. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1689. my ($home_id, $home_path, $url, $exec_folder_path, $exec_path, $precmd, $postcmd, $filesToLockUnlock) = decrypt_params(@_);
  1690. if ( check_b4_chdir($home_path) != 0)
  1691. {
  1692. return 0;
  1693. }
  1694. secure_path_without_decrypt('chattr-i', $home_path);
  1695. create_secure_script($home_path, $exec_folder_path, $exec_path);
  1696. my $bash_scripts_path = MANUAL_TMP_DIR . "/home_id_" . $home_id;
  1697. if ( check_b4_chdir($bash_scripts_path) != 0)
  1698. {
  1699. return 0;
  1700. }
  1701. # Rsync install require the rsync binary to exist in the system
  1702. # to enable this functionality.
  1703. my $rsync_binary = Path::Class::File->new("/usr/bin", "rsync");
  1704. if (!-f $rsync_binary)
  1705. {
  1706. logger "Failed to start rsync update from "
  1707. . $url
  1708. . " to $home_path. Error: Rsync client not installed.";
  1709. return 0;
  1710. }
  1711. my $screen_id = create_screen_id(SCREEN_TYPE_UPDATE, $home_id);
  1712. my $log_file = Path::Class::File->new(SCREEN_LOGS_DIR, "screenlog.$screen_id");
  1713. if(defined $filesToLockUnlock && $filesToLockUnlock ne ""){
  1714. $postcmd .= "\n" . lock_additional_files_logic($home_path, $filesToLockUnlock, "lock", "str");
  1715. }
  1716. backup_home_log( $home_id, $log_file );
  1717. my $path = $home_path;
  1718. $path =~ s/('+)/'\"$1\"'/g;
  1719. my @installcmds = ("/usr/bin/rsync --archive --compress --copy-links --update --verbose rsync://$url '$path'");
  1720. my $installfile = create_bash_scripts( $home_path, $bash_scripts_path, $precmd, $postcmd, @installcmds );
  1721. my $screen_cmd = create_screen_cmd($screen_id, "./$installfile");
  1722. logger "Running rsync update: /usr/bin/rsync --archive --compress --copy-links --update --verbose rsync://$url '$home_path'";
  1723. system($screen_cmd);
  1724. chdir AGENT_RUN_DIR;
  1725. return 1;
  1726. }
  1727. ### @return PID of the download process if started succesfully.
  1728. ### @return -1 If could not create temporary download directory.
  1729. ### @return -2 If could not create destination directory.
  1730. ### @return -3 If resources unavailable.
  1731. sub master_server_update
  1732. {
  1733. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1734. my ($home_id,$home_path,$ms_home_id,$ms_home_path,$exec_folder_path,$exec_path,$precmd,$postcmd) = decrypt_params(@_);
  1735. if ( check_b4_chdir($home_path) != 0)
  1736. {
  1737. return 0;
  1738. }
  1739. secure_path_without_decrypt('chattr-i', $home_path);
  1740. create_secure_script($home_path, $exec_folder_path, $exec_path);
  1741. my $bash_scripts_path = MANUAL_TMP_DIR . "/home_id_" . $home_id;
  1742. if ( check_b4_chdir($bash_scripts_path) != 0)
  1743. {
  1744. return 0;
  1745. }
  1746. my $screen_id = create_screen_id(SCREEN_TYPE_UPDATE, $home_id);
  1747. my $log_file = Path::Class::File->new(SCREEN_LOGS_DIR, "screenlog.$screen_id");
  1748. backup_home_log( $home_id, $log_file );
  1749. my $my_home_path = $home_path;
  1750. $my_home_path =~ s/('+)/'\"$1\"'/g;
  1751. $exec_path =~ s/\Q$home_path\E//g;
  1752. $exec_path =~ s/^\///g;
  1753. $exec_path =~ s/('+)/'\"$1\"'/g;
  1754. $ms_home_path =~ s/('+)/'\"$1\"'/g;
  1755. my @installcmds = ("cd '$ms_home_path'");
  1756. ## Copy files that match the extensions listed at extPatterns.txt
  1757. open(EXT_PATTERNS, '<', Path::Class::File->new(AGENT_RUN_DIR, "extPatterns.txt"))
  1758. || logger "Error reading patterns file $!";
  1759. my @ext_paterns = <EXT_PATTERNS>;
  1760. foreach my $patern (@ext_paterns)
  1761. {
  1762. chop $patern;
  1763. push (@installcmds, "find -iname \\\*.$patern -exec cp -Rfp --parents {} '$my_home_path'/ \\\;");
  1764. }
  1765. close EXT_PATTERNS;
  1766. ## Copy the server executable so it can be secured with chattr +i
  1767. push (@installcmds, "cp -vf --parents '$exec_path' '$my_home_path'");
  1768. ## Do symlinks for each of the other files
  1769. push (@installcmds, "cp -vuRfs '$ms_home_path'/* '$my_home_path'");
  1770. my $installfile = create_bash_scripts( $home_path, $bash_scripts_path, $precmd, $postcmd, @installcmds );
  1771. my $screen_cmd = create_screen_cmd($screen_id, "./$installfile");
  1772. logger "Running master server update from home ID $home_id to home ID $ms_home_id";
  1773. system($screen_cmd);
  1774. chdir AGENT_RUN_DIR;
  1775. return 1;
  1776. }
  1777. sub steam_cmd
  1778. {
  1779. chomp(@_);
  1780. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1781. return steam_cmd_without_decrypt(decrypt_params(@_));
  1782. }
  1783. #### Run the steam client ####
  1784. ### @return 1 If update started
  1785. ### @return 0 In error case.
  1786. sub steam_cmd_without_decrypt
  1787. {
  1788. my ($home_id, $home_path, $mod, $modname, $betaname, $betapwd, $user, $pass, $guard, $exec_folder_path, $exec_path, $precmd, $postcmd, $cfg_os, $filesToLockUnlock) = @_;
  1789. if ( check_b4_chdir($home_path) != 0)
  1790. {
  1791. return 0;
  1792. }
  1793. secure_path_without_decrypt('chattr-i', $home_path);
  1794. create_secure_script($home_path, $exec_folder_path, $exec_path);
  1795. my $bash_scripts_path = MANUAL_TMP_DIR . "/home_id_" . $home_id;
  1796. if ( check_b4_chdir($bash_scripts_path) != 0)
  1797. {
  1798. return 0;
  1799. }
  1800. my $screen_id = create_screen_id(SCREEN_TYPE_UPDATE, $home_id);
  1801. my $screen_id_for_txt_update = substr ($screen_id, rindex($screen_id, '_') + 1);
  1802. my $steam_binary = Path::Class::File->new(STEAMCMD_CLIENT_DIR, "steamcmd.sh");
  1803. my $installSteamFile = $screen_id_for_txt_update . "_install.txt";
  1804. my $installtxt = Path::Class::File->new(STEAMCMD_CLIENT_DIR, $installSteamFile);
  1805. open FILE, '>', $installtxt;
  1806. print FILE "\@ShutdownOnFailedCommand 1\n";
  1807. print FILE "\@NoPromptForPassword 1\n";
  1808. if($cfg_os eq 'windows')
  1809. {
  1810. print FILE "\@sSteamCmdForcePlatformType windows\n";
  1811. }
  1812. if($guard ne '')
  1813. {
  1814. print FILE "set_steam_guard_code $guard\n";
  1815. }
  1816. if($user ne '' && $user ne 'anonymous')
  1817. {
  1818. print FILE "login $user $pass\n";
  1819. }
  1820. else
  1821. {
  1822. print FILE "login anonymous\n";
  1823. }
  1824. print FILE "force_install_dir \"$home_path\"\n";
  1825. if($modname ne "")
  1826. {
  1827. print FILE "app_set_config $mod mod $modname\n";
  1828. print FILE "app_update $mod mod $modname validate\n";
  1829. }
  1830. if($betaname ne "" && $betapwd ne "")
  1831. {
  1832. print FILE "app_update $mod -beta $betaname -betapassword $betapwd\n";
  1833. }
  1834. elsif($betaname ne "" && $betapwd eq "")
  1835. {
  1836. print FILE "app_update $mod -beta $betaname\n";
  1837. }
  1838. else
  1839. {
  1840. print FILE "app_update $mod\n";
  1841. }
  1842. print FILE "exit\n";
  1843. close FILE;
  1844. my $log_file = Path::Class::File->new(SCREEN_LOGS_DIR, "screenlog.$screen_id");
  1845. backup_home_log( $home_id, $log_file );
  1846. my $postcmd_mod = $postcmd;
  1847. if(defined $filesToLockUnlock && $filesToLockUnlock ne ""){
  1848. $postcmd_mod .= "\n" . lock_additional_files_logic($home_path, $filesToLockUnlock, "lock", "str");
  1849. }
  1850. my @installcmds = ("$steam_binary +runscript $installtxt +exit");
  1851. my $installfile = create_bash_scripts( $home_path, $bash_scripts_path, $precmd, $postcmd_mod, @installcmds );
  1852. my $screen_cmd = create_screen_cmd($screen_id, "./$installfile");
  1853. logger "Running steam update: $steam_binary +runscript $installtxt +exit";
  1854. system($screen_cmd);
  1855. return 1;
  1856. }
  1857. sub fetch_steam_version
  1858. {
  1859. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1860. my ($appId, $pureOutput) = &decrypt_params(@_);
  1861. my $steam_binary = Path::Class::File->new(STEAMCMD_CLIENT_DIR, "steamcmd.sh");
  1862. my $steam_options = "+login anonymous +app_info_update 1 +app_info_print \"$appId\" +quit";
  1863. 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';
  1864. logger "Getting latest version info for AppId $appId";
  1865. my $response = `$steam_binary $steam_options $grep`;
  1866. return $response;
  1867. }
  1868. sub installed_steam_version
  1869. {
  1870. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1871. my ($game_home, $mod, $pureOutput) = &decrypt_params(@_);
  1872. my $appFile = $game_home."/steamapps/appmanifest_$mod.acf";
  1873. my $grep = $pureOutput != "0" ? "" : '| grep buildid | tr \'[:blank:]"\' \' \' | tr -s \' \' | cut -d\' \' -f3';
  1874. if ( ! -f $appFile)
  1875. {
  1876. return "-10";
  1877. }
  1878. return `cat $appFile $grep`;
  1879. }
  1880. sub automatic_steam_update
  1881. {
  1882. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1883. my ($home_id, $game_home, $server_ip, $server_port, $exec_path, $exec_folder_path,
  1884. $control_protocol, $control_password, $control_type,
  1885. $appId, $modname, $betaname, $betapwd, $user, $pass, $guard, $precmd, $postcmd, $cfg_os, $filesToLockUnlock,
  1886. $startup_cmd, $cpu, $nice, $preStart, $envVars) = &decrypt_params(@_);
  1887. # Is the server currently running? if it is, we'll try to start it after updating.
  1888. my $isServerRunning = is_screen_running_without_decrypt(SCREEN_TYPE_HOME, $home_id) == 1 ? 1 : 0;
  1889. # Check if an update is already happening.
  1890. if (is_screen_running_without_decrypt(SCREEN_TYPE_UPDATE, $home_id) == 1)
  1891. {
  1892. logger("Update already running for server $home_id, unable to start automatic update.");
  1893. return -10;
  1894. }
  1895. # Stop the server if it's running.
  1896. if ($isServerRunning == 1)
  1897. {
  1898. logger("Stopping server $home_id for automatic update.");
  1899. if (stop_server_without_decrypt($home_id, $server_ip, $server_port, $control_protocol, $control_password, $control_type, $game_home) != 0)
  1900. {
  1901. logger("Failed to stop server $home_id for automatic update. Exiting update procedure.");
  1902. return -9
  1903. }
  1904. }
  1905. # 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.
  1906. 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)
  1907. {
  1908. logger("Failed to start steam_cmd for server $home_id.");
  1909. return -8;
  1910. } else {
  1911. if ($isServerRunning == 1)
  1912. {
  1913. while (1)
  1914. {
  1915. # If the update screen for $home_id isn't running, attempt to start the server.
  1916. if (is_screen_running_without_decrypt(SCREEN_TYPE_UPDATE, $home_id) == 0)
  1917. {
  1918. 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)
  1919. {
  1920. logger("Failed to start server $home_id after automatic update.");
  1921. return -7;
  1922. } else {
  1923. logger("Starting server $home_id after automatic update.");
  1924. return 1;
  1925. }
  1926. last;
  1927. }
  1928. sleep 5;
  1929. }
  1930. } else {
  1931. # Update was started, but server wasn't initially running.
  1932. return 2;
  1933. }
  1934. }
  1935. }
  1936. sub rsync_progress
  1937. {
  1938. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1939. my ($running_home) = &decrypt_param(@_);
  1940. logger "User requested progress on rsync job on home $running_home.";
  1941. if (-r $running_home)
  1942. {
  1943. $running_home =~ s/('+)/'"$1"'/g;
  1944. my $progress = `du -sk '$running_home'`;
  1945. chomp($progress);
  1946. my ($bytes, $junk) = split(/\s+/, $progress);
  1947. logger("Found $bytes and $junk");
  1948. return $bytes;
  1949. }
  1950. return "0";
  1951. }
  1952. sub is_file_download_in_progress
  1953. {
  1954. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1955. my ($pid) = &decrypt_param(@_);
  1956. logger "User requested if download is in progress with pid $pid.";
  1957. my @pids = `ps -ef`;
  1958. @pids = grep(/$pid/, @pids);
  1959. logger "Number of pids for file download: @pids";
  1960. if (@pids > '0')
  1961. {
  1962. return 1;
  1963. }
  1964. return 0;
  1965. }
  1966. ### \return 1 If file is uncompressed succesfully.
  1967. ### \return 0 If file does not exist.
  1968. ### \return -1 If file could not be uncompressed.
  1969. sub uncompress_file
  1970. {
  1971. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  1972. return uncompress_file_without_decrypt(decrypt_params(@_));
  1973. }
  1974. sub uncompress_file_without_decrypt
  1975. {
  1976. # File must include full path.
  1977. my ($file, $destination) = @_;
  1978. logger "Uncompression called for file $file to dir $destination.";
  1979. if (!-e $file)
  1980. {
  1981. logger "File $file could not be found for uncompression.";
  1982. return 0;
  1983. }
  1984. if (!-e $destination)
  1985. {
  1986. mkpath($destination, {error => \my $err});
  1987. if (@$err)
  1988. {
  1989. logger "Failed to create destination dir $destination.";
  1990. return 0;
  1991. }
  1992. }
  1993. my $ae = Archive::Extract->new(archive => $file);
  1994. if (!$ae)
  1995. {
  1996. logger "Could not create archive instance for file $file.";
  1997. return -1;
  1998. }
  1999. my $ok = $ae->extract(to => $destination);
  2000. if (!$ok)
  2001. {
  2002. logger "File $file could not be uncompressed.";
  2003. return -1;
  2004. }
  2005. logger "File uncompressed/extracted successfully.";
  2006. return 1;
  2007. }
  2008. ### \return 1 If files are compressed succesfully.
  2009. ### \return -1 If files could not be compressed.
  2010. sub compress_files
  2011. {
  2012. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2013. return compress_files_without_decrypt(decrypt_params(@_));
  2014. }
  2015. sub compress_files_without_decrypt
  2016. {
  2017. my ($files,$destination,$archive_name,$archive_type) = @_;
  2018. if (!-e $destination)
  2019. {
  2020. logger "compress_files: Destination path ( $destination ) could not be found.";
  2021. return -1;
  2022. }
  2023. chdir $destination;
  2024. my @items = split /\Q\n/, $files;
  2025. my @inventory;
  2026. if($archive_type eq "zip")
  2027. {
  2028. logger $archive_type." compression called, destination archive is: $destination$archive_name.$archive_type";
  2029. my $zip = Archive::Zip->new();
  2030. foreach my $item (@items) {
  2031. if(-e $item)
  2032. {
  2033. if (-f $item)
  2034. {
  2035. $zip->addFile( $item );
  2036. }
  2037. elsif (-d $item)
  2038. {
  2039. $zip->addTree( $item, $item );
  2040. }
  2041. }
  2042. }
  2043. # Save the file
  2044. unless ( $zip->writeToFileNamed($archive_name.'.zip') == AZ_OK ) {
  2045. logger "Write Error at $destination/$archive_name.$archive_type";
  2046. return -1
  2047. }
  2048. logger $archive_type." archive $destination$archive_name.$archive_type created successfully";
  2049. return 1;
  2050. }
  2051. elsif($archive_type eq "tbz")
  2052. {
  2053. logger $archive_type." compression called, destination archive is: $destination$archive_name.$archive_type";
  2054. my $tar = Archive::Tar->new;
  2055. foreach my $item (@items) {
  2056. if(-e $item)
  2057. {
  2058. if (-f $item)
  2059. {
  2060. $tar->add_files( $item );
  2061. }
  2062. elsif (-d $item)
  2063. {
  2064. @inventory = ();
  2065. find (sub { push @inventory, $File::Find::name }, $item);
  2066. $tar->add_files( @inventory );
  2067. }
  2068. }
  2069. }
  2070. # Save the file
  2071. unless ( $tar->write("$archive_name.$archive_type", COMPRESS_BZIP) ) {
  2072. logger "Write Error at $destination/$archive_name.$archive_type";
  2073. return -1
  2074. }
  2075. logger $archive_type." archive $destination$archive_name.$archive_type created successfully";
  2076. return 1;
  2077. }
  2078. elsif($archive_type eq "tgz")
  2079. {
  2080. logger $archive_type." compression called, destination archive is: $destination$archive_name.$archive_type";
  2081. my $tar = Archive::Tar->new;
  2082. foreach my $item (@items) {
  2083. if(-e $item)
  2084. {
  2085. if (-f $item)
  2086. {
  2087. $tar->add_files( $item );
  2088. }
  2089. elsif (-d $item)
  2090. {
  2091. @inventory = ();
  2092. find (sub { push @inventory, $File::Find::name }, $item);
  2093. $tar->add_files( @inventory );
  2094. }
  2095. }
  2096. }
  2097. # Save the file
  2098. unless ( $tar->write("$archive_name.$archive_type", COMPRESS_GZIP) ) {
  2099. logger "Write Error at $destination/$archive_name.$archive_type";
  2100. return -1
  2101. }
  2102. logger $archive_type." archive $destination$archive_name.$archive_type created successfully";
  2103. return 1;
  2104. }
  2105. elsif($archive_type eq "tar")
  2106. {
  2107. logger $archive_type." compression called, destination archive is: $destination$archive_name.$archive_type";
  2108. my $tar = Archive::Tar->new;
  2109. foreach my $item (@items) {
  2110. if(-e $item)
  2111. {
  2112. if (-f $item)
  2113. {
  2114. $tar->add_files( $item );
  2115. }
  2116. elsif (-d $item)
  2117. {
  2118. @inventory = ();
  2119. find (sub { push @inventory, $File::Find::name }, $item);
  2120. $tar->add_files( @inventory );
  2121. }
  2122. }
  2123. }
  2124. # Save the file
  2125. unless ( $tar->write("$archive_name.$archive_type") ) {
  2126. logger "Write Error at $destination/$archive_name.$archive_type";
  2127. return -1
  2128. }
  2129. logger $archive_type." archive $destination$archive_name.$archive_type created successfully";
  2130. return 1;
  2131. }
  2132. elsif($archive_type eq "bz2")
  2133. {
  2134. logger $archive_type." compression called.";
  2135. foreach my $item (@items) {
  2136. if(-e $item)
  2137. {
  2138. if (-f $item)
  2139. {
  2140. bzip2 $item => "$item.bz2";
  2141. }
  2142. elsif (-d $item)
  2143. {
  2144. @inventory = ();
  2145. find (sub { push @inventory, $File::Find::name }, $item);
  2146. foreach my $relative_item (@inventory) {
  2147. bzip2 $relative_item => "$relative_item.bz2";
  2148. }
  2149. }
  2150. }
  2151. }
  2152. logger $archive_type." archives created successfully at $destination";
  2153. return 1;
  2154. }
  2155. }
  2156. sub discover_ips
  2157. {
  2158. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2159. my ($check) = decrypt_params(@_);
  2160. if ($check ne "chk")
  2161. {
  2162. logger "Invalid parameter '$check' given for discover_ips function.";
  2163. return "";
  2164. }
  2165. my $iplist = "";
  2166. my $ipfound;
  2167. my $junk;
  2168. my @ipraw = `/sbin/ifconfig`;
  2169. while (<@ipraw>)
  2170. {
  2171. chomp;
  2172. next if $_ !~ /^inet:/ ;
  2173. logger "Found addr on line: $_";
  2174. ($junk, $ipfound) = split(":", $_);
  2175. next if $ipfound eq '';
  2176. next if $ipfound eq '127.0.0.1';
  2177. logger "Found an IP $ipfound";
  2178. $iplist .= "$ipfound,";
  2179. logger "IPlist is now $iplist";
  2180. }
  2181. while (<@ipraw>)
  2182. {
  2183. chomp;
  2184. next if $_ !~ /^addr:/ ;
  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. chop $iplist;
  2194. return "$iplist";
  2195. }
  2196. ### Return -1 In case of invalid param
  2197. ### Return 1;content in case of success
  2198. sub mon_stats
  2199. {
  2200. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2201. my ($mon_stats) = decrypt_params(@_);
  2202. if ($mon_stats ne "mon_stats")
  2203. {
  2204. logger "Invalid parameter '$mon_stats' given for $mon_stats function.";
  2205. return -1;
  2206. }
  2207. my @disk = `df -hP -x tmpfs`;
  2208. my $encoded_content = encode_list(@disk);
  2209. my @uptime = `uptime`;
  2210. $encoded_content .= encode_list(@uptime);
  2211. return "1;$encoded_content";
  2212. }
  2213. sub exec
  2214. {
  2215. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2216. my ($command) = decrypt_params(@_);
  2217. my @cmdret = `$command 2>/dev/null`;
  2218. my $encoded_content = encode_list(@cmdret);
  2219. return "1;$encoded_content";
  2220. }
  2221. # used in conjunction with the clone_home feature in the web panel
  2222. # this actually does the file copies
  2223. sub clone_home
  2224. {
  2225. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2226. my ($source_home, $dest_home, $owner) = decrypt_params(@_);
  2227. my ($time_start, $time_stop, $time_diff);
  2228. logger "Copying from $source_home to $dest_home...";
  2229. # check size of source_home, make sure we have space to copy
  2230. if (!-e $source_home)
  2231. {
  2232. logger "ERROR - $source_home does not exist";
  2233. return 0;
  2234. }
  2235. logger "Game home $source_home exists...copy will proceed";
  2236. # start the copy, and a timer
  2237. $time_start = time();
  2238. if (!dircopy("$source_home", "$dest_home"))
  2239. {
  2240. $time_stop = time();
  2241. $time_diff = $time_stop - $time_start;
  2242. logger
  2243. "Error occured after $time_diff seconds during copy of $source_home to $dest_home - $!";
  2244. return 0;
  2245. }
  2246. else
  2247. {
  2248. $time_stop = time();
  2249. $time_diff = $time_stop - $time_start;
  2250. logger
  2251. "Home clone completed successfully to $dest_home in $time_diff seconds";
  2252. return 1;
  2253. }
  2254. }
  2255. # used to delete the game home from the file system when it's removed from the panel
  2256. sub remove_home
  2257. {
  2258. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2259. my ($home_path_del) = decrypt_params(@_);
  2260. if (!-e $home_path_del)
  2261. {
  2262. logger "ERROR - $home_path_del does not exist...nothing to do";
  2263. return 0;
  2264. }
  2265. secure_path_without_decrypt('chattr-i', $home_path_del);
  2266. sleep 1 while ( !pathrmdir("$home_path_del") );
  2267. logger "Deletetion of $home_path_del successful!";
  2268. return 1;
  2269. }
  2270. sub restart_server
  2271. {
  2272. chomp(@_);
  2273. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2274. return restart_server_without_decrypt(decrypt_params(@_));
  2275. }
  2276. ### Restart the server
  2277. ## return -2 CANT STOP
  2278. ## return -1 CANT START (no startup file found that mach the home_id, port and ip)
  2279. ## return 1 Restart OK
  2280. sub restart_server_without_decrypt
  2281. {
  2282. my ($home_id, $server_ip, $server_port, $control_protocol,
  2283. $control_password, $control_type, $home_path, $server_exe, $run_dir,
  2284. $cmd, $cpu, $nice, $preStart, $envVars) = @_;
  2285. if (stop_server_without_decrypt($home_id, $server_ip,
  2286. $server_port, $control_protocol,
  2287. $control_password, $control_type, $home_path) == 0)
  2288. {
  2289. if (universal_start_without_decrypt($home_id, $home_path, $server_exe, $run_dir,
  2290. $cmd, $server_port, $server_ip, $cpu, $nice, $preStart, $envVars) == 1)
  2291. {
  2292. return 1;
  2293. }
  2294. else
  2295. {
  2296. return -1;
  2297. }
  2298. }
  2299. else
  2300. {
  2301. return -2;
  2302. }
  2303. }
  2304. sub sudo_exec
  2305. {
  2306. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2307. my $sudo_exec = &decrypt_param(@_);
  2308. return sudo_exec_without_decrypt($sudo_exec);
  2309. }
  2310. sub sudo_exec_without_decrypt
  2311. {
  2312. my ($sudo_exec) = @_;
  2313. $sudo_exec =~ s/('+)/'"$1"'/g;
  2314. logger "Running the following command \"" . $sudo_exec . "\" with sudo.";
  2315. my $command = "echo '$SUDOPASSWD'|sudo -kS -p \"\" su -c '$sudo_exec;echo \$?' root 2>&1";
  2316. my @cmdret = qx($command);
  2317. chomp(@cmdret);
  2318. my $ret = pop(@cmdret);
  2319. chomp($ret);
  2320. if ("X$ret" eq "X0")
  2321. {
  2322. logger "Command \"" . $sudo_exec . "\" was successfully run with sudo.";
  2323. return "1;".encode_list(@cmdret);
  2324. }
  2325. logger "Command \"" . $sudo_exec . "\" run with sudo failed with exit code $ret.";
  2326. return -1;
  2327. }
  2328. sub secure_path
  2329. {
  2330. chomp(@_);
  2331. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2332. return secure_path_without_decrypt(decrypt_params(@_));
  2333. }
  2334. sub secure_path_without_decrypt
  2335. {
  2336. my ($action, $file_path, $returnType) = @_;
  2337. my $checkIfFileExists = 1;
  2338. if(defined $returnType && $returnType eq "str"){
  2339. $checkIfFileExists = 0;
  2340. }
  2341. if($checkIfFileExists){
  2342. if(! -e $file_path){
  2343. return -1;
  2344. }
  2345. }
  2346. my $uid = `id -u`;
  2347. chomp $uid;
  2348. my $gid = `id -g`;
  2349. chomp $gid;
  2350. $file_path =~ s/('+)/'\"$1\"'/g;
  2351. if($action eq "chattr+i")
  2352. {
  2353. if(defined $returnType && $returnType eq "str"){
  2354. return 'chown -Rf '.$uid.':'.$gid.' \''.$file_path.'\' && chattr -Rf +i \''.$file_path.'\'';
  2355. }else{
  2356. return sudo_exec_without_decrypt('chown -Rf '.$uid.':'.$gid.' \''.$file_path.'\' && chattr -Rf +i \''.$file_path.'\'');
  2357. }
  2358. }
  2359. elsif($action eq "chattr-i")
  2360. {
  2361. if(defined $returnType && $returnType eq "str"){
  2362. return 'chattr -Rf -i \''.$file_path.'\' && chown -Rf '.$uid.':'.$gid.' \''.$file_path.'\'';
  2363. }else{
  2364. return sudo_exec_without_decrypt('chattr -Rf -i \''.$file_path.'\' && chown -Rf '.$uid.':'.$gid.' \''.$file_path.'\'');
  2365. }
  2366. }
  2367. return -1;
  2368. }
  2369. sub get_chattr
  2370. {
  2371. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2372. my ($file_path) = decrypt_params(@_);
  2373. my $file = $file_path;
  2374. $file_path =~ s/('+)/'\"$1\"'/g;
  2375. return sudo_exec_without_decrypt('(lsattr \''.$file_path.'\' | sed -e "s#'.$file.'##g")|grep -o i');
  2376. }
  2377. sub ftp_mgr
  2378. {
  2379. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2380. my ($action, $login, $password, $home_path) = decrypt_params(@_);
  2381. my $uid = `id -u`;
  2382. chomp $uid;
  2383. my $gid = `id -g`;
  2384. chomp $gid;
  2385. $login =~ s/('+)/'\"$1\"'/g;
  2386. $password =~ s/('+)/'\"$1\"'/g;
  2387. $home_path =~ s/('+)/'\"$1\"'/g;
  2388. if(!defined($Cfg::Preferences{ogp_manages_ftp}) || (defined($Cfg::Preferences{ogp_manages_ftp}) && $Cfg::Preferences{ogp_manages_ftp} eq "1")){
  2389. if( defined($Cfg::Preferences{ftp_method}) && $Cfg::Preferences{ftp_method} eq "IspConfig")
  2390. {
  2391. use constant ISPCONFIG_DIR => Path::Class::Dir->new(AGENT_RUN_DIR, 'IspConfig');
  2392. use constant FTP_USERS_DIR => Path::Class::Dir->new(ISPCONFIG_DIR, 'ftp_users');
  2393. if (!-d FTP_USERS_DIR && !mkdir FTP_USERS_DIR)
  2394. {
  2395. print "Could not create " . FTP_USERS_DIR . " directory $!.";
  2396. return -1;
  2397. }
  2398. chdir ISPCONFIG_DIR;
  2399. if($action eq "list")
  2400. {
  2401. my $users_list;
  2402. opendir(USERS, FTP_USERS_DIR);
  2403. while (my $username = readdir(USERS))
  2404. {
  2405. # Skip . and ..
  2406. next if $username =~ /^\./;
  2407. $users_list .= `php-cgi -f sites_ftp_user_get.php username=\'$username\'`;
  2408. }
  2409. closedir(USERS);
  2410. if( defined($users_list) )
  2411. {
  2412. return "1;".encode_list($users_list);
  2413. }
  2414. }
  2415. elsif($action eq "userdel")
  2416. {
  2417. return "1;".encode_list(`php-cgi -f sites_ftp_user_delete.php username=\'$login\'`);
  2418. }
  2419. elsif($action eq "useradd")
  2420. {
  2421. return "1;".encode_list(`php-cgi -f sites_ftp_user_add.php username=\'$login\' password=\'$password\' dir=\'$home_path\' uid=$uid gid=$gid`);
  2422. }
  2423. elsif($action eq "passwd")
  2424. {
  2425. return "1;".encode_list(`php-cgi -f sites_ftp_user_update.php type=passwd username=\'$login\' password=\'$password\'`);
  2426. }
  2427. elsif($action eq "show")
  2428. {
  2429. return "1;".encode_list(`php-cgi -f sites_ftp_user_get.php type=detail username=\'$login\'`);
  2430. }
  2431. elsif($action eq "usermod")
  2432. {
  2433. return "1;".encode_list(`php-cgi -f sites_ftp_user_update.php username=\'$login\' password=\'$password\'`);
  2434. }
  2435. }
  2436. elsif(defined($Cfg::Preferences{ftp_method}) && $Cfg::Preferences{ftp_method} eq "EHCP" && -e "/etc/init.d/ehcp")
  2437. {
  2438. use constant EHCP_DIR => Path::Class::Dir->new(AGENT_RUN_DIR, 'EHCP');
  2439. chdir EHCP_DIR;
  2440. my $phpScript;
  2441. my $phpOut;
  2442. chmod 0777, 'ehcp_ftp_log.txt';
  2443. # In order to access the FTP files, the vsftpd user needs to be added to the ogp group
  2444. sudo_exec_without_decrypt("usermod -a -G '$gid' ftp");
  2445. sudo_exec_without_decrypt("usermod -a -G '$gid' vsftpd");
  2446. if($action eq "list")
  2447. {
  2448. return "1;".encode_list(`php-cgi -f listAllUsers.php`);
  2449. }
  2450. elsif($action eq "userdel")
  2451. {
  2452. $phpScript = `php-cgi -f delAccount.php username=\'$login\'`;
  2453. $phpOut = `php-cgi -f syncftp.php`;
  2454. return $phpScript;
  2455. }
  2456. elsif($action eq "useradd")
  2457. {
  2458. $phpScript = `php-cgi -f addAccount.php username=\'$login\' password=\'$password\' dir=\'$home_path\' uid=$uid gid=$gid`;
  2459. $phpOut = `php-cgi -f syncftp.php`;
  2460. return $phpScript;
  2461. }
  2462. elsif($action eq "passwd")
  2463. {
  2464. $phpScript = `php-cgi -f updatePass.php username=\'$login\' password=\'$password\'`;
  2465. $phpOut = `php-cgi -f syncftp.php`;
  2466. return $phpScript ;
  2467. }
  2468. elsif($action eq "show")
  2469. {
  2470. return "1;".encode_list(`php-cgi -f showAccount.php username=\'$login\'`);
  2471. }
  2472. elsif($action eq "usermod")
  2473. {
  2474. $phpScript = `php-cgi -f updateInfo.php username=\'$login\' password=\'$password\'`;
  2475. $phpOut = `php-cgi -f syncftp.php`;
  2476. return $phpScript;
  2477. }
  2478. }
  2479. elsif(defined($Cfg::Preferences{ftp_method}) && $Cfg::Preferences{ftp_method} eq "proftpd" && -e $Cfg::Preferences{proftpd_conf_path})
  2480. {
  2481. chdir $Cfg::Preferences{proftpd_conf_path};
  2482. if($action eq "list")
  2483. {
  2484. my $users;
  2485. open(PASSWD, 'ftpd.passwd');
  2486. while (<PASSWD>) {
  2487. chomp;
  2488. my($login, $passwd, $uid, $gid, $gcos, $home, $shell) = split(/:/);
  2489. $users .= "$login\t$home\n";
  2490. }
  2491. close(PASSWD);
  2492. return "1;".encode_list($users);
  2493. }
  2494. elsif($action eq "userdel")
  2495. {
  2496. return sudo_exec_without_decrypt("ftpasswd --passwd --delete-user --name='$login'");
  2497. }
  2498. elsif($action eq "useradd")
  2499. {
  2500. return sudo_exec_without_decrypt("echo '$password' | ftpasswd --passwd --name='$login' --home='$home_path' --shell=/bin/false --uid=$uid --gid=$gid --stdin");
  2501. }
  2502. elsif($action eq "passwd")
  2503. {
  2504. return sudo_exec_without_decrypt("echo '$password' | ftpasswd --passwd --change-password --name='$login' --stdin");
  2505. }
  2506. elsif($action eq "show")
  2507. {
  2508. return 1;
  2509. }
  2510. elsif($action eq "usermod")
  2511. {
  2512. return 1;
  2513. }
  2514. chdir AGENT_RUN_DIR;
  2515. }
  2516. else
  2517. {
  2518. if($action eq "list")
  2519. {
  2520. return sudo_exec_without_decrypt("pure-pw list");
  2521. }
  2522. elsif($action eq "userdel")
  2523. {
  2524. return sudo_exec_without_decrypt("pure-pw userdel '$login' && pure-pw mkdb");
  2525. }
  2526. elsif($action eq "useradd")
  2527. {
  2528. return sudo_exec_without_decrypt("(echo '$password'; echo '$password') | pure-pw useradd '$login' -u $uid -g $gid -d '$home_path' && pure-pw mkdb");
  2529. }
  2530. elsif($action eq "passwd")
  2531. {
  2532. return sudo_exec_without_decrypt("(echo '$password'; echo '$password') | pure-pw passwd '$login' && pure-pw mkdb");
  2533. }
  2534. elsif($action eq "show")
  2535. {
  2536. return sudo_exec_without_decrypt("pure-pw show '$login'");
  2537. }
  2538. elsif($action eq "usermod")
  2539. {
  2540. my $update_account = "pure-pw usermod '$login' -u $uid -g $gid";
  2541. my @account_settings = split /[\n]+/, $password;
  2542. foreach my $setting (@account_settings) {
  2543. my ($key, $value) = split /[\t]+/, $setting;
  2544. if( $key eq 'Directory' )
  2545. {
  2546. $value =~ s/('+)/'\"$1\"'/g;
  2547. $update_account .= " -d '$value'";
  2548. }
  2549. if( $key eq 'Full_name' )
  2550. {
  2551. if( $value ne "" )
  2552. {
  2553. $value =~ s/('+)/'\"$1\"'/g;
  2554. $update_account .= " -c '$value'";
  2555. }
  2556. else
  2557. {
  2558. $update_account .= ' -c ""';
  2559. }
  2560. }
  2561. if( $key eq 'Download_bandwidth' && $value ne "" )
  2562. {
  2563. my $Download_bandwidth;
  2564. if($value eq 0)
  2565. {
  2566. $Download_bandwidth = "\"\"";
  2567. }
  2568. else
  2569. {
  2570. $Download_bandwidth = $value;
  2571. }
  2572. $update_account .= " -t " . $Download_bandwidth;
  2573. }
  2574. if( $key eq 'Upload___bandwidth' && $value ne "" )
  2575. {
  2576. my $Upload___bandwidth;
  2577. if($value eq 0)
  2578. {
  2579. $Upload___bandwidth = "\"\"";
  2580. }
  2581. else
  2582. {
  2583. $Upload___bandwidth = $value;
  2584. }
  2585. $update_account .= " -T " . $Upload___bandwidth;
  2586. }
  2587. if( $key eq 'Max_files' )
  2588. {
  2589. if( $value eq "0" )
  2590. {
  2591. $update_account .= ' -n ""';
  2592. }
  2593. elsif( $value ne "" )
  2594. {
  2595. $update_account .= " -n " . $value;
  2596. }
  2597. else
  2598. {
  2599. $update_account .= ' -n ""';
  2600. }
  2601. }
  2602. if( $key eq 'Max_size' )
  2603. {
  2604. if( $value ne "" && $value ne "0" )
  2605. {
  2606. $update_account .= " -N " . $value;
  2607. }
  2608. else
  2609. {
  2610. $update_account .= ' -N ""';
  2611. }
  2612. }
  2613. if( $key eq 'Ratio' && $value ne "" )
  2614. {
  2615. my($upload_ratio,$download_ratio) = split/:/,$value;
  2616. if($upload_ratio eq "0")
  2617. {
  2618. $upload_ratio = "\"\"";
  2619. }
  2620. $update_account .= " -q " . $upload_ratio;
  2621. if($download_ratio eq "0")
  2622. {
  2623. $download_ratio = "\"\"";
  2624. }
  2625. $update_account .= " -Q " . $download_ratio;
  2626. }
  2627. if( $key eq 'Allowed_client_IPs' )
  2628. {
  2629. if( $value ne "" )
  2630. {
  2631. $update_account .= " -r " . $value;
  2632. }
  2633. else
  2634. {
  2635. $update_account .= ' -r ""';
  2636. }
  2637. }
  2638. if( $key eq 'Denied__client_IPs' )
  2639. {
  2640. if( $value ne "" )
  2641. {
  2642. $update_account .= " -R " . $value;
  2643. }
  2644. else
  2645. {
  2646. $update_account .= ' -R ""';
  2647. }
  2648. }
  2649. if( $key eq 'Allowed_local__IPs' )
  2650. {
  2651. if( $value ne "" )
  2652. {
  2653. $update_account .= " -i " . $value;
  2654. }
  2655. else
  2656. {
  2657. $update_account .= ' -i ""';
  2658. }
  2659. }
  2660. if( $key eq 'Denied__local__IPs' )
  2661. {
  2662. if( $value ne "" )
  2663. {
  2664. $update_account .= " -I " . $value;
  2665. }
  2666. else
  2667. {
  2668. $update_account .= ' -I ""';
  2669. }
  2670. }
  2671. if( $key eq 'Max_sim_sessions' && $value ne "" )
  2672. {
  2673. $update_account .= " -y " . $value;
  2674. }
  2675. if ( $key eq 'Time_restrictions' )
  2676. {
  2677. if( $value eq "0000-0000")
  2678. {
  2679. $update_account .= ' -z ""';
  2680. }
  2681. elsif( $value ne "" )
  2682. {
  2683. $update_account .= " -z " . $value;
  2684. }
  2685. else
  2686. {
  2687. $update_account .= ' -z ""';
  2688. }
  2689. }
  2690. }
  2691. $update_account .=" && pure-pw mkdb";
  2692. # print $update_account;
  2693. return sudo_exec_without_decrypt($update_account);
  2694. }
  2695. }
  2696. }
  2697. return 0;
  2698. }
  2699. sub start_fastdl
  2700. {
  2701. if(-e Path::Class::File->new(FD_DIR, 'Settings.pm'))
  2702. {
  2703. system('perl FastDownload/ForkedDaemon.pm &');
  2704. sleep(1);
  2705. return 1;
  2706. }
  2707. else
  2708. {
  2709. return -2;
  2710. }
  2711. }
  2712. sub stop_fastdl
  2713. {
  2714. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2715. return stop_fastdl_without_decrypt();
  2716. }
  2717. sub stop_fastdl_without_decrypt
  2718. {
  2719. my $pid;
  2720. open(PIDFILE, '<', FD_PID_FILE)
  2721. || logger "Error reading pid file $!",1;
  2722. while (<PIDFILE>)
  2723. {
  2724. $pid = $_;
  2725. chomp $pid;
  2726. }
  2727. close(PIDFILE);
  2728. my $cnt = kill 9, $pid;
  2729. if ($cnt == 1)
  2730. {
  2731. logger "Fast Download Daemon Stopped.",1;
  2732. return 1;
  2733. }
  2734. else
  2735. {
  2736. logger "Fast Download Daemon with pid $pid can not be stopped.",1;
  2737. return -1;
  2738. }
  2739. }
  2740. sub restart_fastdl
  2741. {
  2742. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2743. return restart_fastdl_without_decrypt();
  2744. }
  2745. sub restart_fastdl_without_decrypt
  2746. {
  2747. if((fastdl_status_without_decrypt() == -1) || (stop_fastdl_without_decrypt() == 1))
  2748. {
  2749. if(start_fastdl() == 1)
  2750. {
  2751. # Success
  2752. return 1;
  2753. }
  2754. # Cant start
  2755. return -2;
  2756. }
  2757. # Cant stop
  2758. return -3;
  2759. }
  2760. sub fastdl_status
  2761. {
  2762. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2763. return fastdl_status_without_decrypt();
  2764. }
  2765. sub fastdl_status_without_decrypt
  2766. {
  2767. my $pid;
  2768. if(!open(PIDFILE, '<', FD_PID_FILE))
  2769. {
  2770. logger "Error reading pid file $!";
  2771. return -1;
  2772. }
  2773. while (<PIDFILE>)
  2774. {
  2775. $pid = $_;
  2776. chomp $pid;
  2777. }
  2778. close(PIDFILE);
  2779. my $cnt = kill 0, $pid;
  2780. if ($cnt == 1)
  2781. {
  2782. return 1;
  2783. }
  2784. else
  2785. {
  2786. return -1;
  2787. }
  2788. }
  2789. sub fastdl_get_aliases
  2790. {
  2791. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2792. my %aliases;
  2793. my $i;
  2794. my @file_lines;
  2795. if(-d FD_ALIASES_DIR)
  2796. {
  2797. if( !opendir(ALIASES, FD_ALIASES_DIR) )
  2798. {
  2799. logger "Error openning aliases directory " . FD_ALIASES_DIR . ", $!";
  2800. }
  2801. else
  2802. {
  2803. while (my $alias = readdir(ALIASES))
  2804. {
  2805. # Skip . and ..
  2806. next if $alias =~ /^\./;
  2807. if( !open(ALIAS, '<', Path::Class::Dir->new(FD_ALIASES_DIR, $alias)) )
  2808. {
  2809. logger "Error reading alias '$alias', $!";
  2810. }
  2811. else
  2812. {
  2813. $i = 0;
  2814. @file_lines = ();
  2815. while (<ALIAS>)
  2816. {
  2817. chomp $_;
  2818. $file_lines[$i] = $_;
  2819. $i++;
  2820. }
  2821. close(ALIAS);
  2822. $aliases{$alias}{home} = $file_lines[0];
  2823. $aliases{$alias}{match_file_extension} = $file_lines[1];
  2824. $aliases{$alias}{match_client_ip} = $file_lines[2];
  2825. }
  2826. }
  2827. closedir(ALIASES);
  2828. }
  2829. }
  2830. else
  2831. {
  2832. logger "Aliases directory '" . FD_ALIASES_DIR . "' does not exist or is inaccessible.";
  2833. }
  2834. return {%aliases};
  2835. }
  2836. sub fastdl_del_alias
  2837. {
  2838. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2839. foreach my $alias (decrypt_params(@_))
  2840. {
  2841. unlink Path::Class::File->new(FD_ALIASES_DIR, $alias);
  2842. }
  2843. return restart_fastdl_without_decrypt();
  2844. }
  2845. sub fastdl_add_alias
  2846. {
  2847. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2848. my ($alias,$home,$match_file_extension,$match_client_ip) = decrypt_params(@_);
  2849. if(!-e FD_ALIASES_DIR)
  2850. {
  2851. if(!mkdir FD_ALIASES_DIR)
  2852. {
  2853. logger "ERROR - Failed to create " . FD_ALIASES_DIR . " directory.";
  2854. return -1;
  2855. }
  2856. }
  2857. my $alias_path = Path::Class::File->new(FD_ALIASES_DIR, $alias);
  2858. if (!open(ALIAS, '>', $alias_path))
  2859. {
  2860. logger "ERROR - Failed to open ".$alias_path." for writing.";
  2861. return -1;
  2862. }
  2863. else
  2864. {
  2865. print ALIAS "$home\n";
  2866. print ALIAS "$match_file_extension\n";
  2867. print ALIAS "$match_client_ip";
  2868. close(ALIAS);
  2869. return restart_fastdl_without_decrypt();
  2870. }
  2871. }
  2872. sub fastdl_get_info
  2873. {
  2874. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2875. if(-e Path::Class::File->new(FD_DIR, 'Settings.pm'))
  2876. {
  2877. delete $INC{"FastDownload/Settings.pm"};
  2878. require "FastDownload/Settings.pm"; # Settings for Fast Download Daemon.
  2879. if(not defined $FastDownload::Settings{autostart_on_agent_startup})
  2880. {
  2881. $FastDownload::Settings{autostart_on_agent_startup} = 0;
  2882. }
  2883. return {'port' => $FastDownload::Settings{port},
  2884. 'ip' => $FastDownload::Settings{ip},
  2885. 'listing' => $FastDownload::Settings{listing},
  2886. 'autostart_on_agent_startup'=> $FastDownload::Settings{autostart_on_agent_startup}};
  2887. }
  2888. return -1
  2889. }
  2890. sub fastdl_create_config
  2891. {
  2892. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2893. if(!-e FD_DIR)
  2894. {
  2895. if(!mkdir FD_DIR)
  2896. {
  2897. logger "ERROR - Failed to create " . FD_DIR . " directory.";
  2898. return -1;
  2899. }
  2900. }
  2901. my ($fd_address, $fd_port, $listing, $autostart_on_agent_startup) = decrypt_params(@_);
  2902. my $settings_string = "%FastDownload::Settings = (\n".
  2903. "\tport => $fd_port,\n".
  2904. "\tip => '$fd_address',\n".
  2905. "\tlisting => $listing,\n".
  2906. "\tautostart_on_agent_startup => $autostart_on_agent_startup,\n".
  2907. ");";
  2908. my $settings = Path::Class::File->new(FD_DIR, 'Settings.pm');
  2909. if (!open(SETTINGS, '>', $settings))
  2910. {
  2911. logger "ERROR - Failed to open $settings for writing.";
  2912. return -1;
  2913. }
  2914. else
  2915. {
  2916. print SETTINGS $settings_string;
  2917. close(SETTINGS);
  2918. }
  2919. logger "$settings file written successfully.";
  2920. return 1;
  2921. }
  2922. sub agent_restart
  2923. {
  2924. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  2925. my $dec_check = decrypt_param(@_);
  2926. if ($dec_check eq 'restart')
  2927. {
  2928. chdir AGENT_RUN_DIR;
  2929. if(-e "ogp_agent_run.pid")
  2930. {
  2931. my $init_pid = `cat ogp_agent_run.pid`;
  2932. chomp($init_pid);
  2933. if(kill 0, $init_pid)
  2934. {
  2935. my $or_exist = "";
  2936. my $rm_pid_file = "";
  2937. if(-e "ogp_agent.pid")
  2938. {
  2939. $rm_pid_file = " ogp_agent.pid";
  2940. my $agent_pid = `cat ogp_agent.pid`;
  2941. chomp($agent_pid);
  2942. if( kill 0, $agent_pid )
  2943. {
  2944. $or_exist = " -o -e /proc/$agent_pid";
  2945. }
  2946. }
  2947. open (AGENT_RESTART_SCRIPT, '>', 'tmp_restart.sh');
  2948. my $restart = "echo -n \"Stopping OGP Agent...\"\n".
  2949. "kill $init_pid\n".
  2950. "while [ -e /proc/$init_pid $or_exist ];do echo -n .;sleep 1;done\n".
  2951. "rm -f ogp_agent_run.pid $rm_pid_file\necho \" [OK]\"\n".
  2952. "echo -n \"Starting OGP Agent...\"\n".
  2953. "screen -d -m -t \"ogp_agent\" -c \"" . SCREENRC_FILE . "\" -S ogp_agent bash ogp_agent_run -pidfile ogp_agent_run.pid\n".
  2954. "while [ ! -e ogp_agent_run.pid -o ! -e ogp_agent.pid ];do echo -n .;sleep 1;done\n".
  2955. "echo \" [OK]\"\n".
  2956. "rm -f tmp_restart.sh\n".
  2957. "exit 0\n";
  2958. print AGENT_RESTART_SCRIPT $restart;
  2959. close (AGENT_RESTART_SCRIPT);
  2960. if( -e 'tmp_restart.sh' )
  2961. {
  2962. system('screen -d -m -t "agent_restart" -c "' . SCREENRC_FILE . '" -S agent_restart bash tmp_restart.sh');
  2963. }
  2964. }
  2965. }
  2966. }
  2967. return -1;
  2968. }
  2969. # Subroutines to be called
  2970. sub scheduler_dispatcher {
  2971. my ($task, $args) = @_;
  2972. my $response = `$args`;
  2973. chomp($response);
  2974. my $log = "Executed command: $args";
  2975. if($response ne "")
  2976. {
  2977. $log .= ", response:\n$response";
  2978. }
  2979. scheduler_log_events($log);
  2980. }
  2981. sub scheduler_server_action
  2982. {
  2983. my ($task, $args) = @_;
  2984. my ($action, @server_args) = split('\|\%\|', $args);
  2985. if($action eq "%ACTION=start")
  2986. {
  2987. my ($home_id, $ip, $port) = ($server_args[0], $server_args[6], $server_args[5]);
  2988. my $ret = universal_start_without_decrypt(@server_args);
  2989. if($ret == 1)
  2990. {
  2991. scheduler_log_events("Started server home ID $home_id on address $ip:$port");
  2992. }
  2993. else
  2994. {
  2995. scheduler_log_events("Failed starting server home ID $home_id on address $ip:$port (Check agent log)");
  2996. }
  2997. }
  2998. elsif($action eq "%ACTION=stop")
  2999. {
  3000. my ($home_id, $ip, $port) = ($server_args[0], $server_args[1], $server_args[2]);
  3001. my $ret = stop_server_without_decrypt(@server_args);
  3002. if($ret == 0)
  3003. {
  3004. scheduler_log_events("Stopped server home ID $home_id on address $ip:$port");
  3005. }
  3006. elsif($ret == 1)
  3007. {
  3008. scheduler_log_events("Failed stopping server home ID $home_id on address $ip:$port (Invalid IP:Port given)");
  3009. }
  3010. }
  3011. elsif($action eq "%ACTION=restart")
  3012. {
  3013. my ($home_id, $ip, $port) = ($server_args[0], $server_args[1], $server_args[2]);
  3014. my $ret = restart_server_without_decrypt(@server_args);
  3015. if($ret == 1)
  3016. {
  3017. scheduler_log_events("Restarted server home ID $home_id on address $ip:$port");
  3018. }
  3019. elsif($ret == -1)
  3020. {
  3021. scheduler_log_events("Failed restarting server home ID $home_id on address $ip:$port (Server could not be started, check agent log)");
  3022. }
  3023. elsif($ret == -2)
  3024. {
  3025. scheduler_log_events("Failed restarting server home ID $home_id on address $ip:$port (Server could not be stopped, check agent log)");
  3026. }
  3027. }
  3028. return 1;
  3029. }
  3030. sub scheduler_log_events
  3031. {
  3032. my $logcmd = $_[0];
  3033. $logcmd = localtime() . " $logcmd\n";
  3034. logger "Can't open " . SCHED_LOG_FILE . " - $!" unless open(LOGFILE, '>>', SCHED_LOG_FILE);
  3035. logger "Failed to lock " . SCHED_LOG_FILE . "." unless flock(LOGFILE, LOCK_EX);
  3036. logger "Failed to seek to end of " . SCHED_LOG_FILE . "." unless seek(LOGFILE, 0, 2);
  3037. logger "Failed to write to " . SCHED_LOG_FILE . "." unless print LOGFILE "$logcmd";
  3038. logger "Failed to unlock " . SCHED_LOG_FILE . "." unless flock(LOGFILE, LOCK_UN);
  3039. logger "Failed to close " . SCHED_LOG_FILE . "." unless close(LOGFILE);
  3040. }
  3041. sub scheduler_add_task
  3042. {
  3043. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3044. my $new_task = decrypt_param(@_);
  3045. if (open(TASKS, '>>', SCHED_TASKS))
  3046. {
  3047. print TASKS "$new_task\n";
  3048. logger "Created new task: $new_task";
  3049. close(TASKS);
  3050. scheduler_stop();
  3051. # Create new object with default dispatcher for scheduled tasks
  3052. $cron = new Schedule::Cron( \&scheduler_dispatcher, {
  3053. nofork => 1,
  3054. loglevel => 0,
  3055. log => sub { print $_[1], "\n"; }
  3056. } );
  3057. $cron->add_entry( "* * * * * *", \&scheduler_read_tasks );
  3058. # Run scheduler
  3059. $cron->run( {detach=>1, pid_file=>SCHED_PID} );
  3060. return 1;
  3061. }
  3062. logger "Cannot create task: $new_task ( $! )";
  3063. return -1;
  3064. }
  3065. sub scheduler_del_task
  3066. {
  3067. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3068. my $name = decrypt_param(@_);
  3069. if( scheduler_read_tasks() == -1 )
  3070. {
  3071. return -1;
  3072. }
  3073. my @entries = $cron->list_entries();
  3074. if(open(TASKS, '>', SCHED_TASKS))
  3075. {
  3076. foreach my $task ( @entries ) {
  3077. next if $task->{args}[0] eq $name;
  3078. next unless $task->{args}[0] =~ /task_[0-9]*/;
  3079. if(defined $task->{args}[1])
  3080. {
  3081. print TASKS join(" ", $task->{time}, $task->{args}[1]) . "\n";
  3082. }
  3083. else
  3084. {
  3085. print TASKS $task->{time} . "\n";
  3086. }
  3087. }
  3088. close( TASKS );
  3089. scheduler_stop();
  3090. # Create new object with default dispatcher for scheduled tasks
  3091. $cron = new Schedule::Cron( \&scheduler_dispatcher, {
  3092. nofork => 1,
  3093. loglevel => 0,
  3094. log => sub { print $_[1], "\n"; }
  3095. } );
  3096. $cron->add_entry( "* * * * * *", \&scheduler_read_tasks );
  3097. # Run scheduler
  3098. $cron->run( {detach=>1, pid_file=>SCHED_PID} );
  3099. return 1;
  3100. }
  3101. logger "Cannot open file " . SCHED_TASKS . " for deleting task id: $name ( $! )",1;
  3102. return -1;
  3103. }
  3104. sub scheduler_edit_task
  3105. {
  3106. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3107. my ($name, $new_task) = decrypt_params(@_);
  3108. if( scheduler_read_tasks() == -1 )
  3109. {
  3110. return -1;
  3111. }
  3112. my @entries = $cron->list_entries();
  3113. if(open(TASKS, '>', SCHED_TASKS))
  3114. {
  3115. foreach my $task ( @entries ) {
  3116. next unless $task->{args}[0] =~ /task_[0-9]*/;
  3117. if($name eq $task->{args}[0])
  3118. {
  3119. print TASKS "$new_task\n";
  3120. }
  3121. else
  3122. {
  3123. if(defined $task->{args}[1])
  3124. {
  3125. print TASKS join(" ", $task->{time}, $task->{args}[1]) . "\n";
  3126. }
  3127. else
  3128. {
  3129. print TASKS $task->{time} . "\n";
  3130. }
  3131. }
  3132. }
  3133. close( TASKS );
  3134. scheduler_stop();
  3135. # Create new object with default dispatcher for scheduled tasks
  3136. $cron = new Schedule::Cron( \&scheduler_dispatcher, {
  3137. nofork => 1,
  3138. loglevel => 0,
  3139. log => sub { print $_[1], "\n"; }
  3140. } );
  3141. $cron->add_entry( "* * * * * *", \&scheduler_read_tasks );
  3142. # Run scheduler
  3143. $cron->run( {detach=>1, pid_file=>SCHED_PID} );
  3144. return 1;
  3145. }
  3146. logger "Cannot open file " . SCHED_TASKS . " for editing task id: $name ( $! )",1;
  3147. return -1;
  3148. }
  3149. sub scheduler_read_tasks
  3150. {
  3151. if( open(TASKS, '<', SCHED_TASKS) )
  3152. {
  3153. $cron->clean_timetable();
  3154. }
  3155. else
  3156. {
  3157. logger "Error reading tasks file $!";
  3158. scheduler_stop();
  3159. return -1;
  3160. }
  3161. my $i = 0;
  3162. while (<TASKS>)
  3163. {
  3164. next if $_ =~ /^(#.*|[\s|\t]*?\n)/;
  3165. my ($minute, $hour, $dayOfTheMonth, $month, $dayOfTheWeek, @args) = split(' ', $_);
  3166. my $time = "$minute $hour $dayOfTheMonth $month $dayOfTheWeek";
  3167. if("@args" =~ /^\%ACTION.*/)
  3168. {
  3169. $cron->add_entry($time, \&scheduler_server_action, 'task_' . $i++, "@args");
  3170. }
  3171. else
  3172. {
  3173. $cron->add_entry($time, 'task_' . $i++, "@args");
  3174. }
  3175. }
  3176. close(TASKS);
  3177. return 1;
  3178. }
  3179. sub scheduler_stop
  3180. {
  3181. my $pid;
  3182. if(open(PIDFILE, '<', SCHED_PID))
  3183. {
  3184. $pid = <PIDFILE>;
  3185. chomp $pid;
  3186. close(PIDFILE);
  3187. if($pid ne "")
  3188. {
  3189. if( kill 0, $pid )
  3190. {
  3191. my $cnt = kill 9, $pid;
  3192. if ($cnt == 1)
  3193. {
  3194. unlink SCHED_PID;
  3195. return 1;
  3196. }
  3197. }
  3198. }
  3199. }
  3200. return -1;
  3201. }
  3202. sub scheduler_list_tasks
  3203. {
  3204. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3205. if( scheduler_read_tasks() == -1 )
  3206. {
  3207. return -1;
  3208. }
  3209. my @entries = $cron->list_entries();
  3210. my %entries_array;
  3211. foreach my $task ( @entries ) {
  3212. if( defined $task->{args}[1] )
  3213. {
  3214. $entries_array{$task->{args}[0]} = encode_base64(join(" ", $task->{time}, $task->{args}[1]));
  3215. }
  3216. else
  3217. {
  3218. $entries_array{$task->{args}[0]} = encode_base64($task->{time});
  3219. }
  3220. }
  3221. if( %entries_array )
  3222. {
  3223. return {%entries_array};
  3224. }
  3225. return -1;
  3226. }
  3227. sub get_file_part
  3228. {
  3229. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3230. my ($file, $offset) = decrypt_params(@_);
  3231. if (!open(FILE, '<', $file))
  3232. {
  3233. logger "ERROR - Can't open file $file for reading.";
  3234. return -1;
  3235. }
  3236. binmode(FILE);
  3237. if($offset != 0)
  3238. {
  3239. return -1 unless seek FILE, $offset, 0;
  3240. }
  3241. my $data = "";
  3242. my ($n, $buf);
  3243. my $limit = $offset + 60 * 57 * 1000; #Max 3420Kb (1000 iterations) (top statistics ~ VIRT 116m, RES 47m)
  3244. while (($n = read FILE, $buf, 60 * 57) != 0 && $offset <= $limit ) {
  3245. $data .= $buf;
  3246. $offset += $n;
  3247. }
  3248. close(FILE);
  3249. if( $data ne "" )
  3250. {
  3251. my $b64zlib = encode_base64(compress($data,9));
  3252. return "$offset;$b64zlib";
  3253. }
  3254. else
  3255. {
  3256. return -1;
  3257. }
  3258. }
  3259. sub stop_update
  3260. {
  3261. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3262. my $home_id = decrypt_param(@_);
  3263. my $screen_id = create_screen_id(SCREEN_TYPE_UPDATE, $home_id);
  3264. system('screen -S '.$screen_id.' -p 0 -X stuff $\'\003\'');
  3265. if ($? == 0)
  3266. {
  3267. return 0;
  3268. }
  3269. return 1
  3270. }
  3271. sub shell_action
  3272. {
  3273. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3274. my ($action, $arguments) = decrypt_params(@_);
  3275. if($action eq 'remove_file')
  3276. {
  3277. chomp($arguments);
  3278. unlink($arguments);
  3279. return "1;";
  3280. }
  3281. elsif($action eq 'remove_recursive')
  3282. {
  3283. my @items = split(';', $arguments);
  3284. foreach my $item ( @items ) {
  3285. chomp($item);
  3286. if(-d $item)
  3287. {
  3288. pathrmdir($item);
  3289. }
  3290. else
  3291. {
  3292. unlink($item);
  3293. }
  3294. }
  3295. return "1;";
  3296. }
  3297. elsif($action eq 'create_dir')
  3298. {
  3299. chomp($arguments);
  3300. mkpath($arguments);
  3301. return "1;";
  3302. }
  3303. elsif($action eq 'move')
  3304. {
  3305. my($src, $dest) = split(';', $arguments);
  3306. chomp($src);
  3307. chomp($dest);
  3308. if(-d $src)
  3309. {
  3310. $dest = Path::Class::Dir->new($dest, basename($src));
  3311. dirmove($src, $dest);
  3312. }
  3313. else
  3314. {
  3315. fmove($src, $dest);
  3316. }
  3317. return "1;";
  3318. }
  3319. elsif($action eq 'copy')
  3320. {
  3321. my($src, $dest) = split(';', $arguments);
  3322. chomp($src);
  3323. chomp($dest);
  3324. if(-d $src)
  3325. {
  3326. $dest = Path::Class::Dir->new($dest, basename($src));
  3327. dircopy($src, $dest);
  3328. }
  3329. else
  3330. {
  3331. fcopy($src, $dest);
  3332. }
  3333. return "1;";
  3334. }
  3335. elsif($action eq 'touch')
  3336. {
  3337. chomp($arguments);
  3338. open(FH, '>', $arguments);
  3339. print FH "";
  3340. close(FH);
  3341. return "1;";
  3342. }
  3343. elsif($action eq 'size')
  3344. {
  3345. chomp($arguments);
  3346. my $size = 0;
  3347. if(-d $arguments)
  3348. {
  3349. find(sub { $size += -s }, $arguments ? $arguments : '.');
  3350. }
  3351. else
  3352. {
  3353. $size += (stat($arguments))[7];
  3354. }
  3355. return "1;" . encode_list($size);
  3356. }
  3357. elsif($action eq 'get_cpu_usage')
  3358. {
  3359. my %prev_idle;
  3360. my %prev_total;
  3361. open(STAT, '/proc/stat');
  3362. while (<STAT>) {
  3363. next unless /^cpu([0-9]+)/;
  3364. my @stat = split /\s+/, $_;
  3365. $prev_idle{$1} = $stat[4];
  3366. $prev_total{$1} = $stat[1] + $stat[2] + $stat[3] + $stat[4];
  3367. }
  3368. close STAT;
  3369. sleep 1;
  3370. my %idle;
  3371. my %total;
  3372. open(STAT, '/proc/stat');
  3373. while (<STAT>) {
  3374. next unless /^cpu([0-9]+)/;
  3375. my @stat = split /\s+/, $_;
  3376. $idle{$1} = $stat[4];
  3377. $total{$1} = $stat[1] + $stat[2] + $stat[3] + $stat[4];
  3378. }
  3379. close STAT;
  3380. my %cpu_percent_usage;
  3381. foreach my $key ( keys %idle )
  3382. {
  3383. my $diff_idle = $idle{$key} - $prev_idle{$key};
  3384. my $diff_total = $total{$key} - $prev_total{$key};
  3385. my $percent = (100 * ($diff_total - $diff_idle)) / $diff_total;
  3386. $percent = sprintf "%.2f", $percent unless $percent == 0;
  3387. $cpu_percent_usage{$key} = encode_base64($percent);
  3388. }
  3389. return {%cpu_percent_usage};
  3390. }
  3391. elsif($action eq 'get_ram_usage')
  3392. {
  3393. my($total, $buffers, $cached, $free) = qw(0 0 0 0);
  3394. open(STAT, '/proc/meminfo');
  3395. while (<STAT>) {
  3396. $total += $1 if /MemTotal\:\s+(\d+) kB/;
  3397. $buffers += $1 if /Buffers\:\s+(\d+) kB/;
  3398. $cached += $1 if /Cached\:\s+(\d+) kB/;
  3399. $free += $1 if /MemFree\:\s+(\d+) kB/;
  3400. }
  3401. close STAT;
  3402. my $used = $total - $free - $cached - $buffers;
  3403. my $percent = 100 * $used / $total;
  3404. my %mem_usage;
  3405. $mem_usage{'used'} = encode_base64($used * 1024);
  3406. $mem_usage{'total'} = encode_base64($total * 1024);
  3407. $mem_usage{'percent'} = encode_base64($percent);
  3408. return {%mem_usage};
  3409. }
  3410. elsif($action eq 'get_disk_usage')
  3411. {
  3412. my($total, $used, $free) = split(' ', `df -lP 2>/dev/null|grep "^/dev/.*"|awk '{total+=\$2}{used+=\$3}{free+=\$4} END {print total, used, free}'`);
  3413. my $percent = 100 * $used / $total;
  3414. my %disk_usage;
  3415. $disk_usage{'free'} = encode_base64($free * 1024);
  3416. $disk_usage{'used'} = encode_base64($used * 1024);
  3417. $disk_usage{'total'} = encode_base64($total * 1024);
  3418. $disk_usage{'percent'} = encode_base64($percent);
  3419. return {%disk_usage};
  3420. }
  3421. elsif($action eq 'get_uptime')
  3422. {
  3423. open(STAT, '/proc/uptime');
  3424. my $uptime = 0;
  3425. while (<STAT>) {
  3426. $uptime += $1 if /^([0-9]+)/;
  3427. }
  3428. close STAT;
  3429. my %upsince;
  3430. $upsince{'0'} = encode_base64($uptime);
  3431. $upsince{'1'} = encode_base64(time - $uptime);
  3432. return {%upsince};
  3433. }
  3434. elsif($action eq 'get_tasklist')
  3435. {
  3436. my %taskList;
  3437. $taskList{'task'} = encode_base64(`top -b -c -i -w512 -n2 | awk '/^top/{i++}i==2' | grep "COMMAND" -A 30`);
  3438. return {%taskList};
  3439. }
  3440. elsif($action eq 'get_timestamp')
  3441. {
  3442. return "1;" . encode_list(time);
  3443. }
  3444. return 0;
  3445. }
  3446. sub remote_query
  3447. {
  3448. return "Bad Encryption Key" unless(decrypt_param(pop(@_)) eq "Encryption checking OK");
  3449. my ($protocol, $game_type, $ip, $c_port, $q_port, $s_port) = decrypt_params(@_);
  3450. my $command = "which php-cgi 2>&1;echo \$?";
  3451. my @cmdret = qx($command);
  3452. chomp(@cmdret);
  3453. my $ret = pop(@cmdret);
  3454. chomp($ret);
  3455. if ("X$ret" ne "X0")
  3456. {
  3457. return -1;
  3458. }
  3459. my $PHP_CGI = "@cmdret";
  3460. my $php_query_dir = Path::Class::Dir->new(AGENT_RUN_DIR, 'php-query');
  3461. if($protocol eq 'lgsl')
  3462. {
  3463. chdir($php_query_dir->subdir('lgsl'));
  3464. my $cmd = $PHP_CGI .
  3465. " -f lgsl_feed.php" .
  3466. " lgsl_type=" . $game_type .
  3467. " ip=" . $ip .
  3468. " c_port=" . $c_port .
  3469. " q_port=" . $q_port .
  3470. " s_port=" . $s_port .
  3471. " request=sp";
  3472. my $response = `$cmd`;
  3473. chomp($response);
  3474. chdir(AGENT_RUN_DIR);
  3475. if($response eq "FAILURE")
  3476. {
  3477. return -1;
  3478. }
  3479. return encode_base64($response, "");
  3480. }
  3481. elsif($protocol eq 'gameq')
  3482. {
  3483. chdir($php_query_dir->subdir('gameq'));
  3484. my $cmd = $PHP_CGI .
  3485. " -f gameq_feed.php" .
  3486. " game_type=" . $game_type .
  3487. " ip=" . $ip .
  3488. " c_port=" . $c_port .
  3489. " q_port=" . $q_port .
  3490. " s_port=" . $s_port;
  3491. my $response = `$cmd`;
  3492. chomp($response);
  3493. chdir(AGENT_RUN_DIR);
  3494. if($response eq "FAILURE")
  3495. {
  3496. return -1;
  3497. }
  3498. return encode_base64($response, "");
  3499. }
  3500. return -1;
  3501. }