Advertisement
Guest User

Untitled

a guest
Oct 10th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.16 KB | None | 0 0
  1. import socket
  2. import sys
  3. import datetime
  4. import time
  5. import os
  6.  
  7.  
  8. CS_IP = socket.gethostbyname("lab8p3")
  9. CS_PORT = 58002
  10. MY_PORT = 59000
  11. MyIP=[l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2]
  12.         if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)),
  13.         s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET,
  14.         socket.SOCK_DGRAM)]][0][1]]) if l][0][0]
  15.  
  16. #------------------------------------
  17. #|     INIT                         |
  18. #------------------------------------
  19. for i in range(0,len(sys.argv)-1):
  20.     if sys.argv[i] == "-n":
  21.         CS_IP = socket.gethostbyname(sys.argv[i+1])
  22.     if sys.argv[i] == "-p":
  23.         CS_PORT = int(sys.argv[i+1])
  24.     if sys.argv[i] == "-b":
  25.         MY_PORT = int(sys.argv[i+1])
  26.  
  27.  
  28. s_udp = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
  29. s_udp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  30. s_udp.bind(("", MY_PORT))
  31.  
  32. f = open("user_reg.txt","w")
  33. f.close()
  34.  
  35. #---------------------------------------------------------
  36. #                      USER DATABASE
  37. #---------------------------------------------------------
  38. def create_user(user,password):
  39.     f = open("user_reg.txt","a")
  40.     f.write(user+"|"+password+"\n")
  41.     f.close()
  42.  
  43. def check_user(user,password):
  44.     f = open("user_reg.txt","r")
  45.     for line in f:
  46.         if line.split("|")[0] == user:
  47.             f.close()
  48.             return "NOK"
  49.     f.close()
  50.     return "OK"
  51.  
  52. def del_user(user):
  53.     f = open("user_reg.txt","r")
  54.     lines = f.readlines()
  55.     f.close()
  56.     f = open("user_reg.txt","w")
  57.     for line in lines:
  58.         if line.split("|")[0] != user:
  59.             f.write(line)
  60.     f.close()
  61.  
  62. #---------------------------------------------------------
  63. #             Interface de Envio de Mensagens: UDP
  64. #---------------------------------------------------------
  65. def send_udp(message):
  66.     print datetime.datetime.now().strftime("[%H:%M:%S.%f")+"]UDP: Sending "+message+" to "+CS_IP+":",CS_PORT
  67.     message.encode()
  68.     s_udp.sendto(message, (CS_IP,CS_PORT))
  69.  
  70.  
  71.  
  72.  
  73. def receive_udp():
  74.     data, addr = s_udp.recvfrom(1024)
  75.     print datetime.datetime.now().strftime("[%H:%M:%S.%f")+"]UDP: Received "+ data+" from ",addr
  76.  
  77.     data.decode()
  78.     return data
  79.  
  80. #---------------------------------------------------------
  81. #             Interface de Envio de Mensagens: TCP
  82. #---------------------------------------------------------
  83. def receive_tcp(conn, addr):
  84.     print datetime.datetime.now().strftime("[%H:%M:%S.%f")+']TCP: Connection address:', addr
  85.     data = conn.recv(BUFFER_SIZE)
  86.     data.decode()
  87.     print datetime.datetime.now().strftime("[%H:%M:%S.%f")+"]TCP: Received "+ data+" from ",addr
  88.     return data
  89.  
  90. def send_tcp(message, conn, addr):
  91.     print datetime.datetime.now().strftime("[%H:%M:%S.%f")+"]TCP: Sending "+message+" to ",addr
  92.     message.encode()
  93.     conn.send(message)
  94.  
  95. #---------------------------------------------------------
  96. #                           REG
  97. #---------------------------------------------------------
  98.  
  99. def init(attempts):
  100.     s_udp.settimeout(5)
  101.     try:
  102.         attempts += 1
  103.         send_udp(reg_CS(MyIP,MY_PORT))
  104.         if(receive_udp() == "RGR NOK\n" and attempts < 5):
  105.             time.sleep(5)
  106.             init(attempts)
  107.         elif attempts == 5:
  108.             print "Maximum attempts reached."
  109.             sys.exit(1)
  110.         else:
  111.             s_udp.settimeout(None)
  112.  
  113.     except socket.timeout as e:
  114.         init(attempts)
  115.  
  116. def reg_CS(ip,port):
  117.     return "REG "+ip+" "+str(port)
  118.  
  119. #---------------------------------------------------------
  120. #                           UNR
  121. #---------------------------------------------------------
  122.  
  123.  
  124. def unr_CS(ip,port):
  125.     return"UNR "+ip+" "+str(port)
  126. #---------------------------------------------------------
  127. #                           createFile/Dir
  128. #---------------------------------------------------------
  129. def createDir(dir):
  130.     if not os.path.isdir(os.getcwd()+"/"+dir):
  131.         os.mkdir(dir)
  132.  
  133. def createFile(file,dir):
  134.     f = open(dir+"/"+file.getName(), "w")
  135.     f.write(file.getData())
  136.     f.close()
  137. #---------------------------------------------------------
  138. #                           UPR
  139. #---------------------------------------------------------
  140.  
  141. class File:
  142.     def __init__(self, name, date, time, size, data):
  143.         self.name = name
  144.         self.datetime = datetime.datetime(int(date.split(".")[2]),int(date.split(".")[1]),int(date.split(".")[0]),int(time.split(":")[0]),int(time.split(":")[1]),int(time.split(":")[2]))
  145.         self.size=int(size)
  146.  
  147.     def __str__(self):
  148.         return "{0:s} {1:02d}.{2:02d}.{3:04d} {4:02d}.{5:02d}.{6:02d} {7:d}".format(self.name, self.datetime.day, self.datetime.month, self.datetime.year, self.datetime.hour, self.datetime.minute, self.datetime.second, self.size)
  149.  
  150.  
  151. def read_file(string):
  152.     #print "name is "+string.split(" ")[0]+" ,"
  153.     name = string.split(" ")[0]
  154.     #print "date is "+string.split(" ")[1]+" ,"
  155.     date = string.split(" ")[1]
  156.     #print "time is "+string.split(" ")[2]+" ,"
  157.     time = string.split(" ")[2]
  158.     #print "size is "+string.split(" ")[3]+" ,"
  159.     size = string.split(" ")[3]
  160.     data_index = len(name) + 1 + len(date) + 1 + len(time) + 1 + len(size) + 1
  161.     size = int(size)
  162.     data = string[data_index:data_index+size]
  163.     #print "data is "+data+" ,"
  164.     file = File(name,date,time,size,data)
  165.     #print "Remaining:"+string[data_index+size+1:]
  166.     return file, string[data_index+size+1:]
  167.  
  168. def command_parser(command,stage):
  169.     if stage == "init" and command[:4] == "UPL ":
  170.         return command_parser(command[4:],"dir")
  171.     elif stage == "dir":
  172.         dir = command.split(" ")[0]
  173.         return command_parser(command[len(dir)+1:], "nFiles"), dir
  174.     elif stage == "nFiles":
  175.         try:
  176.             files=[]
  177.             n = int(command.split(" ")[0])
  178.             file_string = command[len(command.split(" ")[0])+1:]
  179.             for i in range(0,n):
  180.                 myfile , file_string = read_file(file_string)
  181.                 files.append(myfile)
  182.             return files
  183.         except ValueError:
  184.             return "UPR ERR\n"
  185.     else:
  186.         return "UPR ERR\n"
  187.  
  188. def UPR(stri, user):
  189.     try:
  190.         files, dir = command_parser(stri,"init")
  191.         createDir(user)
  192.         createDir(user + "/" + dir)
  193.         for file in files:
  194.             createFile(file, user + "/" + dir)
  195.         return "UPR OK\n"
  196.     except IOError, ValueError:
  197.         return "UPR NOK\n"
  198. #---------------------------------------------------------
  199. #                           RBR
  200. #---------------------------------------------------------
  201. #TODO
  202. #falta o err
  203. def RBR(stri, user):
  204.     dir_path = os.getcwd()+"/"+user+"/"+dir
  205.     files = ""
  206.     N = 0;
  207.     try:
  208.         for filename in os.listdir(dir_path):
  209.             if os.path.isfile(dir_path+"/"+filename):
  210.  
  211.                 mtime = time.gmtime(os.path.getmtime(dir_path+"/"+filename))
  212.  
  213.                 f = open(dir_path + "/" + filename, "r")
  214.                 data = f.read()
  215.                 f.close()
  216.  
  217.                 files = files + " " + filename + " " + "{0:02d}.{1:02d}.{2:04d} {3:02d}:{4:02d}:{5:02d}".format(mtime.tm_mday, mtime.tm_mon,
  218.                 mtime.tm_year, mtime.tm_hour, mtime.tm_min, mtime.tm_sec)+ " "+ str(int(os.stat(dir_path+"/"+filename).st_size)) + " " + data
  219.                 N += 1
  220.         files = files[1:]
  221.  
  222.         print "RBR " + " " + str(N) + " " + files + "\n"
  223.         send("RBR " + " " + str(N) + " " + files + "\n")
  224.     except:
  225.         send("RBR EOF\n")
  226.  
  227. #---------------------------------------------------------
  228. #                           AUR
  229. #---------------------------------------------------------
  230.  
  231. def user_aut(user,password): #Autenticacao de users
  232.     if check_user(user,password)=="OK":
  233.         return "AUR OK\n"
  234.     else:
  235.         return "AUR NOK\n"
  236.  
  237. #---------------------------------------------------------
  238. #                           LUR
  239. #---------------------------------------------------------
  240.  
  241. def user_reg(user,password): #Registo de users
  242.     check = check_user(user,password)
  243.     print "[DEBUG]"+check
  244.     if check == "OK":
  245.         create_user(user,password)
  246.         return "LUR OK\n"
  247.     elif check =="NOK":
  248.         return "LUR NOK\n"
  249.     else:
  250.         return "LUR ERR\n"
  251.  
  252. #---------------------------------------------------------
  253. #                           DLB ------------------------------------------------------------ TO TEST
  254. #---------------------------------------------------------
  255. def delete_dir(user,dir):
  256.     work_dir=os.getcwd()
  257.  
  258.     if os.path.isdir(work_dir+"/"+user+"/"+dir):
  259.         if len(os.dirlist())==1:
  260.             os.rmdir(dir)
  261.             os.rmdir(work_dir+"/"+user)
  262.             return "DBR OK\n"
  263.         else:
  264.             os.rmdir(dir)
  265.             return "DBR OK\n"
  266.     else:
  267.         return "DBR NOK\n"
  268.  
  269. #---------------------------------------------------------
  270. #                           UNR
  271. #---------------------------------------------------------
  272. def unr_CS(ip,port):
  273.     return"UNR "+ip+" "+str(port)
  274.  
  275.  
  276. #---------------------------------------------------------
  277. #                       Directories
  278. #---------------------------------------------------------
  279.  
  280. def createDir(dir):
  281.     if not os.path.isdir(os.getcwd()+"/"+dir):
  282.         os.mkdir(dir)
  283.  
  284. #---------------------------------------------------------
  285. #                       CHILD
  286. #---------------------------------------------------------
  287. def child():
  288.     s_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  289.     s_tcp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  290.     s_tcp.bind(("", MY_PORT))
  291.     s_tcp.listen(1)
  292.  
  293.     while True:
  294.         conn , addr = s_tcp.accept()
  295.  
  296.         receipt = receive_tcp(conn, addr)
  297.  
  298.         if receipt.split(" ")[0]=="AUT":
  299.             user= receipt.split(" ")[1]
  300.             password=receipt.split(" ")[2]
  301.             AUR = user_aut(user,password)
  302.             send_tcp(AUR, conn, addr)
  303.             if AUR == "AUR OK\n":
  304.                 receipt = receive_tcp(conn, addr)
  305.                 if receipt.split(" ")[0] == "UPL":
  306.                     send_tcp(UPR(receipt,user), conn, addr)
  307.                 elif receipt.split(" ")[0] == "RSB":
  308.                     send_tcp(RBR(receipt.split(" ")[1],user), conn, addr)
  309.  
  310. #---------------------------------------------------------
  311. #                          main
  312. #---------------------------------------------------------
  313.  
  314. try:
  315.  
  316.     init(0)
  317.  
  318.     pid = os.fork()
  319.  
  320.     if pid==0:
  321.         child()
  322.  
  323.     while True:
  324.  
  325.         command=receive_udp()
  326.         print command
  327.  
  328.         if command.split(" ")[0]=="AUT":
  329.             user= command.split(" ")[1]
  330.             password=command.split(" ")[2]
  331.             send(user_aut(user,password))
  332.         elif command.split(" ")[0]=="LSU":
  333.             user= command.split(" ")[1]
  334.             password=command.split(" ")[2]
  335.             send_udp(user_reg(user,password))
  336.         elif command.split(" ")[0]=="DLB":
  337.             user=command.split(" ")[1]
  338.             dir=command.split(" ")[2]
  339.             send_udp(delete_dir(user,dir))
  340.  
  341.         else:
  342.             send("ERROR")
  343. except KeyboardInterrupt: #CTRL+C Interrupt
  344.     send_udp(unr_CS(MyIP,MY_PORT))
  345.     sys.exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement