KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sf > drftpd > master > command > plugins > UserManagment


1 /*
2  * This file is part of DrFTPD, Distributed FTP Daemon.
3  *
4  * DrFTPD is free software; you can redistribute it and/or modify it under the
5  * terms of the GNU General Public License as published by the Free Software
6  * Foundation; either version 2 of the License, or (at your option) any later
7  * version.
8  *
9  * DrFTPD is distributed in the hope that it will be useful, but WITHOUT ANY
10  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
11  * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along with
14  * DrFTPD; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
15  * Suite 330, Boston, MA 02111-1307 USA
16  */

17 package net.sf.drftpd.master.command.plugins;
18 import java.rmi.RemoteException JavaDoc;
19 import java.text.ParseException JavaDoc;
20 import java.text.SimpleDateFormat JavaDoc;
21 import java.util.ArrayList JavaDoc;
22 import java.util.Collection JavaDoc;
23 import java.util.Date JavaDoc;
24 import java.util.Iterator JavaDoc;
25 import java.util.NoSuchElementException JavaDoc;
26 import java.util.StringTokenizer JavaDoc;
27 import net.sf.drftpd.Bytes;
28 import net.sf.drftpd.DuplicateElementException;
29 import net.sf.drftpd.HostMask;
30 import net.sf.drftpd.master.BaseFtpConnection;
31 import net.sf.drftpd.master.FtpReply;
32 import net.sf.drftpd.master.FtpRequest;
33 import net.sf.drftpd.master.command.CommandManager;
34 import net.sf.drftpd.master.command.CommandManagerFactory;
35 import net.sf.drftpd.master.config.FtpConfig;
36 import net.sf.drftpd.master.config.Permission;
37 import net.sf.drftpd.master.usermanager.NoSuchUserException;
38 import net.sf.drftpd.master.usermanager.User;
39 import net.sf.drftpd.master.usermanager.UserExistsException;
40 import net.sf.drftpd.master.usermanager.UserFileException;
41 import net.sf.drftpd.slave.Transfer;
42 import net.sf.drftpd.util.ReplacerUtils;
43 import net.sf.drftpd.util.Time;
44 import org.apache.log4j.Level;
45 import org.apache.log4j.Logger;
46 import org.drftpd.commands.CommandHandler;
47 import org.drftpd.commands.CommandHandlerFactory;
48 import org.drftpd.commands.UnhandledCommandException;
49 import org.tanesha.replacer.FormatterException;
50 import org.tanesha.replacer.ReplacerEnvironment;
51 import org.tanesha.replacer.ReplacerFormat;
52 import org.tanesha.replacer.SimplePrintf;
53 /**
54  * @author mog
55  * @author zubov
56  * @version $Id: UserManagment.java,v 1.39.2.4 2004/07/07 17:13:55 zubov Exp $
57  */

