001: /*
002: * Created on Sep 6, 2004
003: */
004: package org.drftpd.plugins;
005:
006: import java.beans.XMLDecoder;
007: import java.beans.XMLEncoder;
008: import java.io.FileInputStream;
009: import java.io.FileNotFoundException;
010: import java.io.FileOutputStream;
011: import java.io.IOException;
012: import java.util.Collection;
013: import java.util.HashMap;
014: import java.util.HashSet;
015: import java.util.Iterator;
016: import java.util.MissingResourceException;
017: import java.util.ResourceBundle;
018: import java.util.StringTokenizer;
019:
020: import javax.imageio.stream.FileImageInputStream;
021:
022: import net.sf.drftpd.FileExistsException;
023: import net.sf.drftpd.master.BaseFtpConnection;
024: import net.sf.drftpd.master.command.CommandManager;
025: import net.sf.drftpd.master.command.CommandManagerFactory;
026:
027: import org.apache.log4j.Logger;
028: import org.drftpd.commands.CommandHandler;
029: import org.drftpd.commands.CommandHandlerFactory;
030: import org.drftpd.commands.Reply;
031: import org.drftpd.commands.ReplyException;
032: import org.drftpd.commands.UnhandledCommandException;
033: import org.drftpd.io.SafeFileOutputStream;
034: import org.drftpd.master.ConnectionManager;
035: import org.drftpd.remotefile.LinkedRemoteFile;
036: import org.drftpd.usermanager.User;
037: import org.drftpd.usermanager.UserFileException;
038: import org.tanesha.replacer.ReplacerEnvironment;
039:
040: /**
041: * @author Teflon
042: */
043: public class TDPAffilManagement implements CommandHandler,
044: CommandHandlerFactory {
045: private static final Logger logger = Logger
046: .getLogger(TDPAffilManagement.class);
047:
048: String _affilsRoot;
049: HashSet<String> _affils = new HashSet<String>();
050:
051: HashMap<String, String> _allowedGroups;
052:
053: ConnectionManager _cm;
054:
055: //boolean _loadSuccess = false;
056:
057: //HashMap<String, String> _template;
058:
059: public TDPAffilManagement() throws FileNotFoundException {
060: super ();
061: readPerms();
062: }
063:
064: /**
065: * @throws FileNotFoundException
066: *
067: */
068: private void readPerms() throws FileNotFoundException {
069: XMLDecoder in = new XMLDecoder(
070: new FileInputStream("affils.xml"));
071: _affils = (HashSet<String>) in.readObject();
072: }
073:
074: public Reply doSITE_ADDAFFIL(BaseFtpConnection conn)
075: throws ReplyException {
076: if (!conn.getRequest().hasArgument()) {
077: return new Reply(202, "Usage: site addaffil <group>");
078: }
079:
080: StringTokenizer st = new StringTokenizer(conn.getRequest()
081: .getArgument(), " ");
082: if (!st.hasMoreTokens()) {
083: return Reply.RESPONSE_501_SYNTAX_ERROR;
084: }
085:
086: String group = st.nextToken();
087: ReplacerEnvironment env = new ReplacerEnvironment();
088: env.add("group", group);
089: env.add("affilsroot", _affilsRoot);
090:
091: Reply response = (Reply) Reply.RESPONSE_200_COMMAND_OK.clone();
092: // ArrayList<String> permsData = readPerms();
093:
094: // for (Iterator iter = permsData.iterator(); iter.hasNext();) {
095: // if (((String) iter.next()).startsWith(AM_START + group)) {
096: // return new Reply(550, "Requested action not taken. " + "Affil "
097: // + group + " already exists in perms.conf.");
098: // }
099: // }
100: //
101: // permsData.add("");
102: // permsData.add(AM_START + group);
103: _affils.add(group);
104: // for (Iterator iter = _template.keySet().iterator(); iter.hasNext();) {
105: // String perm = (String) iter.next();
106: // String template = (String) _template.get(perm);
107: // if (template.equals(""))
108: // continue;
109: //
110: // try {
111: // template = SimplePrintf.jprintf(template, env);
112: // } catch (FormatterException e) {
113: // response.addComment(e.getMessage());
114: // return response;
115: // }
116: // permsData.add(paddingString(perm, 11, ' ', false) + " " + template);
117: // }
118: // permsData.add(AM_END + group);
119: // writePerms(permsData);
120: try {
121: writePerms();
122: } catch (IOException e) {
123: throw new ReplyException(e);
124: }
125: response.addComment("Added " + group + " to perms.conf");
126:
127: try {
128: LinkedRemoteFile aRoot = conn.getGlobalContext().getRoot()
129: .lookupFile(_affilsRoot);
130: aRoot.createDirectory(conn.getUserNull().getName(), conn
131: .getUserNull().getGroup(), group);
132: response.addComment("Created group dir " + _affilsRoot
133: + "/" + group);
134: } catch (FileNotFoundException e1) {
135: String err = "Affils root dir (" + _affilsRoot
136: + ") was not found on site.";
137: logger.warn(err, e1);
138: response.addComment(err);
139: } catch (FileExistsException e) {
140: logger.warn("Couldn't create affil pre dir for " + group
141: + ". It already exists.");
142: response.addComment("Group directory " + _affilsRoot + "/"
143: + group + " already exists.");
144: }
145: //
146: // response.addComment("Executing SITE RELOAD");
147: // String ret = doSITE_RELOAD(conn);
148: // if (!ret.equals(""))
149: // response.addComment(ret);
150:
151: return response;
152: }
153:
154: private void writePerms() throws IOException {
155: XMLEncoder out = new XMLEncoder(new SafeFileOutputStream(
156: "affils.xml"));
157: out.writeObject(_affils);
158: out.close();
159: }
160:
161: public Reply doSITE_AFFILS(BaseFtpConnection conn) {
162: Reply response = (Reply) Reply.RESPONSE_200_COMMAND_OK.clone();
163: // ArrayList permsData = readPerms();
164: // for (Iterator iter = permsData.iterator(); iter.hasNext();) {
165: for (String affil : _affils) {
166: // String line = (String) iter.next();
167: // if (line.startsWith("#TDPAffilManagement")) {
168: // String amLine[] = line.split(" ");
169: // if (amLine.length < 3) {
170: // logger.info("Ignoring Invalid TDPAM line: " + line);
171: // continue;
172: // }
173: //
174: // if (amLine[1].equals("START")) {
175: // String group = amLine[2];
176: // // logger.info("Processing configuration for group " +
177: // // group);
178: // do {
179: // line = (String) iter.next();
180: // if (line.startsWith(AM_END + group)) {
181: response.addComment("Found " + affil);
182: // }
183: // } while (!line.startsWith("#TDPAffilManagement")
184: // && iter.hasNext());
185: //
186: // }
187: // }
188: //
189: }
190: return response;
191: }
192:
193: public Reply doSITE_DELAFFIL(BaseFtpConnection conn) {
194: if (!conn.getRequest().hasArgument()) {
195: return new Reply(202,
196: "Usage: site delaffil <group> [-delusers]");
197: }
198:
199: StringTokenizer st = new StringTokenizer(conn.getRequest()
200: .getArgument(), " ");
201: if (!st.hasMoreTokens()) {
202: return Reply.RESPONSE_501_SYNTAX_ERROR;
203: }
204: String group = st.nextToken();
205: boolean delusers = false;
206: if (st.hasMoreTokens() && st.nextToken().equals("-delusers")) {
207: delusers = true;
208: }
209:
210: Reply response = (Reply) Reply.RESPONSE_200_COMMAND_OK.clone();
211: //HashSet<String> permsData = readPerms();
212: //permsData.add(group);
213: if (_affils.remove(group)) {
214: response.addComment("Deleted " + group);
215: } else {
216: response.addComment(group + " not found");
217: }
218: //writePerms(permsData);
219:
220: try {
221: LinkedRemoteFile aRoot = conn.getGlobalContext().getRoot()
222: .lookupFile(_affilsRoot + "/" + group);
223: aRoot.delete();
224: response.addComment("Deleted group dir " + _affilsRoot
225: + "/" + group);
226: } catch (FileNotFoundException e) {
227: response.addComment("Could not delete group dir "
228: + _affilsRoot + "/" + group);
229: }
230:
231: if (delusers) {
232: try {
233: Collection gusers = conn.getGlobalContext()
234: .getUserManager().getAllUsersByGroup(group);
235: for (Iterator iter = gusers.iterator(); iter.hasNext();) {
236: User user = (User) iter.next();
237: user.setDeleted(true);
238: user.commit();
239: response.addComment("Deleted user "
240: + user.getName());
241: }
242: } catch (UserFileException e1) {
243: response.addComment("Error retrieving users in group "
244: + group);
245: }
246: } else {
247: response.addComment("No users were deleted");
248: }
249:
250: response.addComment("Reloading perms.conf");
251: // String ret = doSITE_RELOAD(conn);
252: // if (!ret.equals(""))
253: // response.addComment(ret);
254:
255: return response;
256: }
257:
258: public Reply execute(BaseFtpConnection conn) throws ReplyException {
259:
260: if (!isAllowed(conn))
261: return Reply.RESPONSE_530_ACCESS_DENIED;
262:
263: String cmd = conn.getRequest().getCommand();
264: if ("SITE AFFILS".equals(cmd))
265: return doSITE_AFFILS(conn);
266: if ("SITE ADDAFFIL".equals(cmd))
267: return doSITE_ADDAFFIL(conn);
268: if ("SITE DELAFFIL".equals(cmd))
269: return doSITE_DELAFFIL(conn);
270: throw UnhandledCommandException.create(
271: TDPAffilManagement.class, conn.getRequest());
272: }
273:
274: public String[] getFeatReplies() {
275: return null;
276: }
277:
278: public CommandHandler initialize(BaseFtpConnection conn,
279: CommandManager initializer) {
280: return this ;
281: }
282:
283: public boolean isAllowed(BaseFtpConnection conn) {
284: String cmd = conn.getRequest().getCommand().substring(
285: "SITE ".length()).toLowerCase();
286: String groups[] = ((String) _allowedGroups.get(cmd + ".allow"))
287: .split(" ");
288: for (int i = 0; i < groups.length; i++) {
289: if (conn.getUserNull().isMemberOf(groups[i]))
290: return true;
291: }
292: return false;
293: }
294:
295: public void load(CommandManagerFactory initializer) {
296: loadSettings();
297: }
298:
299: public boolean loadSettings() {
300: //_template = new HashMap<String, String>();
301: _allowedGroups = new HashMap<String, String>();
302: ResourceBundle bundle = ResourceBundle
303: .getBundle(TDPAffilManagement.class.getName());
304: try {
305: _allowedGroups.put("affils.allow", bundle
306: .getString("affils.allow"));
307: _allowedGroups.put("addaffil.allow", bundle
308: .getString("addaffil.allow"));
309: _allowedGroups.put("delaffil.allow", bundle
310: .getString("delaffil.allow"));
311:
312: _affilsRoot = bundle.getString("affilsroot");
313:
314: // _template.put("pre", bundle.getString("template.pre"));
315: // _template.put("privpath", bundle.getString("template.privpath"));
316: // _template.put("makedir", bundle.getString("template.makedir"));
317: // _template.put("delete", bundle.getString("template.delete"));
318: // _template.put("rename", bundle.getString("template.rename"));
319: // _template
320: // .put("creditloss", bundle.getString("template.creditloss"));
321: } catch (MissingResourceException e) {
322: logger
323: .warn(
324: "Error reading config in TDPAffilManagement.properties",
325: e);
326: logger.warn("TDPAffilManagement will be disabled");
327: return false;
328: }
329:
330: logger.info("TDPAffilManagement plugin loaded successfully");
331: return true;
332: }
333:
334: public synchronized String paddingString(String s, int n, char c,
335: boolean paddingLeft) {
336: StringBuffer str = new StringBuffer(s);
337: int strLength = str.length();
338: if (n > 0 && n > strLength) {
339: for (int i = 0; i <= n; i++) {
340: if (paddingLeft) {
341: if (i < n - strLength)
342: str.insert(0, c);
343: } else {
344: if (i > strLength)
345: str.append(c);
346: }
347: }
348: }
349: return str.toString();
350: }
351:
352: // /**
353: // *
354: // */
355: // public ArrayList<String> readPerms() {
356: // ArrayList<String> permsData = new ArrayList<String>();
357: // try {
358: // BufferedReader br = new BufferedReader(new InputStreamReader(
359: // new FileInputStream("conf/perms.conf")));
360: // String line = "";
361: // while ((line = br.readLine()) != null) {
362: // permsData.add(line);
363: // }
364: // br.close();
365: // } catch (FileNotFoundException e) {
366: // logger.warn("Error reading perms.conf file", e);
367: // return null;
368: // } catch (IOException e) {
369: // logger.warn("Error reading perms.conf file", e);
370: // return null;
371: // }
372: // return permsData;
373: // }
374:
375: public void unload() {
376: }
377:
378: // private void writePerms(ArrayList permsData) {
379: // logger.info("Saving perms.conf file");
380: // try {
381: // PrintWriter out = new PrintWriter(new SafeFileWriter(
382: // "conf/perms.conf"));
383: // for (Iterator iter = permsData.iterator(); iter.hasNext();) {
384: // String line = (String) iter.next();
385: // out.println(line);
386: // }
387: // out.close();
388: // } catch (IOException e) {
389: // logger.warn("Error saving perms.conf", e);
390: // }
391: // }
392:
393: }
|