From 1bc83891c68ee269727e81a13cc70da698bcc7a7 Mon Sep 17 00:00:00 2001 From: Simon Rettberg Date: Tue, 2 Jun 2015 19:53:31 +0200 Subject: [server] Compiling again, still lots of stubs --- .../src/main/java/server/ServerHandler.java | 621 ++++++++------------- .../src/main/java/server/SessionManager.java | 84 +++ .../src/main/java/server/StartServer.java | 45 +- 3 files changed, 347 insertions(+), 403 deletions(-) create mode 100644 dozentenmodulserver/src/main/java/server/SessionManager.java (limited to 'dozentenmodulserver/src/main/java/server') diff --git a/dozentenmodulserver/src/main/java/server/ServerHandler.java b/dozentenmodulserver/src/main/java/server/ServerHandler.java index b5d7bc54..bc16273f 100644 --- a/dozentenmodulserver/src/main/java/server/ServerHandler.java +++ b/dozentenmodulserver/src/main/java/server/ServerHandler.java @@ -1,13 +1,9 @@ package server; import java.io.File; +import java.io.FileNotFoundException; import java.io.IOException; -import java.math.BigInteger; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; +import java.nio.ByteBuffer; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -19,244 +15,113 @@ import models.Configuration; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.apache.thrift.TException; -import org.openslx.imagemaster.thrift.iface.ImageServer.Client; import org.openslx.imagemaster.thrift.iface.UserInfo; import org.openslx.sat.thrift.iface.Image; import org.openslx.sat.thrift.iface.Lecture; import org.openslx.sat.thrift.iface.Person; import org.openslx.sat.thrift.iface.Server; -import org.openslx.sat.thrift.iface.User; +import org.openslx.sat.thrift.iface.TUploadFinishException; +import org.openslx.sat.thrift.iface.TUploadRejectedException; +import org.openslx.sat.thrift.iface.TransferInformation; import org.openslx.sat.thrift.version.Version; import sql.SQL; -import thrift.MasterThriftConnection; +import util.Constants; +import util.FileSystem; +import util.Formatter; +import fileserv.ActiveUpload; +import fileserv.FileServer; public class ServerHandler implements Server.Iface { - private static Logger log = Logger.getLogger(ServerHandler.class); - static SQL sql = new SQL(); - - // saves the current tokens and the mapped userdata, returning from the server - // TODO: Handle/cache tokens in own class, add timeout to tokens in case client never marks it invalid - private Map tokenManager = new HashMap<>(); - - public boolean authenticated(String token) throws TException { - if (tokenManager.get(token) != null) { - // user found in tokenManager, session was set to valid once before - // (cached session, no further action needed) - return true; - } else { - MasterThriftConnection thrift = new MasterThriftConnection(); - Client client = thrift.getMasterThriftConnection(); - - // user not in tokenManager, check authentication, then add user to tokenManager - log.info("token is: " + token); - UserInfo ui = null; - if ((ui = client.getUserFromToken(token)) != null) { - // user was authenticated by the masterserver, cache the data - tokenManager.put(token, ui); - return true; - } - } - - return false; - } - - /** - * local function, which gets userdata from the tokenmanager, not the - * masterserver implemented, as there is no need for userdata in each - * function, so return type of authenticated should stay boolean - */ - private UserInfo getUserFromToken(String token) { - UserInfo ui = tokenManager.get(token); - return ui; - } - - public boolean setSessionInvalid(String token) { - log.info("token disabling.. round one"); - log.info(tokenManager.get(token)); - - tokenManager.remove(token); - - log.info("token disabling.. round two"); - log.info(tokenManager.get(token)); - - // check if deletion worked and token isn't stored anymore - return tokenManager.get(token) == null; - } - - @Override - public User getFtpUser(String token) throws TException { - if (authenticated(token)) { - - log.info("returning FTPUser..."); - User user = new User(); - user.setUserName(UUID.randomUUID().toString().substring(0, 8)); - user.setPassword(getEncodedSha1Sum(UUID.randomUUID().toString().substring(0, 8))); - if (Configuration.config.getAbsolute_path().endsWith("/")) { - user.setPath(Configuration.config.getAbsolute_path()); - } else { - user.setPath(Configuration.config.getAbsolute_path() + "/"); - } - - // check if folder temp and folder prod exist - if (folderTempExists() == true && folderProdExists() == true) { - sql.writeFTPUser(user.getUserName(), user.getPassword()); - return user; - } else { - log.info("Error: returning null user"); - return null; - } - } - return null; - - } - - public boolean folderTempExists() { - // check if folder temp exists, otherwise create it - Path path = null; - if (Configuration.config.getAbsolute_path().endsWith("/")) { - path = Paths.get(Configuration.config.getAbsolute_path() + "temp"); - } else { - path = Paths.get(Configuration.config.getAbsolute_path() + "/temp"); - } - - if (Files.exists(path) == true) { - log.info("folder '" + path + "' exists, no further action"); - return true; - } else { - // create directory and set permissions - boolean success = (new File(path + "")).mkdirs(); - - if (!success) { - log.info("failed to create folder '" + path + "'"); - return false; - } else { - // set permissions - try { - Runtime.getRuntime().exec("chmod 777 " + path); - } catch (IOException e) { - e.printStackTrace(); - } - log.info("folder '" + path + "' successfully created"); - return true; - } - } - - }// end folderTempExists() - - public boolean folderProdExists() { - // check if folder temp exists, otherwise create it - Path path = null; - if (Configuration.config.getAbsolute_path().endsWith("/")) { - path = Paths.get(Configuration.config.getAbsolute_path() + "prod"); - } else { - path = Paths.get(Configuration.config.getAbsolute_path() + "/prod"); - } - - if (Files.exists(path) == true) { - log.info("folder '" + path + "' exists, no further action"); - return true; - } else { - // create directory and set permissions - boolean success = (new File(path + "")).mkdirs(); - - if (!success) { - log.info("failed to create folder '" + path + "'"); - return false; - } else { - // set permissions - // TODO: Just no. Check if it's writable and bail out if not, but don't - // blindly try to set permissions when you don't even check if it worked. - try { - Runtime.getRuntime().exec("chmod 777 " + path); - } catch (IOException e) { - e.printStackTrace(); - } - log.info("folder '" + path + "' successfully created"); - return true; - } - } - - }// end folderProdExists() - - public String getEncodedSha1Sum(String key) { + private static final Logger log = Logger.getLogger(ServerHandler.class); + private static final SQL sql = new SQL(); + private static final FileServer fileServer = FileServer.instance(); + + @Override + public String finishImageUpload(String imageName, String description, boolean license, boolean internet, + long shareMode, String os, String uploadToken) throws TException { + ActiveUpload upload = fileServer.getUploadByToken(uploadToken); + if (upload == null) { + log.warn("A client called finishImageUpload, but the given token is unknown"); + throw new TUploadFinishException("Your upload token is invalid"); + } + if (!upload.isComplete()) { + log.warn("A client called finishImageUpload for an upload that is still running"); + throw new TUploadFinishException("Cannot finish upload: Still in progress..."); + } + // We need an owner for the upload to handle it properly + UserInfo user = upload.getOwner(); + if (user == null) { + log.warn("A client called finishImageUpload, the uploadToken was valid, but the upload doesn't have an owner"); + throw new TUploadFinishException("Your upload doesn't have an owner. (This should not happen!)"); + } + // We also need a temp file + File file = upload.getDestinationFile(); + if (file == null || !file.getName().endsWith(Constants.INCOMPLETE_UPLOAD_SUFFIX)) { + log.warn("A client called finishImageUpload, but there is no temp file involved or it has the wrong extension (" + + file + ")"); + throw new TUploadFinishException("Your upload doesn't have a matching temp file on the server."); + } + + // Ready to go. First step: Rename temp file to something usable + File destination = new File(file.getParent(), Formatter.vmName(user, imageName)); + // Sanity check: destination should be a sub directory of the vmStorePath + String relPath = FileSystem.getRelativePath(destination, Configuration.getVmStoreBasePath()); + if (relPath == null) { + log.warn(destination.getAbsolutePath() + " is not a subdir of " + + Configuration.getVmStoreBasePath().getAbsolutePath()); + throw new TUploadFinishException( + "Your file lies outside of the vm store directory (This is a server side issue)."); + } + // Execute rename + boolean ret = false; + Exception renameException = null; try { - MessageDigest md = MessageDigest.getInstance("SHA1"); - md.update(key.getBytes()); - log.info("successfully returned EncodedSha1Sum"); // How do you know? You didn't return anything yet - return new BigInteger(1, md.digest()).toString(16); - } catch (NoSuchAlgorithmException e) { - // handle error case to taste + ret = file.renameTo(destination); + } catch (Exception e) { + ret = false; + renameException = e; } - return null; - } - - @Override - public long DeleteFtpUser(String user, String token) throws TException { - if (authenticated(token)) { - return sql.DeleteUser(user); + if (!ret) { + // Rename failed :-( + log.warn("Could not rename '" + file.getAbsolutePath() + "' to '" + destination.getAbsolutePath() + + "'", renameException); } - return -1; - } - @Override - public String getPathOfImage(String image_id, String version, String token) throws TException { - if (authenticated(token)) { - log.info("successfully returned PathOfImage: " + sql.getPathOfImage(image_id, version)); - - return sql.getPathOfImage(image_id, version); - } - return null; - } + // Now insert meta data into DB - @Override - public String setInstitution(String university, String token) throws TException { - if (authenticated(token)) { - // TODO: wat. Institutions are defined globally on the master server, including their ID - return sql.setInstitution(university); + final String imageUuid = UUID.randomUUID().toString(); + final String mode; + if (shareMode == 0) { + mode = "only_local"; + } else { + mode = "to_be_published"; } - return null; - } - - @Override - public boolean writeVLdata(String imagename, String desc, String Tel, String Fak, boolean license, - boolean internet, long ram, long cpu, String imagePath, boolean isTemplate, long filesize, - long shareMode, String os, String uid, String token, String userID) throws TException { - - if (authenticated(token)) { - String mode = null; - - if (shareMode == 0) { - mode = "only_local"; - } else { - mode = "to_be_published"; - } - // OS impl Select and write - // ACHTUNG: Anzahl der Leerzeichen muss eingehalten werden: - // 'Windows 7 32 bit" - // TODO: Might be the biggest mess around here. We should define OS types on the - // master server in the future and have them synced to the satellite. - String pk_os = sql.getOSpk(os.substring(0, nthIndexOf(os, " ", 2)), - os.substring(nthIndexOf(os, " ", 2), os.lastIndexOf(" ")).replace(" ", "")); + // OS impl Select and write + // ACHTUNG: Anzahl der Leerzeichen muss eingehalten werden: + // 'Windows 7 32 bit" + // TODO: Might be the biggest mess around here. We should define OS types on the + // master server in the future and have them synced to the satellite. + String pk_os = sql.getOSpk(os.substring(0, nthIndexOf(os, " ", 2)), + os.substring(nthIndexOf(os, " ", 2), os.lastIndexOf(" ")).replace(" ", "")); - sql.setImageData(userID, license, internet, cpu, ram, imagename, desc, imagePath, filesize, mode, - pk_os, uid); + ret = sql.writeNewImageData(user.userId, license, internet, imageName, description, relPath, + upload.getSize(), mode, pk_os, imageUuid); + if (!ret) + throw new TUploadFinishException( + "Image uploaded successfully, but could not be inserted into data base."); - log.info("userID in serverhandler was: " + userID); + return imageUuid; - log.info("written VLdata"); - return true; - } - return false; } @Override // @param: userID - deprecated, to be removed while setting up new suite-architecture public List getImageListPermissionWrite(String userID, String token) throws TException { - if (authenticated(token)) { - UserInfo ui = getUserFromToken(token); + UserInfo ui = SessionManager.get(token); + if (ui != null) { return sql.getImageListPermissionWrite(ui.getUserId()); } return null; @@ -265,8 +130,8 @@ public class ServerHandler implements Server.Iface { @Override // @param: userID - deprecated, to be removed while setting up new suite-architecture public List getImageListPermissionRead(String userID, String token) throws TException { - if (authenticated(token)) { - UserInfo ui = getUserFromToken(token); + UserInfo ui = SessionManager.get(token); + if (ui != null) { return sql.getImageListPermissionRead(ui.getUserId()); } return null; @@ -275,8 +140,8 @@ public class ServerHandler implements Server.Iface { @Override // @param: userID - deprecated, to be removed while setting up new suite-architecture public List getImageListPermissionLink(String userID, String token) throws TException { - if (authenticated(token)) { - UserInfo ui = getUserFromToken(token); + UserInfo ui = SessionManager.get(token); + if (ui != null) { return sql.getImageListPermissionLink(ui.getUserId()); } return null; @@ -285,8 +150,8 @@ public class ServerHandler implements Server.Iface { @Override // @param: userID - deprecated, to be removed while setting up new suite-architecture public List getImageListPermissionAdmin(String userID, String token) throws TException { - if (authenticated(token)) { - UserInfo ui = getUserFromToken(token); + UserInfo ui = SessionManager.get(token); + if (ui != null) { return sql.getImageListPermissionAdmin(ui.getUserId()); } return null; @@ -294,7 +159,8 @@ public class ServerHandler implements Server.Iface { @Override public List getImageListAllTemplates(String token) throws TException { - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { return sql.getImageListAllTemplates(); } return null; @@ -302,7 +168,8 @@ public class ServerHandler implements Server.Iface { @Override public List getAllOS(String token) throws TException { - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { return sql.getAllOS(); } return null; @@ -318,12 +185,11 @@ public class ServerHandler implements Server.Iface { @Override public Map getPersonData(String Vorname, String Nachname, String token) throws TException { - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { Map map = new HashMap<>(); - UserInfo ui = getUserFromToken(token); - map.put("mail", ui.getEMail()); map.put("Nachname", ui.getLastName()); map.put("Vorname", ui.getFirstName()); @@ -337,10 +203,11 @@ public class ServerHandler implements Server.Iface { return null; } + @Override public void setPerson(String userID, String token, String institution) throws TException { // TODO: Again, what's going on with institution as a parameter here? It's part of the UserInfo... - if (authenticated(token)) { - UserInfo ui = getUserFromToken(token); + UserInfo ui = SessionManager.get(token); + if (ui != null) { sql.setPerson(userID, ui.getLastName(), ui.getFirstName(), ui.getEMail(), new Date(), institution); } } @@ -349,9 +216,9 @@ public class ServerHandler implements Server.Iface { public boolean writeLecturedata(String name, String shortdesc, String desc, String startDate, String endDate, boolean isActive, String imageID, String token, String Tel, String Fak, String lectureID, String university) throws TException { - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { // TODO: Check if the user has the permissions to set this lecture's meta data... - UserInfo ui = getUserFromToken(token); Map map = new HashMap(); int imageversion = 0; @@ -371,77 +238,35 @@ public class ServerHandler implements Server.Iface { } - @Override - public boolean startFileCopy(String filename, String token) throws TException { - if (authenticated(token)) { - // copy file from folder temp to folder prod - String file = Configuration.config.getAbsolute_path() + "temp/" + filename; - File tmpFile = new File(file); - - log.info("Trying to move file to '/srv/openslx/nfs/prod/" + tmpFile.getName() + "'"); - try { - FileUtils.moveFile(tmpFile, new File(Configuration.config.getAbsolute_path() + "prod/" - + filename)); - // int ret = sql.UpdateImagePath(filename); - if (sql.UpdateImagePath(filename) == 0) { - log.info("file moved and database updated."); - } - - } catch (IOException e) { - log.info("Failed to move file."); - e.printStackTrace(); - } - } - return true; - } - @Override public Map getImageData(String imageid, String imageversion, String token) throws TException { - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { return sql.getImageData(imageid, imageversion); } return null; } @Override - public boolean updateImageData(String name, String newName, String desc, String image_path, - boolean license, boolean internet, long ram, long cpu, String id, String version, - boolean isTemplate, long filesize, long shareMode, String os, String token) throws TException { - - if (authenticated(token)) { - - // get old_image_path - String old_image_path = sql.getFile(id, version); - - String mode = null; - + public boolean updateImageData(String userToken, String imageId, String newName, String desc, + boolean license, boolean internet, long shareMode, String os) throws TException { + UserInfo ui = SessionManager.get(userToken); + if (ui != null) { + final String mode; if (shareMode == 0) { mode = "only_local"; } else { mode = "to_be_published"; } + String pk_os = sql.getOSpk(os.substring(0, nthIndexOf(os, " ", 2)), os.substring(nthIndexOf(os, " ", 2), os.lastIndexOf(" ")).replace(" ", "")); // do database update - if successful then delete old file from // drive - int val = sql.UpdateImageData(name, newName, desc, image_path, license, internet, cpu, ram, id, - version, isTemplate, filesize, mode, pk_os); - - // check if new file has been uploaded by checking if the new file - // path equals the old file path - // if so, no new file was uploaded. Else delete old file - if (val == 0 && (!old_image_path.substring(5).matches(image_path.substring(5)))) { - // update was successful - delete old file - // log.debug("deleting file "+old_image_path); - deleteImageByPath(old_image_path); - } else { - // update was not successful - delete new file - // TODO not yet implemented - // log.debug("doing nothing because no new file was uploaded.."); + return sql.updateImageData(newName, desc, license, internet, imageId, mode, pk_os); - } } return false; } @@ -457,8 +282,8 @@ public class ServerHandler implements Server.Iface { @Override public List getLectureListPermissionRead(String token) throws TException { - if (authenticated(token)) { - UserInfo ui = getUserFromToken(token); + UserInfo ui = SessionManager.get(token); + if (ui != null) { // log.info("returning LectureListRead"); return sql.getLectureListPermissionRead(ui.getUserId()); } @@ -467,8 +292,8 @@ public class ServerHandler implements Server.Iface { @Override public List getLectureListPermissionWrite(String token) throws TException { - if (authenticated(token)) { - UserInfo ui = getUserFromToken(token); + UserInfo ui = SessionManager.get(token); + if (ui != null) { // log.info("returning LectureListWrite"); return sql.getLectureListPermissionWrite(ui.getUserId()); } @@ -477,8 +302,8 @@ public class ServerHandler implements Server.Iface { @Override public List getLectureListPermissionAdmin(String token) throws TException { - if (authenticated(token)) { - UserInfo ui = getUserFromToken(token); + UserInfo ui = SessionManager.get(token); + if (ui != null) { // log.info("returning LectureListAdmin"); return sql.getLectureListPermissionAdmin(ui.getUserId()); } @@ -489,8 +314,8 @@ public class ServerHandler implements Server.Iface { public boolean updateLecturedata(String name, String newName, String shortdesc, String desc, String startDate, String endDate, boolean isActive, String imageid, String imageversion, String token, String Tel, String Fak, String id, String university) throws TException { - if (authenticated(token)) { - UserInfo ui = getUserFromToken(token); + UserInfo ui = SessionManager.get(token); + if (ui != null) { sql.updateLectureData(imageid, imageversion, ui.getLastName(), newName, desc, shortdesc, startDate, endDate, isActive, id); @@ -500,79 +325,59 @@ public class ServerHandler implements Server.Iface { } @Override - public boolean deleteImageServer(String imageid, String imageversion, String token) throws TException { - if (authenticated(token)) { - // TODO: Has user permissions to delete this file? - String stringFile = sql.getFile(imageid, imageversion); - log.info("File to Delete: " + stringFile); - - File tmpFile = new File(Configuration.config.getAbsolute_path() + stringFile); - - log.info("Absolute Path used for deletion: " + tmpFile); - - try { - // File wird von Server gelöscht - FileUtils.forceDelete(tmpFile); - return true; + public boolean deleteImage(String imageId, String imageVersion, String token) throws TException { + UserInfo ui = SessionManager.get(token); + if (ui == null) + return false; - } catch (IOException e) { - log.info("Failed to execute deleteImageServer."); - e.printStackTrace(); + // TODO: Has user permissions to delete this file? + String stringFile = sql.getFile(imageId, imageVersion); + if (stringFile == null) + return false; - } - } - return false; - } - - @Override - public boolean deleteImageData(String id, String version, String token) throws TException { - boolean success = false; + log.info("File to Delete: " + stringFile); - if (authenticated(token)) { - if (sql.deleteImage(id, version) == true) { - success = true; - log.info("Image '" + id + "' and permissions successfully deleted."); - } + if (sql.deleteImage(imageId, imageVersion)) { + log.info("Image '" + imageId + "' and permissions successfully deleted."); } - return success; - } - - // TODO: ... I can write a small java app that calls this function to delete random files anywhere on the sat - // If this function is not really required for some obscure reason then it should be removed - public boolean deleteImageByPath(String image_path) throws TException { - log.info("File to Delete: " + image_path); - - File tmpFile = new File(Configuration.config.getAbsolute_path() + image_path); + File tmpFile = new File(Configuration.getVmStoreBasePath(), stringFile); try { - // File wird von Server gelöscht - FileUtils.forceDelete(tmpFile); - return true; - - } catch (IOException e) { - log.info("Failed to execute deleteImageServer."); - e.printStackTrace(); - + log.info("Absolute Path used for deletion: " + tmpFile.getCanonicalPath()); + } catch (IOException e1) { } - return false; + if (tmpFile.isFile()) { + log.warn(".... file does not exist!"); + } else { + try { + // File wird von Server gelöscht + FileUtils.forceDelete(tmpFile); + } catch (IOException e) { + log.info("Failed to execute deleteImage.", e); + } + } + return true; } @Override public boolean connectedToLecture(String id, String version, String token) throws TException { - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { // TODO: Permissions return sql.connectedToLecture(id, version); } return true; } - public boolean deleteLecture(String id, String token, String university) throws TException { + @Override + public boolean deleteLecture(String id, String token) throws TException { boolean success = false; - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { // TODO: Permissions if (sql.deleteLecture(id) == true) { @@ -586,7 +391,8 @@ public class ServerHandler implements Server.Iface { @Override public List getAllUniversities(String token) throws TException { - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { // TODO: Sync with list from master server (.getOrganizations() - call every now and then and add to local DB) return sql.getAllUniversities(); } @@ -595,7 +401,8 @@ public class ServerHandler implements Server.Iface { @Override public Map getLectureData(String lectureid, String token) throws TException { - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { return sql.getLectureData(lectureid); } return null; @@ -616,7 +423,8 @@ public class ServerHandler implements Server.Iface { @Override public boolean checkUser(String username, String token) throws TException { - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { return sql.checkUser(username); } return false; @@ -625,9 +433,9 @@ public class ServerHandler implements Server.Iface { @Override public boolean createUser(String token, String university) throws TException { - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { // TODO: Do not use university param... - UserInfo ui = getUserFromToken(token); String pk_institution = sql.setInstitution(university); sql.setPerson(ui.getEMail(), ui.getLastName(), ui.getFirstName(), ui.getEMail(), new Date(), pk_institution); @@ -639,8 +447,8 @@ public class ServerHandler implements Server.Iface { @Override public boolean writeImageRights(String imageID, String token, String role, String university, String userID) throws TException { - if (authenticated(token)) { - UserInfo ui = getUserFromToken(token); + UserInfo ui = SessionManager.get(token); + if (ui != null) { String pk_image = null; Map map = new HashMap(); @@ -692,9 +500,8 @@ public class ServerHandler implements Server.Iface { @Override public boolean writeLectureRights(String lectureID, String role, String token, String university, String userID) throws TException { - if (authenticated(token)) { - // String pk_lecture = null; - UserInfo ui = getUserFromToken(token); + UserInfo ui = SessionManager.get(token); + if (ui != null) { String pk_institution = sql.setInstitution(university); String pk_person = sql.setPerson(userID, ui.getLastName(), ui.getFirstName(), ui.getEMail(), new Date(), pk_institution); @@ -735,7 +542,8 @@ public class ServerHandler implements Server.Iface { @Override public List getAllOtherSatelliteUsers(List userID, String token) throws TException { // TODO: Like we couldn't filter the current user on the client side... - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { return sql.getAllOtherSatelliteUsers(userID); // return null; } @@ -743,19 +551,23 @@ public class ServerHandler implements Server.Iface { } // set permissions for users which are !=userID + @Override public boolean writeAdditionalImageRights(String imageID, String userID, boolean isRead, boolean isWrite, boolean isLinkAllowed, boolean isAdmin, String token) throws TException { boolean success = false; - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { sql.writeAdditionalImageRights(imageID, userID, isRead, isWrite, isLinkAllowed, isAdmin); log.info("Written additional image rights for " + userID); } return success; } + @Override public boolean writeAdditionalLectureRights(String lectureID, String userID, boolean isRead, boolean isWrite, boolean isAdmin, String token) throws TException { - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { sql.writeAdditionalLectureRights(lectureID, userID, isRead, isWrite, isAdmin); log.info("Written additional lecture rights for " + userID); @@ -767,15 +579,18 @@ public class ServerHandler implements Server.Iface { @Override public List getPermissionForUserAndImage(String token, String imageID, String userID) throws TException { - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { return sql.getPermissionForUserAndImage(userID, imageID); } return null; } + @Override public List getPermissionForUserAndLecture(String token, String lectureID, String userID) throws TException { - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { return sql.getPermissionForUserAndLecture(userID, lectureID); } return null; @@ -784,7 +599,8 @@ public class ServerHandler implements Server.Iface { @Override public void deleteAllAdditionalImagePermissions(String imageID, String token, String userID) throws TException { - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { sql.deleteAllAdditionalImagePermissions(imageID, userID); } return; @@ -793,7 +609,8 @@ public class ServerHandler implements Server.Iface { @Override public void deleteAllAdditionalLecturePermissions(String lectureID, String token, String userID) throws TException { - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { sql.deleteAllAdditionalLecturePermissions(lectureID, userID); } @@ -802,7 +619,8 @@ public class ServerHandler implements Server.Iface { @Override public List getImageList(String userID, String token) throws TException { - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { return sql.getImageList(userID); } return null; @@ -810,7 +628,8 @@ public class ServerHandler implements Server.Iface { @Override public List getAdditionalImageContacts(String imageID, String token) throws TException { - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { return sql.getAdditionalImageContacts(imageID); } return null; @@ -818,22 +637,17 @@ public class ServerHandler implements Server.Iface { @Override public String getOsNameForGuestOs(String guestOS, String token) throws TException { - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { return sql.getOsNameForGuestOs(guestOS); } return null; } @Override - public String createRandomUUID(String token) throws TException { - if (authenticated(token)) { - return sql.createRandomUUID(); - } - return null; - } - public Map getItemOwner(String itemID, String token) throws TException { - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { return sql.getItemOwner(itemID); } return null; @@ -842,8 +656,8 @@ public class ServerHandler implements Server.Iface { @Override public boolean userIsImageAdmin(String imageID, String token, String userID) throws TException { - - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { return sql.userIsImageAdmin(userID, imageID); } return false; @@ -852,8 +666,8 @@ public class ServerHandler implements Server.Iface { @Override public boolean userIsLectureAdmin(String userID, String lectureID, String token) throws TException { - - if (authenticated(token)) { + UserInfo ui = SessionManager.get(token); + if (ui != null) { return sql.userIsLectureAdmin(userID, lectureID); } @@ -863,7 +677,7 @@ public class ServerHandler implements Server.Iface { @Override public String getInstitutionByID(String institutionID) throws TException { // TODO Auto-generated method stub - return null; + return "-institution-"; } @Override @@ -871,4 +685,59 @@ public class ServerHandler implements Server.Iface { return Version.VERSION; } + @Override + public TransferInformation requestUpload(String userToken, long fileSize, List blockHashes) + throws TException { + UserInfo ui = SessionManager.get(userToken); + if (ui == null) + return null; + + String transferToken; + try { + transferToken = fileServer.createNewUserUpload(ui, fileSize, blockHashes); + } catch (Exception e) { + log.warn("Cannot accept upload request from user " + Formatter.userFullName(ui), e); + if (e instanceof TException) + throw (TException) e; + throw new TUploadRejectedException(e.getMessage()); + } + return new TransferInformation(transferToken, fileServer.getPlainPort(), fileServer.getSslPort()); + } + + @Override + public void cancelUpload(String uploadToken) throws TException { + // TODO Auto-generated method stub + + } + + @Override + public TransferInformation requestDownload(String userToken, String imageId) throws TException { + // TODO Auto-generated method stub + return null; + } + + @Override + public void cancelDownload(String downloadToken) throws TException { + // TODO Auto-generated method stub + + } + + @Override + public boolean updateImageFile(String uploadToken, String imageId) throws TException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean authenticated(String token) throws TException { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean setSessionInvalid(String token) throws TException { + // TODO Auto-generated method stub + return false; + } + }// end class diff --git a/dozentenmodulserver/src/main/java/server/SessionManager.java b/dozentenmodulserver/src/main/java/server/SessionManager.java new file mode 100644 index 00000000..75336de0 --- /dev/null +++ b/dozentenmodulserver/src/main/java/server/SessionManager.java @@ -0,0 +1,84 @@ +package server; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; + +import org.apache.log4j.Logger; +import org.openslx.imagemaster.thrift.iface.UserInfo; +import org.openslx.thrifthelper.ThriftManager; + +/** + * Manages user sessions. Mainly used to map tokens to users. + * + */ +public class SessionManager { + + private static final Logger LOGGER = Logger.getLogger(SessionManager.class); + + private static class Entry { + private static final long SESSION_TIMEOUT = TimeUnit.DAYS.toMillis(1); + private final UserInfo user; + private long validUntil; + + private Entry(UserInfo user) { + this.user = user; + this.validUntil = System.currentTimeMillis() + SESSION_TIMEOUT; + } + + public void touch(long now) { + this.validUntil = now + SESSION_TIMEOUT; + } + } + + // saves the current tokens and the mapped userdata, returning from the server + private static Map tokenManager = new ConcurrentHashMap<>(); + + /** + * Get the user corresponding to the given token. Returns null if the token + * is not known, or the session already timed out. + * + * @param token + * user's token + * @return UserInfo for the matching user + */ + public static UserInfo get(String token) { + Entry e = tokenManager.get(token); + if (e != null) { + // User session already cached + final long now = System.currentTimeMillis(); + if (e.validUntil < now) { + tokenManager.remove(token); + return getRemote(token); + } + e.touch(now); + return e.user; + } + return getRemote(token); + } + + /** + * Remove session matching the given token + * + * @param token + */ + public static void remove(String token) { + tokenManager.remove(token); + } + + private static UserInfo getRemote(String token) { + UserInfo ui = null; + try { + ui = ThriftManager.getMasterClient().getUserFromToken(token); + } catch (Exception e) { + LOGGER.warn("Could not reach master server to query for user token of a client!", e); + } + if (ui == null) + return null; + tokenManager.put(token, new Entry(ui)); + return ui; + } + + // TODO: Clean map of old entries periodically + +} diff --git a/dozentenmodulserver/src/main/java/server/StartServer.java b/dozentenmodulserver/src/main/java/server/StartServer.java index 04314ee7..a5631622 100644 --- a/dozentenmodulserver/src/main/java/server/StartServer.java +++ b/dozentenmodulserver/src/main/java/server/StartServer.java @@ -1,59 +1,50 @@ package server; -import java.io.File; -import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; + import models.Configuration; + import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; -import org.ini4j.InvalidFileFormatException; -import org.ini4j.Wini; -import server.BinaryListener; +import fileserv.FileServer; public class StartServer { - /** - * @param args - */ - private static Logger log = Logger.getLogger(StartServer.class); private static List servers = new ArrayList<>(); public static void main(String[] args) { - //get going and show basic information in logfile BasicConfigurator.configure(); - log.info("*************************************************************************************************"); - log.info("******************* " + new Date() + " - starting Application ***********************"); - log.info("*************************************************************************************************"); + log.info("****************************************************************"); + log.info("******************* starting Application ***********************"); + log.info("****************************************************************"); // get Configuration try { - log.info(new Date() + " - Getting config from .ini-file"); - Wini ini = new Wini(new File("Server_Config.ini")); - Configuration.config.setAbsolute_path(ini.get("ftp", - "path_absolute")); - Configuration.config - .setSql_connection(ini.get("sql", "connection")); - Configuration.config.setSql_pass(ini.get("sql", "pass")); - Configuration.config.setSql_user(ini.get("sql", "user")); - } catch (InvalidFileFormatException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); - } catch (IOException e1) { - // TODO Auto-generated catch block - e1.printStackTrace(); + log.info("Loading configuration"); + Configuration.load(); + } catch (Exception e1) { + log.fatal("Could not load configuration", e1); + System.exit(1); + } + + // Start file transfer server + if (!FileServer.instance().start()) { + log.error("Could not start internal file server."); + return; } // Start Server Thread t; t = new Thread(new BinaryListener()); servers.add(t); t.start(); + // Wait for servers for (Thread wait : servers) { boolean success = false; while (!success) { -- cgit v1.2.3-55-g7522