58 public class UserManagment implements CommandHandler, CommandHandlerFactory {
59     private static final Logger logger = Logger.getLogger(UserManagment.class);
60     private FtpReply doSITE_ADDIP(BaseFtpConnection conn) {
61         FtpRequest request = conn.getRequest();
62         if (!conn.getUserNull().isAdmin() && !conn.getUserNull().isGroupAdmin()) {
63             return FtpReply.RESPONSE_530_ACCESS_DENIED;
64         }
65         if (!request.hasArgument()) {
66             return new FtpReply(501, conn.jprintf(
67                     UserManagment.class.getName(), "addip.usage"));
68         }
69         String JavaDoc args[] = request.getArgument().split(" ");
70         if (args.length < 2) {
71             return new FtpReply(501, conn.jprintf(
72                     UserManagment.class.getName(), "addip.specify"));
73         }
74         FtpReply response = new FtpReply(200);
75         User myUser;
76         try {
77             myUser = conn.getConnectionManager().getUserManager()
78                     .getUserByName(args[0]);
79             if (conn.getUserNull().isGroupAdmin()
80                     && !conn.getUserNull().getGroupName().equals(
81                             myUser.getGroupName())) {
82                 return FtpReply.RESPONSE_530_ACCESS_DENIED;
83             }
84             ReplacerEnvironment env = new ReplacerEnvironment();
85             env.add("targetuser", myUser.getUsername());
86             for (int i = 1; i < args.length; i++) {
87                 String JavaDoc string = args[i];
88                 env.add("mask", string);
89                 try {
90                     myUser.addIPMask(string);
91                     response.addComment(conn.jprintf(UserManagment.class
92                             .getName(), "addip.success", env));
93                     logger.info("'" + conn.getUserNull().getUsername()
94                             + "' added ip '" + string + "' to '"
95                             + myUser.getUsername() + "'");
96                 } catch (DuplicateElementException e) {
97                     response.addComment(conn.jprintf(UserManagment.class
98                             .getName(), "addip.dupe", env));
99                 }
100             }
101             myUser.commit(); // throws UserFileException
102
//userManager.save(user2);
103
} catch (NoSuchUserException ex) {
104             return new FtpReply(200, "No such user: " + args[0]);
105         } catch (UserFileException ex) {
106             response.addComment(ex.getMessage());
107             return response;
108         }
109         return response;
110     }
111     /**
112      * USAGE: site adduser <user><password>[ <ident@ip#1>... <ident@ip#5>] Adds
113      * a user. You can have wild cards for users that have dynamic ips Examples:
114      * *@192.168.1.* , frank@192.168.*.* , bob@192.*.*.* (*@192.168.1.1[5-9]
115      * will allow only 192.168.1.15-19 to connect but no one else)
116      *
117      * If a user is added by a groupadmin, that user will have the GLOCK flag
118      * enabled and will inherit the groupadmin's home directory.
119      *
120      * All default values for the user are read from file default.user in
121      * /glftpd/ftp-data/users. Comments inside describe what is what. Gadmins
122      * can be assigned their own default. <group>userfiles as templates to be
123      * used when they add a user, if one is not found, default.user will be
124      * used. default.groupname files will also be used for "site gadduser".
125      *
126      * ex. site ADDUSER Archimede mypassword
127      *
128      * This would add the user 'Archimede' with the password 'mypassword'.
129      *
130      * ex. site ADDUSER Archimede mypassword *@127.0.0.1
131      *
132      * This would do the same as above + add the ip '*@127.0.0.1' at the same
133      * time.
134      *
135      * HOMEDIRS: After login, the user will automatically be transferred into
136      * his/her homedir. As of 1.16.x this dir is now "kinda" chroot'ed and they
137      * are now unable to "cd ..".
138      *
139      *
140      *
141      * USAGE: site gadduser <group><user><password>[ <ident@ip#1 ..
142      * ident@ip#5>] Adds a user and changes his/her group to <group>. If
143      * default.group exists, it will be used as a base instead of default.user.
144      *
145      * Only public groups can be used as <group>.
146      */

147     private FtpReply doSITE_ADDUSER(BaseFtpConnection conn) {
148         FtpRequest request = conn.getRequest();
149         boolean isGAdduser = request.getCommand().equals("SITE GADDUSER");
150         if (!request.hasArgument()) {
151             String JavaDoc key;
152             if (isGAdduser) {
153                 key = "gadduser.usage";
154             } else { //request.getCommand().equals("SITE ADDUSER");
155
key = "adduser.usage";
156             }
157             return new FtpReply(501, conn.jprintf(
158                     UserManagment.class.getName(), key));
159         }
160         String JavaDoc newGroup = null;
161         if (conn.getUserNull().isGroupAdmin()) {
162             if (isGAdduser) {
163                 return FtpReply.RESPONSE_530_ACCESS_DENIED;
164             }
165             int users;
166             try {
167                 users = conn.getConnectionManager().getUserManager()
168                         .getAllUsersByGroup(conn.getUserNull().getGroupName())
169                         .size();
170                 if (users >= conn.getUserNull().getGroupSlots()) {
171                     return new FtpReply(200, conn.jprintf(UserManagment.class
172                             .getName(), "adduser.noslots"));
173                 }
174             } catch (UserFileException e1) {
175                 logger.warn("", e1);
176                 return new FtpReply(200, e1.getMessage());
177             }
178             newGroup = conn.getUserNull().getGroupName();
179         } else if (!conn.getUserNull().isAdmin()) {
180             return FtpReply.RESPONSE_530_ACCESS_DENIED;
181         }
182         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(request.getArgument());
183         User newUser;
184         FtpReply response = (FtpReply) FtpReply.RESPONSE_200_COMMAND_OK.clone();
185         ReplacerEnvironment env = new ReplacerEnvironment();
186         try {
187             if (isGAdduser) {
188                 newGroup = st.nextToken();
189             }
190             String JavaDoc newUsername = st.nextToken();
191             env.add("targetuser", newUsername);
192             String JavaDoc pass = st.nextToken();
193             //action, no more NoSuchElementException below here
194
newUser = conn.getConnectionManager().getUserManager().create(
195                     newUsername);
196             newUser.setPassword(pass);
197             response.addComment(conn.jprintf(UserManagment.class.getName(),
198                     "adduser.success", env));
199             newUser.setComment("Added by " + conn.getUserNull().getUsername());
200             if (newGroup != null) {
201                 newUser.setGroup(newGroup);
202                 logger.info("'" + conn.getUserNull().getUsername()
203                         + "' added '" + newUser.getUsername() + "' with group "
204                         + newUser.getGroupName() + "'");
205                 env.add("primgroup", newUser.getGroupName());
206                 response.addComment(conn.jprintf(UserManagment.class.getName(),
207                         "adduser.primgroup", env));
208             } else {
209                 logger.info("'" + conn.getUserNull().getUsername()
210                         + "' added '" + newUser.getUsername() + "'");
211             }
212         } catch (NoSuchElementException JavaDoc ex) {
213             return new FtpReply(501, conn.jprintf(
214                     UserManagment.class.getName(), "adduser.missingpass"));
215         } catch (UserFileException ex) {
216             return new FtpReply(200, ex.getMessage());
217         }
218         try {
219             while (st.hasMoreTokens()) {
220                 String JavaDoc string = st.nextToken();
221                 env.add("mask", string);
222                 new HostMask(string); // validate hostmask
223
try {
224                     newUser.addIPMask(string);
225                     response.addComment(conn.jprintf(UserManagment.class
226                             .getName(), "addip.success", env));
227                     logger.info("'" + conn.getUserNull().getUsername()
228                             + "' added ip '" + string + "' to '"
229                             + newUser.getUsername() + "'");
230                 } catch (DuplicateElementException e1) {
231                     response.addComment(conn.jprintf(UserManagment.class
232                             .getName(), "addip.dupe", env));
233                 }
234             }
235             newUser.commit();
236         } catch (UserFileException ex) {
237             logger.warn("", ex);
238             return new FtpReply(200, ex.getMessage());
239         }
240         return response;
241     }
242     /**
243      * USAGE: site change <user><field><value>- change a field for a user site
244      * change =<group><field><value>- change a field for each member of group
245      * <group>site change {<user1><user2>.. }<field><value>- change a field
246      * for each user in the list site change *<field><value>- change a field
247      * for everyone
248      *
249      * Type "site change user help" in glftpd for syntax.
250      *
251      * Fields available:
252      *
253      * Field Description
254      * ------------------------------------------------------------- ratio
255      * Upload/Download ratio. 0 = Unlimited (Leech) wkly_allotment The number of
256      * kilobytes that this user will be given once a week (you need the reset
257      * binary enabled in your crontab). Syntax: site change user wkly_allotment
258      * "#,###" The first number is the section number (0=default section), the
259      * second is the number of kilobytes to give. (user's credits are replaced,
260      * not added to, with this value) Only one section at a time is supported,
261      * homedir This will change the user's homedir. NOTE: This command is
262      * disabled by default. To enable it, add "min_homedir /site" to your config
263      * file, where "/site" is the minimum directory that users can have, i.e.
264      * you can't change a user's home directory to /ftp-data or anything that
265      * doesn't have "/site" at the beginning. Important: don't use a trailing
266      * slash for homedir! Users CAN NOT cd, list, upload/download, etc, outside
267      * of their home dir. It acts similarly to chroot() (try man chroot).
268      * startup_dir The directory to start in. ex: /incoming will start the user
269      * in /glftpd/site/incoming if rootpath is /glftpd and homedir is /site.
270      * Users CAN cd, list, upload/download, etc, outside of startup_dir.
271      * idle_time Sets the default and maximum idle time for this user (overrides
272      * the -t and -T settings on glftpd command line). If -1, it is disabled; if
273      * 0, it is the same as the idler flag. credits Credits left to download.
274      * flags +1ABC or +H or -3, type "site flags" for a list of flags.
275      * num_logins # # : number of simultaneous logins allowed. The second number
276      * is number of sim. logins from the same IP. timeframe # # : the hour from
277      * which to allow logins and the hour when logins from this user will start
278      * being rejected. This is set in a 24 hour format. If a user is online past
279      * his timeframe, he'll be disconnected the next time he does a 'CWD'.
280      * time_limit Time limits, per LOGIN SESSION. (set in minutes. 0 =
281      * Unlimited) tagline User's tagline. group_slots Number of users a GADMIN
282      * is allowed to add. If you specify a second argument, it will be the
283      * number of leech accounts the gadmin can give (done by "site change user
284      * ratio 0") (2nd arg = leech slots) comment Changes the user's comment (max
285      * 50 characters). Comments are displayed by the comment cookie (see below).
286      * max_dlspeed Downstream bandwidth control (KBytes/sec) (0 = Unlimited)
287      * max_ulspeed Same but for uploads max_sim_down Maximum number of
288      * simultaneous downloads for this user (-1 = unlimited, 0 = zero [user
289      * can't download]) max_sim_up Maximum number of simultaneous uploads for
290      * this user (-1 = unlimited, 0 = zero [user can't upload]) sratio
291      * <SECTIONNAME><#>This is to change the ratio of a section (other than
292      * default).
293      *
294      * Flags available:
295      *
296      * Flagname Flag Description
297      * ------------------------------------------------------------- SITEOP 1
298      * User is siteop. GADMIN 2 User is Groupadmin of his/her first public group
299      * (doesn't work for private groups). GLOCK 3 User cannot change group.
300      * EXEMPT 4 Allows to log in when site is full. Also allows user to do "site
301      * idle 0", which is the same as having the idler flag. Also exempts the
302      * user from the sim_xfers limit in config file. COLOR 5 Enable/Disable the
303      * use of color (toggle with "site color"). DELETED 6 User is deleted.
304      * USEREDIT 7 "Co-Siteop" ANON 8 User is anonymous (per-session like login).
305      *
306      * NOTE* The 1 flag is not GOD mode, you must have the correct flags for the
307      * actions you wish to perform. NOTE* If you have flag 1 then you DO NOT
308      * WANT flag 2
309      *
310      * Restrictions placed on users flagged ANONYMOUS. 1. '!' on login is
311      * ignored. 2. They cannot DELETE, RMDIR, or RENAME. 3. Userfiles do not
312      * update like usual, meaning no stats will be kept for these users. The
313      * userfile only serves as a template for the starting environment of the
314      * logged in user. Use external scripts if you must keep records of their
315      * transfer stats.
316      *
317      * NUKE A User is allowed to use site NUKE. UNNUKE B User is allowed to use
318      * site UNNUKE. UNDUPE C User is allowed to use site UNDUPE. KICK D User is
319      * allowed to use site KICK. KILL E User is allowed to use site KILL/SWHO.
320      * TAKE F User is allowed to use site TAKE. GIVE G User is allowed to use
321      * site GIVE. USERS/USER H This allows you to view users ( site USER/USERS )
322      * IDLER I User is allowed to idle forever. CUSTOM1 J Custom flag 1 CUSTOM2
323      * K Custom flag 2 CUSTOM3 L Custom flag 3 CUSTOM4 M Custom flag 4 CUSTOM5 N
324      * Custom flag 5
325      *
326      * You can use custom flags in the config file to give some users access to
327      * certain things without having to use private groups. These flags will
328      * only show up in "site flags" if they're turned on.
329      *
330      * ex. site change Archimede ratio 5
331      *
332      * This would set the ratio to 1:5 for the user 'Archimede'.
333      *
334      * ex. site change Archimede flags +2-AG
335      *
336      * This would make the user 'Archimede' groupadmin and remove his ability to
337      * use the commands site nuke and site give.
338      *
339      * NOTE: The flag DELETED can not be changed with site change, it will
340      * change when someone does a site deluser/readd.
341      */

342     private FtpReply doSITE_CHANGE(BaseFtpConnection conn) {
343         FtpReply usage = (FtpReply) FtpReply.RESPONSE_501_SYNTAX_ERROR.clone();
344         usage.addComment(conn.jprintf(UserManagment.class.getName(),
345                 "change.usage"));
346         FtpRequest request = conn.getRequest();
347         if (!conn.getUserNull().isAdmin() && !conn.getUserNull().isGroupAdmin()) {
348             return FtpReply.RESPONSE_530_ACCESS_DENIED;
349         }
350         if (!request.hasArgument()) {
351             return usage;
352         }
353         User userToChange;
354         FtpReply response = (FtpReply) FtpReply.RESPONSE_200_COMMAND_OK.clone();
355         ReplacerEnvironment env = new ReplacerEnvironment();
356         StringTokenizer JavaDoc arguments = new StringTokenizer JavaDoc(request.getArgument());
357         if (!arguments.hasMoreTokens()) {
358             return usage;
359         }
360         String JavaDoc username = arguments.nextToken();
361         try {
362             userToChange = conn.getConnectionManager().getUserManager()
363                     .getUserByName(username);
364         } catch (NoSuchUserException e) {
365             return new FtpReply(550, "User " + username + " not found: "
366                     + e.getMessage());
367         } catch (UserFileException e) {
368             logger.log(Level.FATAL, "Error loading user", e);
369             return new FtpReply(550, "Error loading user: " + e.getMessage());
370         }
371         if (!arguments.hasMoreTokens()) {
372             return usage;
373         }
374         String JavaDoc command = arguments.nextToken().toLowerCase();
375         env.add("targetuser", userToChange.getUsername());
376         // String args[] = request.getArgument().split(" ");
377
// String command = args[1].toLowerCase();
378
// 0 = user
379
// 1 = command
380
// 2- = argument
381
String JavaDoc[] commandArguments = new String JavaDoc[arguments.countTokens()];
382         String JavaDoc fullCommandArgument = new String JavaDoc();
383         for (int x = 0; arguments.hasMoreTokens(); x++) {
384             commandArguments[x] = arguments.nextToken();
385             fullCommandArgument = fullCommandArgument + " "
386                     + commandArguments[x];
387         }
388         fullCommandArgument = fullCommandArgument.trim();
389         if ("ratio".equals(command)) {
390             ////// Ratio //////
391
if (commandArguments.length != 1)
392                 return usage;
393             float ratio = Float.parseFloat(commandArguments[0]);
394             if (conn.getUserNull().isGroupAdmin()
395                     && !conn.getUserNull().isAdmin()) {
396                 ////// Group Admin Ratio //////
397
if (!conn.getUserNull().getGroupName().equals(
398                         userToChange.getGroupName())) {
399                     return FtpReply.RESPONSE_530_ACCESS_DENIED;
400                 }
401                 if (ratio == 0F) {
402                     int usedleechslots = 0;
403                     try {
404                         for (Iterator JavaDoc iter = conn.getConnectionManager()
405                                 .getUserManager().getAllUsersByGroup(
406                                         conn.getUserNull().getGroupName())
407                                 .iterator(); iter.hasNext();) {
408                             if (((User) iter.next()).getRatio() == 0F)
409                                 usedleechslots++;
410                         }
411                     } catch (UserFileException e1) {
412                         return new FtpReply(200, "IO error reading userfiles: "
413                                 + e1.getMessage());
414                     }
415                     if (usedleechslots >= conn.getUserNull()
416                             .getGroupLeechSlots()) {
417                         return new FtpReply(200, conn.jprintf(
418                                 UserManagment.class.getName(),
419                                 "changeratio.nomoreslots"));
420                     }
421                 } else if (ratio != 0F) {
422                     return new FtpReply(200, conn.jprintf(UserManagment.class
423                             .getName(), "changeratio.invalidratio"));
424                 }
425                 logger.info("'" + conn.getUserNull().getUsername()
426                         + "' changed ratio for '" + userToChange.getUsername()
427                         + "' from '" + userToChange.getRatio() + "' to '"
428                         + ratio + "'");
429                 userToChange.setRatio(ratio);
430                 env.add("newratio", Float.toString(userToChange.getRatio()));
431                 response.addComment(conn.jprintf(UserManagment.class.getName(),
432                         "changeratio.success", env));
433             } else {
434                 // Ratio changes by an admin //
435
logger.info("'" + conn.getUserNull().getUsername()
436                         + "' changed ratio for '" + userToChange.getUsername()
437                         + "' from '" + userToChange.getRatio() + " to '"
438                         + ratio + "'");
439                 userToChange.setRatio(ratio);
440                 env.add("newratio", Float.toString(userToChange.getRatio()));
441                 response.addComment(conn.jprintf(UserManagment.class.getName(),
442                         "changeratio.success", env));
443             }
444         } else if ("credits".equals(command)) {
445             if (commandArguments.length != 1)
446                 return usage;
447             long credits = Bytes.parseBytes(commandArguments[0]);
448             logger.info("'" + conn.getUserNull().getUsername()
449                     + "' changed credits for '" + userToChange.getUsername()
450                     + "' from '" + userToChange.getCredits() + " to '"
451                     + credits + "'");
452             userToChange.setCredits(credits);
453             env.add("newcredits", Bytes.formatBytes(userToChange.getCredits()));
454             response.addComment(conn.jprintf(UserManagment.class.getName(),
455                     "changecredits.success", env));
456         } else if ("comment".equals(command)) {
457             logger.info("'" + conn.getUserNull().getUsername()
458                     + "' changed comment for '" + userToChange.getUsername()
459                     + "' from '" + userToChange.getComment() + " to '"
460                     + fullCommandArgument + "'");
461             userToChange.setComment(fullCommandArgument);
462             env.add("comment", userToChange.getComment());
463             response.addComment(conn.jprintf(UserManagment.class.getName(),
464                     "changecomment.success", env));
465         } else if ("idle_time".equals(command)) {
466             if (commandArguments.length != 1)
467                 return usage;
468             int idleTime = Integer.parseInt(commandArguments[0]);
469             logger.info("'" + conn.getUserNull().getUsername()
470                     + "' changed idle_time for '" + userToChange.getUsername()
471                     + "' from '" + userToChange.getIdleTime() + " to '"
472                     + idleTime + "'");
473             userToChange.setIdleTime(idleTime);
474             env.add("idletime", Long.toString(userToChange.getIdleTime()));
475             response.addComment(conn.jprintf(UserManagment.class.getName(),
476                     "changeidletime.success", env));
477         } else if ("num_logins".equals(command)) {
478             // [# sim logins] [# sim logins/ip]
479
try {
480                 int numLogins, numLoginsIP;
481                 if (commandArguments.length < 1 || commandArguments.length > 2) {
482                     return FtpReply.RESPONSE_501_SYNTAX_ERROR;
483                 }
484                 numLogins = Integer.parseInt(commandArguments[0]);
485                 if (commandArguments.length == 2) {
486                     numLoginsIP = Integer.parseInt(commandArguments[1]);
487                 } else {
488                     numLoginsIP = userToChange.getMaxLoginsPerIP();
489                 }
490                 logger.info("'" + conn.getUserNull().getUsername()
491                         + "' changed num_logins for '"
492                         + userToChange.getUsername() + "' from '"
493                         + userToChange.getMaxLogins() + "' '"
494                         + userToChange.getMaxLoginsPerIP() + "' to '"
495                         + numLogins + "' '" + numLoginsIP + "'");
496                 userToChange.setMaxLogins(numLogins);
497                 userToChange.setMaxLoginsPerIP(numLoginsIP);
498                 env
499                         .add("numlogins", Long.toString(userToChange
500                                 .getMaxLogins()));
501                 env.add("numloginsip", Long.toString(userToChange
502                         .getMaxLoginsPerIP()));
503                 response.addComment(conn.jprintf(UserManagment.class.getName(),
504                         "changenumlogins.success", env));
505             } catch (NumberFormatException JavaDoc ex) {
506                 return FtpReply.RESPONSE_501_SYNTAX_ERROR;
507             }
508             //} else if ("max_dlspeed".equalsIgnoreCase(command)) {
509
// myUser.setMaxDownloadRate(Integer.parseInt(commandArgument));
510
//} else if ("max_ulspeed".equals(command)) {
511
// myUser.setMaxUploadRate(Integer.parseInt(commandArgument));
512
} else if ("group".equals(command)) {
513             if (commandArguments.length != 1)
514                 return usage;
515             logger.info("'" + conn.getUserNull().getUsername()
516                     + "' changed primary group for '"
517                     + userToChange.getUsername() + "' from '"
518                     + userToChange.getGroupName() + "' to '"
519                     + commandArguments[0] + "'");
520             userToChange.setGroup(commandArguments[0]);
521             env.add("primgroup", userToChange.getGroupName());
522             response.addComment(conn.jprintf(UserManagment.class.getName(),
523                     "changeprimgroup.success", env));
524             // group_slots Number of users a GADMIN is allowed to add.
525
// If you specify a second argument, it will be the
526
// number of leech accounts the gadmin can give (done by
527
// "site change user ratio 0") (2nd arg = leech slots)
528
} else if ("group_slots".equals(command)) {
529             try {
530                 if (commandArguments.length < 1 || commandArguments.length > 2) {
531                     return FtpReply.RESPONSE_501_SYNTAX_ERROR;
532                 }
533                 short groupSlots = Short.parseShort(commandArguments[0]);
534                 short groupLeechSlots;
535                 if (commandArguments.length >= 2) {
536                     groupLeechSlots = Short.parseShort(commandArguments[1]);
537                 } else {
538                     groupLeechSlots = userToChange.getGroupLeechSlots();
539                 }
540                 logger.info("'" + conn.getUserNull().getUsername()
541                         + "' changed group_slots for '"
542                         + userToChange.getUsername() + "' from '"
543                         + userToChange.getGroupSlots() + "' "
544                         + userToChange.getGroupLeechSlots() + "' to '"
545                         + groupSlots + "' '" + groupLeechSlots + "'");
546                 userToChange.setGroupSlots(groupSlots);
547                 userToChange.setGroupLeechSlots(groupLeechSlots);
548                 env.add("groupslots", "" + userToChange.getGroupSlots());
549                 env.add("groupleechslots", Long.toString(userToChange
550                         .getGroupLeechSlots()));
551                 response.addComment(conn.jprintf(UserManagment.class.getName(),
552                         "changegroupslots.success", env));
553             } catch (NumberFormatException JavaDoc ex) {
554                 return FtpReply.RESPONSE_501_SYNTAX_ERROR;
555             }
556         } else if ("created".equals(command)) {
557             long myDate;
558             if (commandArguments.length == 0) {
559                 try {
560                     myDate = new SimpleDateFormat JavaDoc("yyyy-MM-dd").parse(
561                             commandArguments[0]).getTime();
562                 } catch (ParseException JavaDoc e1) {
563                     logger.log(Level.INFO, e1);
564                     return new FtpReply(200, e1.getMessage());
565                 }
566             } else {
567                 myDate = System.currentTimeMillis();
568             }
569             logger.info("'" + conn.getUserNull().getUsername()
570                     + "' changed created for '" + userToChange.getUsername()
571                     + "' from '" + new Date JavaDoc(userToChange.getCreated())
572                     + "' to '" + new Date JavaDoc(myDate) + "'");
573             userToChange.setCreated(myDate);
574             env.add("created", new Date JavaDoc(myDate));
575             return new FtpReply(200, conn.jprintf(UserManagment.class,
576                     "changecreated.success", env));
577         } else if ("wkly_allotment".equals(command)) {
578             if (commandArguments.length != 1)
579                 return usage;
580             long weeklyAllotment = Bytes.parseBytes(commandArguments[0]);
581             logger.info("'" + conn.getUserNull().getUsername()
582                     + "' changed wkly_allotment for '"
583                     + userToChange.getUsername() + "' from '"
584                     + userToChange.getWeeklyAllotment() + "' to "
585                     + weeklyAllotment + "'");
586             userToChange.setWeeklyAllotment(weeklyAllotment);
587             return FtpReply.RESPONSE_200_COMMAND_OK;
588         } else if ("tagline".equals(command)) {
589             if (commandArguments.length < 1)
590                 return usage;
591             logger.info("'" + conn.getUserNull().getUsername()
592                     + "' changed tagline for '" + userToChange.getUsername()
593                     + "' from '" + userToChange.getTagline() + "' to '"
594                     + fullCommandArgument + "'");
595             userToChange.setTagline(fullCommandArgument);
596             return FtpReply.RESPONSE_200_COMMAND_OK;
597         } else {
598             logger.debug("returning usage as default");
599             return usage;
600         }
601         try {
602             userToChange.commit();
603         } catch (UserFileException e) {
604             logger.warn("", e);
605             response.addComment(e.getMessage());
606         }
607         return response;
608     }
609     /**
610      * USAGE: site chgrp <user><group>[ <group>] Adds/removes a user from
611      * group(s).
612      *
613      * ex. site chgrp archimede ftp This would change the group to 'ftp' for the
614      * user 'archimede'.
615      *
616      * ex1. site chgrp archimede ftp This would remove the group ftp from the
617      * user 'archimede'.
618      *
619      * ex2. site chgrp archimede ftp eleet This moves archimede from ftp group
620      * to eleet group.
621      */

622     private FtpReply doSITE_CHGRP(BaseFtpConnection conn) {
623         FtpRequest request = conn.getRequest();
624         if (!conn.getUserNull().isAdmin()) {
625             return FtpReply.RESPONSE_530_ACCESS_DENIED;
626         }
627         if (!request.hasArgument()) {
628             return new FtpReply(501, conn.jprintf(
629                     UserManagment.class.getName(), "chgrp.usage"));
630         }
631         String JavaDoc args[] = request.getArgument().split("[ ,]");
632         if (args.length < 2) {
633             return FtpReply.RESPONSE_501_SYNTAX_ERROR;
634         }
635         User myUser;
636         try {
637             myUser = conn.getConnectionManager().getUserManager()
638                     .getUserByName(args[0]);
639         } catch (NoSuchUserException e) {
640             return new FtpReply(200, "User not found: " + e.getMessage());
641         } catch (UserFileException e) {
642             logger.log(Level.FATAL, "IO error reading user", e);
643             return new FtpReply(200, "IO error reading user: " + e.getMessage());
644         }
645         FtpReply response = new FtpReply(200);
646         for (int i = 1; i < args.length; i++) {
647             String JavaDoc string = args[i];
648             try {
649                 myUser.removeGroup(string);
650                 logger.info("'" + conn.getUserNull().getUsername()
651                         + "' removed '" + myUser.getUsername()
652                         + "' from group '" + string + "'");
653                 response.addComment(myUser.getUsername()
654                         + " removed from group " + string);
655             } catch (NoSuchFieldException JavaDoc e1) {
656                 try {
657                     myUser.addGroup(string);
658                     logger.info("'" + conn.getUserNull().getUsername()
659                             + "' added '" + myUser.getUsername()
660                             + "' to group '" + string + "'");
661                     response.addComment(myUser.getUsername()
662                             + " added to group " + string);
663                 } catch (DuplicateElementException e2) {
664                     throw new RuntimeException JavaDoc(
665                             "Error, user was not a member before", e2);
666                 }
667             }
668         }
669         return response;
670     }
671     /**
672      * USAGE: site chpass <user> <password>
673      * Change users password.
674      *
675      * ex. site chpass Archimede newpassword
676      * This would change the password to 'newpassword' for the
677      * user 'Archimede'.
678      *
679      * See "site passwd" for more info if you get a "Password is not secure
680      * enough" error.
681      *
682      * * Denotes any password, ex. site chpass arch *
683      * This will allow arch to login with any password
684      *
685      * @ Denotes any email-like password, ex. site chpass arch @
686      * This will allow arch to login with a@b.com but not ab.com
687      */

688     private FtpReply doSITE_CHPASS(BaseFtpConnection conn) {
689         FtpRequest request = conn.getRequest();
690         if (!conn.getUserNull().isAdmin()) {
691             return FtpReply.RESPONSE_530_ACCESS_DENIED;
692         }
693         if (!request.hasArgument()) {
694             return new FtpReply(501, conn.jprintf(
695                     UserManagment.class.getName(), "chpass.usage"));
696         }
697         String JavaDoc args[] = request.getArgument().split(" ");
698         if (args.length != 2) {
699             return FtpReply.RESPONSE_501_SYNTAX_ERROR;
700         }
701         try {
702             User myUser = conn.getConnectionManager().getUserManager()
703                     .getUserByName(args[0]);
704             myUser.setPassword(args[1]);
705             logger.info("'" + conn.getUserNull().getUsername()
706                     + "' changed password for '" + myUser.getUsername() + "'");
707             return FtpReply.RESPONSE_200_COMMAND_OK;
708         } catch (NoSuchUserException e) {
709             return new FtpReply(200, "User not found: " + e.getMessage());
710         } catch (UserFileException e) {
711             logger.log(Level.FATAL, "Error reading userfile", e);
712             return new FtpReply(200, "Error reading userfile: "
713                     + e.getMessage());
714         }
715     }
716     /**
717      * USAGE: site delip <user><ident@ip>...
718      *
719      * @param request
720      * @param out
721      */

722     private FtpReply doSITE_DELIP(BaseFtpConnection conn) {
723         FtpRequest request = conn.getRequest();
724         if (!conn.getUserNull().isAdmin() && !conn.getUserNull().isGroupAdmin()) {
725             return FtpReply.RESPONSE_530_ACCESS_DENIED;
726         }
727         if (!request.hasArgument()) {
728             return new FtpReply(501, conn.jprintf(
729                     UserManagment.class.getName(), "delip.usage"));
730         }
731         String JavaDoc args[] = request.getArgument().split(" ");
732         if (args.length < 2) {
733             return FtpReply.RESPONSE_501_SYNTAX_ERROR;
734         }
735         User myUser;
736         try {
737             myUser = conn.getConnectionManager().getUserManager()
738                     .getUserByName(args[0]);
739         } catch (NoSuchUserException e) {
740             return new FtpReply(200, e.getMessage());
741         } catch (UserFileException e) {
742             logger.log(Level.FATAL, "IO error", e);
743             return new FtpReply(200, "IO error: " + e.getMessage());
744         }
745         if (conn.getUserNull().isGroupAdmin()
746                 && !conn.getUserNull().getGroupName().equals(
747                         myUser.getGroupName())) {
748             return FtpReply.RESPONSE_530_ACCESS_DENIED;
749         }
750         FtpReply response = new FtpReply(200);
751         for (int i = 1; i < args.length; i++) {
752             String JavaDoc string = args[i];
753             try {
754                 myUser.removeIpMask(string);
755                 logger
756                         .info("'" + conn.getUserNull().getUsername()
757                                 + "' removed ip '" + string + "' from '"
758                                 + myUser + "'");
759                 response.addComment("Removed " + string);
760             } catch (NoSuchFieldException JavaDoc e1) {
761                 response.addComment("Mask " + string + " not found: "
762                         + e1.getMessage());
763                 continue;
764             }
765         }
766         return response;
767     }
768     private FtpReply doSITE_DELUSER(BaseFtpConnection conn) {
769         FtpRequest request = conn.getRequest();
770         if (!request.hasArgument()) {
771             return new FtpReply(501, conn.jprintf(
772                     UserManagment.class.getName(), "deluser.usage"));
773         }
774         if (!conn.getUserNull().isAdmin() && !conn.getUserNull().isGroupAdmin()) {
775             return FtpReply.RESPONSE_530_ACCESS_DENIED;
776         }
777         String JavaDoc delUsername = request.getArgument();
778         User myUser;
779         try {
780             myUser = conn.getConnectionManager().getUserManager()
781                     .getUserByName(delUsername);
782         } catch (NoSuchUserException e) {
783             return new FtpReply(200, e.getMessage());
784         } catch (UserFileException e) {
785             return new FtpReply(200, "Couldn't getUser: " + e.getMessage());
786         }
787         if (conn.getUserNull().isGroupAdmin()
788                 && !conn.getUserNull().getGroupName().equals(
789                         myUser.getGroupName())) {
790             return FtpReply.RESPONSE_530_ACCESS_DENIED;
791         }
792         myUser.setDeleted(true);
793         logger.info("'" + conn.getUserNull().getUsername() + "' deleted user '"
794                 + myUser.getUsername() + "'");
795         return FtpReply.RESPONSE_200_COMMAND_OK;
796     }
797     private FtpReply doSITE_GINFO(BaseFtpConnection conn) {
798         FtpRequest request = conn.getRequest();
799         //security
800
if (!conn.getUserNull().isAdmin() && !conn.getUserNull().isGroupAdmin()) {
801             return FtpReply.RESPONSE_530_ACCESS_DENIED;
802         }
803         //syntax
804
if (!request.hasArgument()) {
805             return new FtpReply(501, conn.jprintf(
806                     UserManagment.class.getName(), "ginfo.usage"));
807         }
808         //gadmin
809
String JavaDoc group = request.getArgument();
810         if (conn.getUserNull().isGroupAdmin()
811                 && !conn.getUserNull().getGroupName().equals(group)) {
812             return FtpReply.RESPONSE_530_ACCESS_DENIED;
813         }
814         Collection JavaDoc users;
815         try {
816             users = conn.getConnectionManager().getUserManager()
817                     .getAllUsersByGroup(group);
818         } catch (UserFileException e) {
819             return new FtpReply(200, "IO error: " + e.getMessage());
820         }
821         FtpReply response = new FtpReply(200);
822         for (Iterator JavaDoc iter = users.iterator(); iter.hasNext();) {
823             User user = (User) iter.next();
824             char status = ' ';
825             if (user.isGroupAdmin()) {
826                 status = '+';
827             } else if (user.isAdmin()) {
828                 status = '*';
829             }
830             response.addComment(status + user.getUsername());
831         }
832         response.addComment(" * = siteop + = gadmin");
833         return response;
834     }
835     private FtpReply doSITE_GIVE(BaseFtpConnection conn) {
836         FtpRequest request = conn.getRequest();
837         if (!conn.getConfig().checkGive(conn.getUserNull())) {
838             return FtpReply.RESPONSE_530_ACCESS_DENIED;
839         }
840         if (!request.hasArgument()) {
841             return new FtpReply(501, conn.jprintf(
842                     UserManagment.class.getName(), "give.usage"));
843         }
844         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(request.getArgument());
845         if (!st.hasMoreTokens()) {
846             return FtpReply.RESPONSE_501_SYNTAX_ERROR;
847         }
848         User myUser;
849         try {
850             myUser = conn.getConnectionManager().getUserManager()
851                     .getUserByName(st.nextToken());
852         } catch (Exception JavaDoc e) {
853             logger.warn("", e);
854             return new FtpReply(200, e.getMessage());
855         }
856         if (!st.hasMoreTokens()) {
857             return FtpReply.RESPONSE_501_SYNTAX_ERROR;
858         }
859         long credits = Bytes.parseBytes(st.nextToken());
860         if (0 > credits) {
861             return new FtpReply(200, credits + " is not a positive number.");
862         }
863         if (!conn.getUserNull().isAdmin()) {
864             if (credits > conn.getUserNull().getCredits()) {
865                 return new FtpReply(200,
866                         "You cannot give more credits than you have.");
867             }
868             conn.getUserNull().updateCredits(-credits);
869         }
870         logger.info("'" + conn.getUserNull().getUsername() + "' transfered "
871                 + Bytes.formatBytes(credits) + " ('" + credits + "') to '"
872                 + myUser.getUsername() + "'");
873         myUser.updateCredits(credits);
874         return new FtpReply(200, "OK, gave " + Bytes.formatBytes(credits)
875                 + " of your credits to " + myUser.getUsername());
876     }
877     private FtpReply doSITE_GROUPS(BaseFtpConnection conn) {
878         Collection JavaDoc groups;
879         try {
880             groups = conn.getConnectionManager().getUserManager()
881                     .getAllGroups();
882         } catch (UserFileException e) {
883             logger.log(Level.FATAL, "IO error from getAllGroups()", e);
884             return new FtpReply(200, "IO error: " + e.getMessage());
885         }
886         FtpReply response = new FtpReply(200);
887         response.addComment("All groups:");
888         for (Iterator JavaDoc iter = groups.iterator(); iter.hasNext();) {
889             String JavaDoc element = (String JavaDoc) iter.next();
890             response.addComment(element);
891         }
892         return response;
893     }
894     private FtpReply doSITE_KICK(BaseFtpConnection conn) {
895         FtpRequest request = conn.getRequest();
896         if (!conn.getUserNull().isAdmin()) {
897             return FtpReply.RESPONSE_530_ACCESS_DENIED;
898         }
899         if (!request.hasArgument()) {
900             return new FtpReply(501, conn.jprintf(
901                     UserManagment.class.getName(), "kick.usage"));
902         }
903         String JavaDoc arg = request.getArgument();
904         int pos = arg.indexOf(' ');
905         String JavaDoc username;
906         String JavaDoc message = "Kicked by " + conn.getUserNull().getUsername();
907         if (pos == -1) {
908             username = arg;
909         } else {
910             username = arg.substring(0, pos);
911             message = arg.substring(pos + 1);
912         }
913         FtpReply response = (FtpReply) FtpReply.RESPONSE_200_COMMAND_OK.clone();
914         ArrayList JavaDoc conns = new ArrayList JavaDoc(conn.getConnectionManager()
915                 .getConnections());
916         for (Iterator JavaDoc iter = conns.iterator(); iter.hasNext();) {
917             BaseFtpConnection conn2 = (BaseFtpConnection) iter.next();
918             try {
919                 if (conn2.getUser().getUsername().equals(username)) {
920                     conn2.stop(message);
921                 }
922             } catch (NoSuchUserException e) {
923             }
924         }
925         return response;
926     }
927     private FtpReply doSITE_PASSWD(BaseFtpConnection conn) {
928         FtpRequest request = conn.getRequest();
929         if (!request.hasArgument()) {
930             return new FtpReply(501, conn.jprintf(
931                     UserManagment.class.getName(), "passwd.usage"));
932         }
933         logger.info("'" + conn.getUserNull().getUsername()
934                 + "' changed his password");
935         conn.getUserNull().setPassword(request.getArgument());
936         return FtpReply.RESPONSE_200_COMMAND_OK;
937     }
938     private FtpReply doSITE_PURGE(BaseFtpConnection conn) {
939         FtpRequest request = conn.getRequest();
940         if (!conn.getUserNull().isAdmin() && !conn.getUserNull().isGroupAdmin()) {
941             return FtpReply.RESPONSE_530_ACCESS_DENIED;
942         }
943         if (!request.hasArgument()) {
944             return new FtpReply(501, conn.jprintf(
945                     UserManagment.class.getName(), "purge.usage"));
946         }
947         String JavaDoc delUsername = request.getArgument();
948         User myUser;
949         try {
950             myUser = conn.getConnectionManager().getUserManager()
951                     .getUserByNameUnchecked(delUsername);
952         } catch (NoSuchUserException e) {
953             return new FtpReply(200, e.getMessage());
954         } catch (UserFileException e) {
955             return new FtpReply(200, "Couldn't getUser: " + e.getMessage());
956         }
957         if (!myUser.isDeleted()) {
958             return new FtpReply(200, "User isn't deleted");
959         }
960         if (conn.getUserNull().isGroupAdmin()
961                 && !conn.getUserNull().getGroupName().equals(
962                         myUser.getGroupName())) {
963             return FtpReply.RESPONSE_530_ACCESS_DENIED;
964         }
965         myUser.purge();
966         logger.info("'" + conn.getUserNull().getUsername() + "' purged '"
967                 + myUser.getUsername() + "'");
968         return FtpReply.RESPONSE_200_COMMAND_OK;
969     }
970     private FtpReply doSITE_READD(BaseFtpConnection conn) {
971         FtpRequest request = conn.getRequest();
972         if (!conn.getUserNull().isAdmin() && !conn.getUserNull().isGroupAdmin()) {
973             return FtpReply.RESPONSE_530_ACCESS_DENIED;
974         }
975         if (!request.hasArgument()) {
976             return new FtpReply(501, conn.jprintf(
977                     UserManagment.class.getName(), "readd.usage"));
978         }
979         User myUser;
980         try {
981             myUser = conn.getConnectionManager().getUserManager()
982                     .getUserByNameUnchecked(request.getArgument());
983         } catch (NoSuchUserException e) {
984             return new FtpReply(200, e.getMessage());
985         } catch (UserFileException e) {
986             return new FtpReply(200, "IO error: " + e.getMessage());
987         }
988         if (conn.getUserNull().isGroupAdmin()
989                 && !conn.getUserNull().getGroupName().equals(
990                         myUser.getGroupName())) {
991             return FtpReply.RESPONSE_530_ACCESS_DENIED;
992         }
993         if (!myUser.isDeleted()) {
994             return new FtpReply(200, "User wasn't deleted");
995         }
996         myUser.setDeleted(false);
997         logger.info("'" + conn.getUserNull().getUsername() + "' readded '"
998                 + myUser.getUsername() + "'");
999         return FtpReply.RESPONSE_200_COMMAND_OK;
1000    }
1001    private FtpReply doSITE_RENUSER(BaseFtpConnection conn) {
1002        FtpRequest request = conn.getRequest();
1003        if (!conn.getUserNull().isAdmin()) {
1004            return FtpReply.RESPONSE_530_ACCESS_DENIED;
1005        }
1006        if (!request.hasArgument()) {
1007            return new FtpReply(501, conn.jprintf(
1008                    UserManagment.class.getName(), "renuser.usage"));
1009        }
1010        String JavaDoc args[] = request.getArgument().split(" ");
1011        if (args.length != 2) {
1012            return FtpReply.RESPONSE_501_SYNTAX_ERROR;
1013        }
1014        try {
1015            User myUser = conn.getConnectionManager().getUserManager()
1016                    .getUserByName(args[0]);
1017            String JavaDoc oldUsername = myUser.getUsername();
1018            myUser.rename(args[1]);
1019            logger.info("'" + conn.getUserNull().getUsername() + "' renamed '"
1020                    + oldUsername + "' to '" + myUser.getUsername() + "'");
1021        } catch (NoSuchUserException e) {
1022            return new FtpReply(200, "No such user: " + e.getMessage());
1023        } catch (UserExistsException e) {
1024            return new FtpReply(200, "Target username is already taken");
1025        } catch (UserFileException e) {
1026            return new FtpReply(200, e.getMessage());
1027        }
1028        return FtpReply.RESPONSE_200_COMMAND_OK;
1029    }
1030    private FtpReply doSITE_SEEN(BaseFtpConnection conn) {
1031        FtpRequest request = conn.getRequest();
1032        if (!request.hasArgument()) {
1033            return new FtpReply(501, conn.jprintf(
1034                    UserManagment.class.getName(), "seen.usage"));
1035        }
1036        User user;
1037        try {
1038            user = conn.getConnectionManager().getUserManager().getUserByName(
1039                    request.getArgument());
1040        } catch (NoSuchUserException e) {
1041            return new FtpReply(200, e.getMessage());
1042        } catch (UserFileException e) {
1043            logger.log(Level.FATAL, "", e);
1044            return new FtpReply(200, "Error reading userfile: "
1045                    + e.getMessage());
1046        }
1047        return new FtpReply(200, "User was last seen: "
1048                + new Date JavaDoc(user.getLastAccessTime()));
1049    }
1050    private FtpReply doSITE_TAGLINE(BaseFtpConnection conn) {
1051        FtpRequest request = conn.getRequest();
1052        if (!request.hasArgument()) {
1053            return new FtpReply(501, conn.jprintf(
1054                    UserManagment.class.getName(), "tagline.usage"));
1055        }
1056        logger.info("'" + conn.getUserNull().getUsername()
1057                + "' changed his tagline from '"
1058                + conn.getUserNull().getTagline() + "' to '"
1059                + request.getArgument() + "'");
1060        conn.getUserNull().setTagline(request.getArgument());
1061        return FtpReply.RESPONSE_200_COMMAND_OK;
1062    }
1063    /**
1064     * USAGE: site take <user><kbytes>[ <message>] Removes credit from user
1065     *
1066     * ex. site take Archimede 100000 haha
1067     *
1068     * This will remove 100mb of credits from the user 'Archimede' and send the
1069     * message haha to him.
1070     */

1071    private FtpReply doSITE_TAKE(BaseFtpConnection conn) {
1072        FtpRequest request = conn.getRequest();
1073        if (!conn.getConfig().checkTake(conn.getUserNull())) {
1074            return FtpReply.RESPONSE_530_ACCESS_DENIED;
1075        }
1076        if (!request.hasArgument()) {
1077            return new FtpReply(501, conn.jprintf(
1078                    UserManagment.class.getName(), "take.usage"));
1079        }
1080        StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(request.getArgument());
1081        if (!st.hasMoreTokens()) {
1082            return FtpReply.RESPONSE_501_SYNTAX_ERROR;
1083        }
1084        User myUser;
1085        long credits;
1086        try {
1087            myUser = conn.getConnectionManager().getUserManager()
1088                    .getUserByName(st.nextToken());
1089            if (!st.hasMoreTokens()) {
1090                return FtpReply.RESPONSE_501_SYNTAX_ERROR;
1091            }
1092            credits = Bytes.parseBytes(st.nextToken()); // B, not KiB
1093
if (0 > credits) {
1094                return new FtpReply(200, "Credits must be a positive number.");
1095            }
1096            logger.info("'" + conn.getUserNull().getUsername() + "' took "
1097                    + Bytes.formatBytes(credits) + " ('" + credits
1098                    + "') from '" + myUser.getUsername() + "'");
1099            myUser.updateCredits(-credits);
1100        } catch (Exception JavaDoc ex) {
1101            return new FtpReply(200, ex.getMessage());
1102        }
1103        return new FtpReply(200, "OK, removed " + credits + "b from "
1104                + myUser.getUsername() + ".");
1105    }
1106    /**
1107     * USAGE: site user [ <user>] Lists users / Shows detailed info about a
1108     * user.
1109     *
1110     * ex. site user
1111     *
1112     * This will display a list of all users currently on site.
1113     *
1114     * ex. site user Archimede
1115     *
1116     * This will show detailed information about user 'Archimede'.
1117     */

1118    private FtpReply doSITE_USER(BaseFtpConnection conn) {
1119        FtpRequest request = conn.getRequest();
1120        if (!conn.getUserNull().isAdmin() && !conn.getUserNull().isGroupAdmin()) {
1121            return FtpReply.RESPONSE_530_ACCESS_DENIED;
1122        }
1123        if (!request.hasArgument()) {
1124            return new FtpReply(501, conn.jprintf(
1125                    UserManagment.class.getName(), "user.usage"));
1126        }
1127        FtpReply response = (FtpReply) FtpReply.RESPONSE_200_COMMAND_OK.clone();
1128        User myUser;
1129        try {
1130            myUser = conn.getConnectionManager().getUserManager()
1131                    .getUserByNameUnchecked(request.getArgument());
1132        } catch (NoSuchUserException ex) {
1133            response.setMessage("User " + request.getArgument() + " not found");
1134            return response;
1135            //return FtpResponse.RESPONSE_200_COMMAND_OK);
1136
} catch (UserFileException ex) {
1137            return new FtpReply(200, ex.getMessage());
1138        }
1139        if (conn.getUserNull().isGroupAdmin()
1140                && !conn.getUserNull().getGroupName().equals(
1141                        myUser.getGroupName())) {
1142            return FtpReply.RESPONSE_501_SYNTAX_ERROR;
1143        }
1144        //int i = (int) (myUser.getTimeToday() / 1000);
1145
//int hours = i / 60;
1146
//int minutes = i - hours * 60;
1147
//response.addComment("time on today: " + hours + ":" + minutes);
1148
ReplacerEnvironment env = new ReplacerEnvironment();
1149        env.add("username", myUser.getUsername());
1150        env.add("created", new Date JavaDoc(myUser.getCreated()));
1151        env.add("comment", myUser.getComment());
1152        env.add("lastseen", new Date JavaDoc(myUser.getLastAccessTime()));
1153        env.add("totallogins", Long.toString(myUser.getLogins()));
1154        env.add("idletime", Long.toString(myUser.getIdleTime()));
1155        env.add("userratio", Float.toString(myUser.getRatio()));
1156        env.add("usercredits", Bytes.formatBytes(myUser.getCredits()));
1157        env.add("maxlogins", Long.toString(myUser.getMaxLogins()));
1158        env.add("maxloginsip", Long.toString(myUser.getMaxLoginsPerIP()));
1159        env.add("maxsimup", Long.toString(myUser.getMaxSimUploads()));
1160        env.add("maxsimdn", Long.toString(myUser.getMaxSimDownloads()));
1161        env.add("groupslots", Long.toString(myUser.getGroupSlots()));
1162        env.add("groupleechslots", Long.toString(myUser.getGroupLeechSlots()));
1163        env.add("useruploaded", Bytes.formatBytes(myUser.getUploadedBytes()));
1164        env.add("userdownloaded", Bytes
1165                .formatBytes(myUser.getDownloadedBytes()));
1166        env.add("timesnuked", Long.toString(myUser.getTimesNuked()));
1167        env.add("nukedbytes", Bytes.formatBytes(myUser.getNukedBytes()));
1168        env.add("primarygroup", myUser.getGroupName());
1169        env.add("extragroups", myUser.getGroups());
1170        env.add("ipmasks", myUser.getIpMasks());
1171        response.addComment(conn.jprintf(UserManagment.class.getName(),
1172                "user.username", env));
1173        response.addComment(conn.jprintf(UserManagment.class.getName(),
1174                "user.comment", env));
1175        response.addComment(conn.jprintf(UserManagment.class.getName(),
1176                "user.idle", env));
1177        response.addComment(conn.jprintf(UserManagment.class.getName(),
1178                "user.ratio", env));
1179        response.addComment(conn.jprintf(UserManagment.class.getName(),
1180                "user.logins", env));
1181        response.addComment(conn.jprintf(UserManagment.class.getName(),
1182                "user.maxsim", env));
1183        response.addComment(conn.jprintf(UserManagment.class.getName(),
1184                "user.groupslots", env));
1185        response.addComment(conn.jprintf(UserManagment.class.getName(),
1186                "user.xfer", env));
1187        response.addComment(conn.jprintf(UserManagment.class.getName(),
1188                "user.nuke", env));
1189        response.addComment(conn.jprintf(UserManagment.class.getName(),
1190                "user.primarygroup", env));
1191        response.addComment(conn.jprintf(UserManagment.class.getName(),
1192                "user.extragroups", env));
1193        response.addComment(conn.jprintf(UserManagment.class.getName(),
1194                "user.ipmasks", env));
1195        return response;
1196    }
1197    private FtpReply doSITE_USERS(BaseFtpConnection conn) {
1198        FtpRequest request = conn.getRequest();
1199        if (!conn.getUserNull().isAdmin()) {
1200            return FtpReply.RESPONSE_530_ACCESS_DENIED;
1201        }
1202        FtpReply response = new FtpReply(200);
1203        Collection JavaDoc myUsers;
1204        try {
1205            myUsers = conn.getConnectionManager().getUserManager()
1206                    .getAllUsers();
1207        } catch (UserFileException e) {
1208            logger.log(Level.FATAL, "IO error reading all users", e);
1209            return new FtpReply(200, "IO error: " + e.getMessage());
1210        }
1211        if (request.hasArgument()) {
1212            Permission perm = new Permission(FtpConfig
1213                    .makeUsers(new StringTokenizer JavaDoc(request.getArgument())));
1214            for (Iterator JavaDoc iter = myUsers.iterator(); iter.hasNext();) {
1215                User element = (User) iter.next();
1216                if (!perm.check(element))
1217                    iter.remove();
1218            }
1219        }
1220        for (Iterator JavaDoc iter = myUsers.iterator(); iter.hasNext();) {
1221            User myUser = (User) iter.next();
1222            response.addComment(myUser.getUsername());
1223        }
1224        response.addComment("Ok, " + myUsers.size() + " users listed.");
1225        return response;
1226    }
1227    /**
1228     * Lists currently connected users.
1229     */

1230    private FtpReply doSITE_WHO(BaseFtpConnection conn) {
1231        FtpReply response = (FtpReply) FtpReply.RESPONSE_200_COMMAND_OK.clone();
1232        long users = 0, speedup = 0, speeddn = 0, speed = 0;
1233        try {
1234            ReplacerFormat formatup = ReplacerUtils.finalFormat(
1235                    UserManagment.class, "who.up");
1236            ReplacerFormat formatdown = ReplacerUtils.finalFormat(
1237                    UserManagment.class, "who.down");
1238            ReplacerFormat formatidle = ReplacerUtils.finalFormat(
1239                    UserManagment.class, "who.idle");
1240            ReplacerFormat formatcommand = ReplacerUtils.finalFormat(
1241                    UserManagment.class, "who.command");
1242            ReplacerEnvironment env = new ReplacerEnvironment();
1243            ArrayList JavaDoc conns = new ArrayList JavaDoc(conn.getConnectionManager()
1244                    .getConnections());
1245            for (Iterator JavaDoc iter = conns.iterator(); iter.hasNext();) {
1246                BaseFtpConnection conn2 = (BaseFtpConnection) iter.next();
1247                if (conn2.isAuthenticated()) {
1248                    users++;
1249                    User user;
1250                    try {
1251                        user = conn2.getUser();
1252                    } catch (NoSuchUserException e) {
1253                        continue;
1254                    }
1255                    if (conn.getConfig().checkHideInWho(user,
1256                            conn2.getCurrentDirectory()))
1257                        continue;
1258                    //StringBuffer status = new StringBuffer();
1259
env.add("idle", Time.formatTime(System.currentTimeMillis()
1260                            - conn2.getLastActive()));
1261                    env.add("targetuser", user.getUsername());
1262                    if (!conn2.isExecuting()) {
1263                        response.addComment(SimplePrintf.jprintf(formatidle,
1264                                env));
1265                    } else if (conn2.getDataConnectionHandler().isTransfering()) {
1266                        if (conn2.getDataConnectionHandler().isTransfering()) {
1267                            try {
1268                                speed = conn2.getDataConnectionHandler()
1269                                        .getTransfer().getXferSpeed();
1270                                env.add("speed", Bytes.formatBytes(speed)
1271                                        + "/s");
1272                            } catch (RemoteException JavaDoc e2) {
1273                                logger.warn("", e2);
1274                            }
1275                            env.add("file", conn2.getDataConnectionHandler()
1276                                    .getTransferFile().getName());
1277                            env.add("slave", conn2.getDataConnectionHandler()
1278                                    .getTranferSlave().getName());
1279                        }
1280                        if (conn2.getTransferDirection() == Transfer.TRANSFER_RECEIVING_UPLOAD) {
1281                            response.addComment(SimplePrintf.jprintf(formatup,
1282                                    env));
1283                            speedup += speed;
1284                        } else if (conn2.getTransferDirection() == Transfer.TRANSFER_SENDING_DOWNLOAD) {
1285                            response.addComment(SimplePrintf.jprintf(
1286                                    formatdown, env));
1287                            speeddn += speed;
1288                        }
1289                    } else {
1290                        env.add("command", conn2.getRequest().getCommand());
1291                        response.addComment(SimplePrintf.jprintf(formatcommand,
1292                                env));
1293                    }
1294                }
1295            }
1296            env.add("currentusers", Long.toString(users));
1297            env.add("maxusers", Long.toString(conn.getConfig()
1298                    .getMaxUsersTotal()));
1299            env.add("totalupspeed", Bytes.formatBytes(speedup) + "/s");
1300            env.add("totaldnspeed", Bytes.formatBytes(speeddn) + "/s");
1301            response.addComment("");
1302            response.addComment(conn.jprintf(UserManagment.class.getName(),
1303                    "who.statusspeed", env));
1304            response.addComment(conn.jprintf(UserManagment.class.getName(),
1305                    "who.statususers", env));
1306            return response;
1307        } catch (FormatterException e) {
1308            return new FtpReply(200, e.getMessage());
1309        }
1310    }
1311    /*
1312     * (non-Javadoc)
1313     *
1314     * @see net.sf.drftpd.master.command.CommandHandler#execute(net.sf.drftpd.master.BaseFtpConnection)
1315     */

1316    public FtpReply execute(BaseFtpConnection conn)
1317            throws UnhandledCommandException {
1318        String JavaDoc cmd = conn.getRequest().getCommand();
1319        if ("SITE ADDIP".equals(cmd))
1320            return doSITE_ADDIP(conn);
1321        if ("SITE CHANGE".equals(cmd))
1322            return doSITE_CHANGE(conn);
1323        if ("SITE CHGRP".equals(cmd))
1324            return doSITE_CHGRP(conn);
1325        if ("SITE CHPASS".equals(cmd))
1326            return doSITE_CHPASS(conn);
1327        if ("SITE DELIP".equals(cmd))
1328            return doSITE_DELIP(conn);
1329        if ("SITE DELUSER".equals(cmd))
1330            return doSITE_DELUSER(conn);
1331        if ("SITE ADDUSER".equals(cmd) || "SITE GADDUSER".equals(cmd))
1332            return doSITE_ADDUSER(conn);
1333        if ("SITE GINFO".equals(cmd))
1334            return doSITE_GINFO(conn);
1335        if ("SITE GIVE".equals(cmd))
1336            return doSITE_GIVE(conn);
1337        if ("SITE GROUPS".equals(cmd))
1338            return doSITE_GROUPS(conn);
1339        if ("SITE KICK".equals(cmd))
1340            return doSITE_KICK(conn);
1341        if ("SITE PASSWD".equals(cmd))
1342            return doSITE_PASSWD(conn);
1343        if ("SITE PURGE".equals(cmd))
1344            return doSITE_PURGE(conn);
1345        if ("SITE READD".equals(cmd))
1346            return doSITE_READD(conn);
1347        if ("SITE RENUSER".equals(cmd))
1348            return doSITE_RENUSER(conn);
1349        if ("SITE SEEN".equals(cmd))
1350            return doSITE_SEEN(conn);
1351        if ("SITE TAGLINE".equals(cmd))
1352            return doSITE_TAGLINE(conn);
1353        if ("SITE TAKE".equals(cmd))
1354            return doSITE_TAKE(conn);
1355        if ("SITE USER".equals(cmd))
1356            return doSITE_USER(conn);
1357        if ("SITE USERS".equals(cmd))
1358            return doSITE_USERS(conn);
1359        if ("SITE WHO".equals(cmd))
1360            return doSITE_WHO(conn);
1361        throw UnhandledCommandException.create(UserManagment.class, conn
1362                .getRequest());
1363    }
1364    public String JavaDoc[] getFeatReplies() {
1365        return null;
1366    }
1367    public CommandHandler initialize(BaseFtpConnection conn,
1368            CommandManager initializer) {
1369        return this;
1370    }
1371    public void load(CommandManagerFactory initializer) {
1372    }
1373    public void unload() {
1374    }
1375}
Popular Tags