Пример #1
0
def sendBU(sBU, user, filename, filesize, filedata):
    #Identification phase
    message = "{}{}\r\n".format(szasar.Command.User, user)
    sBU.sendall(message.encode("ascii"))
    message = szasar.recvline(sBU).decode("ascii")
    if not iserror(message):
        print("Identification has been done correctly with the BackupServer")
    else:
        print("Has not been possible to identify on the backup server")
        return

    #UPLOAD1
    message = "{}{}?{}\r\n".format(szasar.Command.Upload, filename, filesize)
    sBU.sendall(message.encode("ascii"))
    message = szasar.recvline(sBU).decode("ascii")
    if not iserror(message):
        print("UPLOAD1 has been done correctly with the BackupServer ")
    else:
        print("Has not been possible to make UPLOAD1 on the BackupServer")
        return

    #UPLOAD2
    print(" ======= UPLOAD2 ======= ")
    message = "{}\r\n".format(szasar.Command.Upload2)
    sBU.sendall(message.encode("ascii"))
    sBU.sendall(filedata)
    print("Upload2 enviado")
    message = szasar.recvline(sBU).decode("ascii")
    if not iserror(message):
        print("The file {} has been uploaded correctly to the BackupServer".
              format(filename))
    else:
        print("Has not been possible to make UPLOAD1 on the BackupServer")
Пример #2
0
def comprobar(s_alt):
    while (1):
        preparados, _, _ = select.select([s_alt], [], [], 10)
        if (len(preparados) == 0):
            print ("HA FALLADO EL SERVIDOR PRIMARIO")
        else:
            szasar.recvline(s_alt).decode("ascii")
            s_alt.sendall("OK\r\n".encode("ascii"))
Пример #3
0
def session(s, sr):

    ULTIMO = 0
    inputs = [s, sr]
    while True:
        #print ("Incio del bucle")
        disponibles = 0
        while disponibles == 0:
            #print ("dentro del while")
            inready, outready, excready = select.select(inputs, [], [])
            disponibles = len(inready)
            print("SOCKETS CON MENSAJE " + str(disponibles))

        #print ("ULTIMO MENSAJE TRATADO")
        #print (ULTIMO)

        if (disponibles == 1):
            if (s in inready):
                print("MENSAJE DE S")
                message = szasar.recvline(s).decode("ascii")
                print(message)
                if (int(message[:4]) > int(ULTIMO)):
                    ULTIMO = message[:4]
                    difundir(message, sr)
                    tratarMensaje(message[4:], s)
            elif (sr in inready):
                print("MENSAJE DE SR")
                message = szasar.recvline(sr).decode("ascii")
                print(message)
                if (int(message[:4]) > int(ULTIMO)):
                    ULTIMO = message[:4]
                    tratarMensaje(message[4:], s)

        elif (disponibles == 2):
            print("ESTAN LOS DOS")
            message_s = szasar.recvline(s).decode()
            message_r = szasar.recvline(sr).decode()
            ID_s = message_s[:4]
            ID_r = message_r[:4]
            print(message_s)
            print(message_r)
            if (int(ID_s) > int(ULTIMO)):
                ULTIMO = message_s[:4]
                difundir(message_s, sr)
                tratarMensaje(message_s[4:], s)
            if (int(ID_r) > int(ULTIMO)):
                ULTIMO = message_r[:4]
                tratarMensaje(message_r[4:], s)
def sendBU(sBU, user, filename, filesize, filedata):
    #IDENT
    print(" ======= BU IDENT ======= ")
    print("BU CHECK user: "******" filename: " + str(filename) +
          " filesize: " + str(filesize) + " filedata: " + str(filedata))
    print("IDENT: Usuario enviado al backup: " + user)
    message = "{}{}\r\n".format(szasar.Command.User, user)
    sBU.sendall(message.encode("ascii"))
    try:
        message = szasar.recvline(sBU).decode("ascii")
    except:
        sendER(s, 2)

    if iserror(message):
        print(
            "ERROR1: He entrado al caso en el que el mensaje es error. message: "
            + message)
        return

    #UPLOAD1
    print(" ======= UPLOAD1 ======= ")
    message = "{}{}?{}\r\n".format(szasar.Command.Upload, filename, filesize)
    sBU.sendall(message.encode("ascii"))
    print("Upload1 enviado")
    message = szasar.recvline(sBU).decode("ascii")
    if iserror(message):
        print(
            "ERROR2: He entrado al caso en el que el mensaje es error. message: "
            + message)
        return

    #UPLOAD2
    print(" ======= UPLOAD2 ======= ")
    message = "{}\r\n".format(szasar.Command.Upload2)
    sBU.sendall(message.encode("ascii"))
    sBU.sendall(filedata)
    print("Upload2 enviado")
    message = szasar.recvline(sBU).decode("ascii")
    if iserror(message):
        print(
            "ERROR3: He entrado al caso en el que el mensaje es error. message: "
            + message)
        return
    if not iserror(message):
        print("El fichero {} se ha enviado correctamente al BACKUP SERVER.".
              format(filename))
Пример #5
0
def electNewPrimary():
    for process in backuplist:
        process.sendall(("ELON\r\n".encode("ascii")))
        ready = select.select([process], [], [], 7000)
        if not ready[0]:
            continue
        else:
            message = szasar.recvline(s).decode("ascii")
            if (message.startswith("OK")):
                primary = process
Пример #6
0
def comprobarSiOK(dialog_1, dialog_2):
    intentos = 0
    while (1):
        print(intentos)
        intentos = intentos + 1
        disponibles, a, e = select.select([dialog_1, dialog_2], [], [])
        print("DISPONIBLES: " + str(len(disponibles)))
        if (len(disponibles) == 2):
            message_1 = szasar.recvline(dialog_1).decode("ascii")
            message_2 = szasar.recvline(dialog_2).decode("ascii")
            if (message_1[:2] == "OK" and message_2[:2] == "OK"):
                return "OK"
                break
            else:
                return "NO"
                break
        else:
            if (intentos > 10):
                return "NO"
                break
Пример #7
0
def deleteBU(sBU, user, filename):

    #Identification phase
    message = "{}{}\r\n".format(szasar.Command.User, user)
    sBU.sendall(message.encode("ascii"))
    message = szasar.recvline(sBU).decode("ascii")
    if not iserror(message):
        print("Identification has been done correctly with the BackupServer")
    else:
        print("Has not been possible to make UPLOAD2 on the BackupServer")
        return

    #Delete phase
    message = "{}{}\r\n".format(szasar.Command.Delete, filename)
    sBU.sendall(message.encode("ascii"))
    message = szasar.recvline(sBU).decode("ascii")
    if not iserror(message):
        print("Delete has been done correctly with the BackupServer")
    else:
        print("Has not been possible to make delete on the BackupServer")
        return
Пример #8
0
def beat(p):
    print("Estoy en Beat")
    slist = []
    slist.append(p)
    sendBEAT(p)
    #p.sendall(("BE\r\n").encode("ascii")) #queremos enviar el mensaje m al processo
    ready = select.select(slist, [], [], 7000)
    if not ready[0]:
        print("Not ready. Beat mal: " + message)
        return False
    else:
        message = szasar.recvline(p).decode("ascii")
        if message.startswith("B"):  #if ok
            print("Beat bien")
            return True
        else:
            print("Beat mal: " + message)
            return False
def beat(p):
    print("=== BEAT ===")
    slist = []
    slist.append(p)
    sendBEAT(p)
    #p.send(("BEAT\r\n").encode("ascii")) #queremos enviar el mensaje m al processo
    ready = select.select(slist, [], [], 30)
    if not ready[0]:
        print("Not ready. Timeout ocurred")
        return False
    else:
        try:
            message = szasar.recvline(p).decode("ascii")
            if message.startswith("B"):  #if ok
                print("+++++++ Beat bien")
                return True
        except:
            print("Beat mal... :( ")
            return False
Пример #10
0
def session(s, backuplist):
    state = State.Identification

    while True:
        #print("---SERVER: A la espera de un mensaje........................")
        message = szasar.recvline(s).decode("ascii")
        #print( "---SERVER: Leido msg {} {}\r\n.".format( message[0:4], message[4:] ) )
        if not message:
            return

        if message.startswith(szasar.Command.User):
            if (state != State.Identification):
                sendER(s)
                continue
            try:
                user = USERS.index(message[4:])
                username = message[4:]
            except:
                sendER(s, 2)
            else:
                sendOK(s)
                state = State.Authentication

        elif message.startswith(szasar.Command.Password):
            if state != State.Authentication:
                sendER(s)
                continue
            if (user == 0 or PASSWORDS[user] == message[4:]):
                sendOK(s)
                filespath = os.path.join(FILES_PATH, USERS[user])
                state = State.Main
            else:
                sendER(s, 3)
                state = State.Identification

        elif message.startswith(szasar.Command.List):
            if state != State.Main:
                sendER(s)
                continue
            try:
                message = "OK\r\n"
                for filename in os.listdir(filespath):
                    filesize = os.path.getsize(
                        os.path.join(filespath, filename))
                    message += "{}?{}\r\n".format(filename, filesize)
                message += "\r\n"
            except:
                sendER(s, 4)
            else:
                s.sendall(message.encode("ascii"))

        elif message.startswith(szasar.Command.Download):
            if state != State.Main:
                sendER(s)
                continue
            filename = os.path.join(filespath, message[4:])
            try:
                filesize = os.path.getsize(filename)
            except:
                sendER(s, 5)
                continue
            else:
                sendOK(s, filesize)
                state = State.Downloading

        elif message.startswith(szasar.Command.Download2):
            if state != State.Downloading:
                sendER(s)
                continue
            state = State.Main
            try:
                with open(filename, "rb") as f:
                    filedata = f.read()
            except:
                sendER(s, 6)
            else:
                sendOK(s)
                s.sendall(filedata)

        elif message.startswith(szasar.Command.Upload):
            if state != State.Main:
                sendER(s)
                continue
            if user == 0:
                sendER(s, 7)
                continue
            filename, filesize = message[4:].split('?')
            filesize = int(filesize)
            if filesize > MAX_FILE_SIZE:
                sendER(s, 8)
                continue
            svfs = os.statvfs(filespath)
            if filesize + SPACE_MARGIN > svfs.f_bsize * svfs.f_bavail:
                sendER(s, 9)
                continue
            sendOK(s)
            state = State.Uploading

        elif message.startswith(szasar.Command.Upload2):
            if state != State.Uploading:
                sendER(s)
                continue
            state = State.Main
            try:
                with open(os.path.join(filespath, filename), "wb") as f:
                    filedata = szasar.recvall(s, filesize)
                    f.write(filedata)
            except:
                sendER(s, 10)
            else:
                #Upload to the secondary servers before sending ACK to the client
                for i in backuplist:
                    sendBU(i, username, filename, filesize, filedata)
                sendOK(s)

        elif message.startswith(szasar.Command.Delete):
            if state != State.Main:
                sendER(s)
                continue
            if user == 0:
                sendER(s, 7)
                continue
            try:
                os.remove(os.path.join(filespath, message[4:]))
            except:
                sendER(s, 11)
            else:
                #Delete from the secondary servers before sending ACK to the client
                for i in backuplist:
                    deleteBU(i, username, message[4:])
                sendOK(s)

        elif message.startswith(szasar.Command.Exit):
            sendOK(s)
            s.close()
            return

        else:
            sendER(s)
Пример #11
0
def session(s, i):
    state = State.Identification
    f_path = FILES_PATH + str(i)
    while True:
        print("Session: Hola soy el serverBU{}. Mi filepath es: {}".format(
            i, f_path))
        message = szasar.recvline(s).decode("ascii")
        print("RECV: Estado: " + str(state) + "Msg: " + message)
        if not message:
            print("ERROR: No habia mensaje en sBU")
            return

        if message.startswith(szasar.Command.User):
            print("IDENT: sBU ha entrado en identificacion")
            if (state != State.Identification):
                print("IDENT: Error en la identificacion")
                sendER(s)
                continue
            try:
                user = USERS.index(message[4:])
                username = message[4:]
                filespath = os.path.join(f_path, username)
                print("IDENT: Identification realizada: " + username)
                sendOK(s)
                helbidea, portua = s.getsockname()
                helbidea2 = s.getpeername()
                print("IDENT: OKIdent enviado")
                state = State.Main
            except Exception as e:
                #print("ERROR en ID: usuario recibido: {}" + str(message[4:]) + "yep")
                #print("Error en la identificacion")
                print(e)
                #sendER( s, 2 )

        # elif message.startswith( szasar.Command.Password ):
        # if state != State.Authentication:
        # sendER( s )
        # continue
        # if( user == 0 or PASSWORDS[user] == message[4:] ):
        # sendOK( s )
        # state = State.Main
        # else:
        # sendER( s, 3 )
        # state = State.Identification

        # elif message.startswith( szasar.Command.List ):
        # if state != State.Main:
        # sendER( s )
        # continue
        # try:
        # message = "OK\r\n"
        # for filename in os.listdir( f_path ):
        # filesize = os.path.getsize( os.path.join( f_path, filename ) )
        # message += "{}?{}\r\n".format( filename, filesize )
        # message += "\r\n"
        # except:
        # sendER( s, 4 )
        # else:
        # s.sendall( message.encode( "ascii" ) )

        elif message.startswith(szasar.Command.Download):
            print("Mensaje de descarga detectado")
            if state != State.Main:
                sendER(s)
                continue
            filename = os.path.join(f_path, message[4:])
            try:
                filesize = os.path.getsize(filename)
            except:
                sendER(s, 5)
                continue
            else:
                sendOK(s, filesize)
                state = State.Downloading

        elif message.startswith(szasar.Command.Download2):
            if state != State.Downloading:
                sendER(s)
                continue
            state = State.Identification
            try:
                with open(filename, "rb") as f:
                    filedata = f.read()
            except:
                sendER(s, 6)
            else:
                sendOK(s)
                s.sendall(filedata)

        elif message.startswith(szasar.Command.Upload):
            print("Mensaje de subida detectado")
            if state != State.Main:
                sendER(s)
                continue
            if user == 0:
                sendER(s, 7)
                continue
            filename, filesize = message[4:].split('?')
            filesize = int(filesize)
            if filesize > MAX_FILE_SIZE:
                print("llega error 3")
                sendER(s, 8)
                continue
            svfs = os.statvfs(f_path)
            if filesize + SPACE_MARGIN > svfs.f_bsize * svfs.f_bavail:
                print("llega error 4")
                sendER(s, 9)
                continue
            print("OK1 enviando")
            sendOK(s)
            print("Subida1 completada. filename: {} filesize: {} ".format(
                filename, filesize))
            state = State.Uploading

        elif message.startswith(szasar.Command.Upload2):
            print("Fase 2 de la subida")
            if state != State.Uploading:
                sendER(s)
                continue
            state = State.Identification
            try:
                directories = separate_path(filename)
                print("len(directories): " + str(len(directories)))
                for i in range(len(directories)):
                    if i == 0:
                        finalpath = ""
                    else:
                        finalpath = os.path.join(finalpath, directories[i])
                        print("finalpath: " + finalpath)
                        if (os.path.exists(os.path.join(filespath,
                                                        finalpath)) == False):
                            if (i != len(directories) - 1):
                                os.mkdir(os.path.join(filespath, finalpath))
                with open(os.path.join(filespath, filename), "wb") as f:
                    print("Hemos abierto el path")
                    filedata = szasar.recvall(s, filesize)
                    print("Hemos recibido la información")
                    f.write(filedata)
                    print("Hemos escrito los datos")
                #print (e) #este print hace que entre en el except
            except:
                print("UPLOAD2: He entrado en el except.")
                sendER(s, 10)
            else:
                print("OK2 enviado")
                sendOK(s)

        elif message.startswith(szasar.Command.Delete):
            if state != State.Main:
                sendER(s)
                continue
            if user == 0:
                sendER(s, 7)
                continue
            try:
                os.remove(os.path.join(filespath, message[4:]))
            except:
                sendER(s, 11)
            else:
                sendOK(s)

        elif message.startswith(szasar.Command.Exit):
            sendOK(s)
            return

        elif message.startswith(szasar.Command.Beat):
            print("Session: Msg identificado como beat")
            sendBEAT(s)
        else:
            sendER(s)
def session(s, backuplist):
    state = State.Identification

    while True:
        print("---SERVER: A la espera de un mensaje........................")
        message = szasar.recvline(s).decode("ascii")
        #print( "---SERVER: Leido msg {} {}\r\n.".format( message[0:4], message[4:] ) )
        if not message:
            return

        if message.startswith(szasar.Command.User):
            if (state != State.Identification):
                sendER(s)
                continue
            try:
                user = USERS.index(message[4:])
                username = message[4:]
            except:
                sendER(s, 2)
            else:
                sendOK(s)
                state = State.Authentication

        elif message.startswith(szasar.Command.Password):
            if state != State.Authentication:
                sendER(s)
                continue
            if (user == 0 or PASSWORDS[user] == message[4:]):
                sendOK(s)
                filespath = os.path.join(FILES_PATH, USERS[user])
                state = State.Main
            else:
                sendER(s, 3)
                state = State.Identification

        elif message.startswith(szasar.Command.List):
            if state != State.Main:
                sendER(s)
                continue
            try:
                message = "OK\r\n"
                for filename in os.listdir(filespath):
                    filesize = os.path.getsize(
                        os.path.join(filespath, filename))
                    message += "{}?{}\r\n".format(filename, filesize)
                message += "\r\n"
            except:
                sendER(s, 4)
            else:
                s.sendall(message.encode("ascii"))

        elif message.startswith(szasar.Command.Download):
            if state != State.Main:
                sendER(s)
                continue
            filename = os.path.join(filespath, message[4:])
            try:
                filesize = os.path.getsize(filename)
            except:
                sendER(s, 5)
                continue
            else:
                sendOK(s, filesize)
                state = State.Downloading

        elif message.startswith(szasar.Command.Download2):
            if state != State.Downloading:
                sendER(s)
                continue
            state = State.Main
            try:
                with open(filename, "rb") as f:
                    filedata = f.read()
            except:
                sendER(s, 6)
            else:
                sendOK(s)
                s.sendall(filedata)

        elif message.startswith(szasar.Command.Upload):
            if state != State.Main:
                sendER(s)
                continue
            if user == 0:
                sendER(s, 7)
                continue
            filename, filesize = message[4:].split('?')
            filesize = int(filesize)
            if filesize > MAX_FILE_SIZE:
                sendER(s, 8)
                continue
            svfs = os.statvfs(filespath)
            if filesize + SPACE_MARGIN > svfs.f_bsize * svfs.f_bavail:
                sendER(s, 9)
                continue
            sendOK(s)
            state = State.Uploading

        elif message.startswith(szasar.Command.Upload2):
            if state != State.Uploading:
                sendER(s)
                continue
            state = State.Main
            try:
                with open(os.path.join(filespath, filename), "wb") as f:
                    filedata = szasar.recvall(s, filesize)
                    f.write(filedata)
                    print("MAIN: Escrito en la memoria correctamente")
            except:
                sendER(s, 10)
            else:
                #Ahora toca subirlo a los BACKUP ANTES DE MANDAR EL OK.
                print("Numero de copias a realizar: " + str(len(backuplist)))
                sbu = backuplist[0]
                #i=0
                for i in backuplist:
                    print("Se va a realizar la copia en un servidor")
                    print("CHECK user: "******" filename: " +
                          str(filename) + " filesize: " + str(filesize) +
                          " filedata: " + str(filedata))
                    sendBU(i, username, filename, filesize, filedata)
                    print(
                        "Se ha realizado correctamente la copia en el BackupServer"
                        + str(i))
                    #i += 1 #no es necesario aumentar esto, el for lo hace solo. Ademas de que i es un ELEMENTO de backuplist, no un int.
                sendOK(s)
                print("OK enviado al cliente")

        elif message.startswith(szasar.Command.Delete):
            if state != State.Main:
                sendER(s)
                continue
            if user == 0:
                sendER(s, 7)
                continue
            try:
                os.remove(os.path.join(filespath, message[4:]))
            except:
                sendER(s, 11)
            else:
                sendOK(s)

        elif message.startswith(szasar.Command.Exit):
            sendOK(s)
            s.close()
            return
        elif message.startswith(szasar.Command.Beat):
            print("Session: Msg identificado como beat")
            #sendBEAT( s )
        else:
            sendER(s)
Пример #13
0
def session(s, i):
    state = State.Identification
    f_path = FILES_PATH + str(i)
    while True:
        #print("Hola soy el serverBU{}. Mi filepath es: {}".format(i, f_path))
        message = szasar.recvline(s).decode("ascii")
        #print("RECV: Estado: " + str(state) + "Msg: " + message)
        if not message:
            return

        if message.startswith(szasar.Command.User):
            if (state != State.Identification):
                sendER(s)
                continue
            try:
                user = USERS.index(message[4:])
                username = message[4:]
                #filespath = os.path.join( f_path, "sar" ) Poniendo esto, todos los usuarios suben sus archivos a la carpeta sar
                filespath = os.path.join(f_path, username)
                sendOK(s)
                helbidea, portua = s.getsockname()
                helbidea2 = s.getpeername()
                state = State.Main
            except Exception as e:
                #print("ERROR en ID: usuario recibido: {}" + str(message[4:]) + "yep")
                #print("Error en la identificacion")
                print(e)
                #sendER( s, 2 )
        elif message.startswith(szasar.Command.Elon):
            sendOK(s)
        elif message.startswith(szasar.Command.Modify):
            if state != State.Main:
                sendER(s)
                continue
            if user == 0:
                sendER(s, 7)
                continue
            filename, filesize = message[4:].split('?')
            filesize = int(filesize)
            if filesize > MAX_FILE_SIZE:
                sendER(s, 8)
                continue
            svfs = os.statvfs(filespath)
            if filesize + SPACE_MARGIN > svfs.f_bsize * svfs.f_bavail:
                sendER(s, 9)
                continue
            sendOK(s)
            state = State.Modifying
        elif message.startswith(szasar.Command.Modify2):
            print("He entrado en Session Update2")
            if state != State.Modifying:
                print("He entrado en el error de state de update2")
                sendER(s)
                continue
            state = State.Main
            #falta hacer la comprobacion de diff con los cambios a hacer al fichero
            try:
                with open(os.path.join(filespath, 'temp1'), "wb") as f:
                    filedata = szasar.recvall(s, filesize)
                    f.write(filedata)
                with open(filename, "a+") as file1, open('temp1') as file2:
                    words1 = set(file1)
                    words2 = set(file2)
                    new_words = words2 - words1
                    common = words1.intersection(words2)
                    if new_words:
                        file1.write('\n')
                        for w in new_words:
                            file1.write(w)
                os.remove('temp1')
            except:
                sendER(s, 10)
            else:
                #Upload to the secondary servers before sending ACK to the client
                for i in backuplist:
                    modifyBU(i, username, filename, filesize, filedata)
                print("Update2. Voy a enviar el OK")
                sendOK(s)
        elif message.startswith(szasar.Command.Sock):
            sockets = s.recv(4096)
            sockets = sockets[4:-1]
            backuplistescuchar = [None] * int((len(sockets) / 2))
            i = 0
            j = 0
            while (i < len(sockets) - 1):
                helbidea = sockets[i]
                portua = sockets[i + 1]
                backuplistescuchar[j] = socket.socket(socket.AF_INET,
                                                      socket.SOCK_STREAM)
                try:
                    backuplistescuchar[j].bind(('', portua))
                    print("bind bien en la sincronizacion de sockets")
                except socket.error as msg:
                    print('Bind falla en la sincronizacion de sockets: ' +
                          str(msg))
                    sys.exit()
                backuplistescuchar[j].listen(5)
                j = j + 1
                i = i + 2
            time.sleep(3)
            j = 0
            i = 0
            backuplist = [None] * int((len(sockets) / 2))
            while (i < len(sockets) - 1):
                helbidea = sockets[i]
                portua = sockets[i + 1]
                backuplist[j] = socket.socket(
                    socket.AF_INET,
                    socket.SOCK_STREAM)  #Create new socket for each server.
                backuplist[j].connect((helbidea, portua))
                j = j + 1
                i = i + 2

        elif message.startswith(szasar.Command.Password):
            if state != State.Authentication:
                sendER(s)
                continue
            if (user == 0 or PASSWORDS[user] == message[4:]):
                sendOK(s)
                state = State.Main
            else:
                sendER(s, 3)
                state = State.Identification

        elif message.startswith(szasar.Command.List):
            if state != State.Main:
                sendER(s)
                continue
            try:
                message = "OK\r\n"
                for filename in os.listdir(f_path):
                    filesize = os.path.getsize(os.path.join(f_path, filename))
                    message += "{}?{}\r\n".format(filename, filesize)
                message += "\r\n"
            except:
                sendER(s, 4)
            else:
                s.sendall(message.encode("ascii"))

        elif message.startswith(szasar.Command.Download):
            print("Mensaje de descarga detectado")
            if state != State.Main:
                sendER(s)
                continue
            filename = os.path.join(f_path, message[4:])
            try:
                filesize = os.path.getsize(filename)
            except:
                sendER(s, 5)
                continue
            else:
                sendOK(s, filesize)
                state = State.Downloading

        elif message.startswith(szasar.Command.Download2):
            if state != State.Downloading:
                sendER(s)
                continue
            state = State.Identification
            try:
                with open(filename, "rb") as f:
                    filedata = f.read()
            except:
                sendER(s, 6)
            else:
                sendOK(s)
                s.sendall(filedata)

        elif message.startswith(szasar.Command.Upload):
            if state != State.Main:
                sendER(s)
                continue
            if user == 0:
                sendER(s, 7)
                continue
            filename, filesize = message[4:].split('?')
            filesize = int(filesize)
            if filesize > MAX_FILE_SIZE:
                sendER(s, 8)
                continue
            svfs = os.statvfs(f_path)
            if filesize + SPACE_MARGIN > svfs.f_bsize * svfs.f_bavail:
                sendER(s, 9)
                continue
            sendOK(s)
            state = State.Uploading

        elif message.startswith(szasar.Command.Upload2):
            if state != State.Uploading:
                sendER(s)
                continue
            state = State.Identification
            try:
                #print("1")
                directories = separate_path(filename)
                for i in range(len(directories)):
                    #print("2")
                    if i == 0:
                        #print("21")
                        finalpath = ""
                        #print("finalpath: " + finalpath + " filename: " + filename + " filespath: " + filespath)
                    else:
                        #print("22")
                        finalpath = os.path.join(finalpath, directories[i])
                        #print("3")
                        if (os.path.exists(os.path.join(filespath,
                                                        finalpath)) == False):
                            #print("4")
                            if (i != len(directories) - 1):
                                #print("5")
                                os.mkdir(os.path.join(filespath, finalpath))
                                #print("6")
                with open(os.path.join(filespath, filename), "wb") as f:
                    #print("7")
                    filedata = szasar.recvall(s, filesize)
                    #print("8")
                    f.write(filedata)
                    #print("9")
                #print (e) #este print hacia que entrara en el except
            except:
                print("He entrado en el except del upload 2")
                sendER(s, 10)
            else:
                sendOK(s)

        elif message.startswith(szasar.Command.Delete):
            if state != State.Main:
                sendER(s)
                continue
            if user == 0:
                sendER(s, 7)
                continue
            state = State.Identification
            try:
                os.remove(os.path.join(filespath, message[4:]))
            except:
                sendER(s, 11)
            else:
                sendOK(s)

        elif message.startswith(szasar.Command.Exit):
            sendOK(s)
            return

        elif message.startswith(szasar.Command.Beat):
            print("Session: Msg identificado como beat")
            sendBEAT(s)

        elif message.startswith(szasar.Command.Update):
            print("Mensaje identificado como update")
            if state != State.Main:
                sendER(s)
                continue
            try:
                message = "OK\r\n"
                for filename in os.listdir(filespath):
                    with open(filename, "rb") as f:
                        filedata = f.read()
                    message += "{}?{}?\r\n".format(filename, filedata)
                message += "\r\n"
                #siempre se envia el mensaje asi: nombre?contenido
            except:
                sendER(s, 4)
            else:
                s.sendall(message.encode("ascii"))

        else:
            sendER(s)
Пример #14
0
def log():
	user = input( "Introduce el nombre de usuario: " )				# El cliente pregunta al usuario su nick
	password = input( "Introduce la contraseña: " )					# El cliente pregunta al usuario su contrasena
	message = "{}{}#{}\r\n".format( szasar.Command.Log, user, password )
	s.sendall( message.encode() )
	return szasar.recvline(s).decode()
Пример #15
0
	option = Menu.menu()											# Printea el menu para que el usuario vea las diferentes opciones y elija la requerida

	if option == Menu.Upload:										# Esta funcion nos permite enviar un video al servidor para guardarlo alli
		filename = input( "Indica el fichero que quieres subir: " )
		try:
			filesize = os.path.getsize( filename )					# Primero, intentara acceder al archivo y leerlo. En caso de error el cliente se lo printeara al usuario
			with open( filename, "rb" ) as f:
				filedata = f.read()
				print("Tamaño: ", len(filedata), " bytes")
		except:
			print( "No se ha podido acceder al fichero {}.".format( filename ) )
			continue

		message = "{}{}#".format( szasar.Command.Put, filesize ) 
		s.sendall( message.encode() + filedata)						# Enviamos el mensaje junto, pero lo juntamos directamente en bytes para no tener que traducir bytes a strings.
		message = szasar.recvline( s ).decode()						# Recibimos la respuesta del servidor respecto a la consulta enviada por el cliente
		if not iserror( message ):									# En caso de que haya sido satisfactorio el cliente nos lo hara saber mediante un print
			print( "El fichero {} se ha enviado correctamente.".format( filename ) )
																	# En caso contrario, el cliente nos printeara el error correspondiente al fallo del proceso

	elif option == Menu.Download:									# Esta funcion nos permite descargar un video del cual enviaremos el ID
		fileid = input( "Indica el fichero que quieres bajar: " )
		message =  "{}{}\r\n".format( szasar.Command.Get, fileid )
		s.sendall( message.encode() )
		message = szasar.recvline_file( s )							# Recibimos la respuesta del servidor respecto a la consulta enviada por el cliente
		if iserror(message[:5].decode()):							# Comprobamos si la respuesta del servidor es correcta, en este caso el cliene intentara escribir los 
			continue												# datos del video enviados por el servidor, en caso de que haya un error al escribir, lo printera.
		try:														# Si la respuesta es erronea el cliente printeara la explicacion del error y volvera a printear
			with open(fileid, "wb" ) as f:							# el menu para que el cliente decida que opcion quiere realizar
				f.write( message[3:] )
		except:
Пример #16
0
def session(s):
    state = State.Identification
    print(s, "\n\n", state)
    while True:
        message = szasar.recvline(dialog).decode("ascii")
        if not message:
            return

        if message.startswith(szasar.Command.User):
            if (state != State.Identification):
                sendER(s)
                continue
            try:
                user = USERS.index(message[4:])
            except:
                sendER(s, 2)
            else:
                sendOK(s)
                state = State.Authentication

        elif message.startswith(szasar.Command.Password):
            if state != State.Authentication:
                sendER(s)
                continue
            if (user == 0 or PASSWORDS[user] == message[4:]):
                sendOK(s)
                state = State.Main

            else:
                sendER(s, 3)
                state = State.Identification

        elif message.startswith(szasar.Command.List):
            if state != State.Main:
                sendER(s)
                continue
            try:
                message = "OK\r\n"
                for filename in os.listdir(FILES_PATH):
                    filesize = os.path.getsize(
                        os.path.join(FILES_PATH, filename))
                    message += "{}?{}\r\n".format(filename, filesize)
                message += "\r\n"
            except:
                sendER(s, 4)
            else:
                s.sendall(message.encode("ascii"))

        elif message.startswith(szasar.Command.Download):
            if state != State.Main:
                sendER(s)
                continue
            filename = os.path.join(FILES_PATH, message[4:])
            try:
                filesize = os.path.getsize(filename)
            except:
                sendER(s, 5)
                continue
            else:
                sendOK(s, filesize)
                state = State.Downloading

        elif message.startswith(szasar.Command.Download2):
            if state != State.Downloading:
                sendER(s)
                continue
            state = State.Main
            try:
                with open(filename, "rb") as f:
                    filedata = f.read()
            except:
                sendER(s, 6)
            else:
                sendOK(s)
                s.sendall(filedata)

        elif message.startswith(szasar.Command.Upload):
            if state != State.Main:
                sendER(s)
                continue
            if user == 0:
                sendER(s, 7)
                continue
            filename, filesize = message[4:].split('?')
            filesize = int(filesize)
            if filesize > MAX_FILE_SIZE:
                sendER(s, 8)
                continue
            svfs = os.statvfs(FILES_PATH)
            if filesize + SPACE_MARGIN > svfs.f_bsize * svfs.f_bavail:
                sendER(s, 9)
                continue
            sendOK(s)
            state = State.Uploading

        elif message.startswith(szasar.Command.Upload2):
            if state != State.Uploading:
                sendER(s)
                continue
            state = State.Main
            try:
                with open(os.path.join(FILES_PATH, filename), "wb") as f:
                    filedata = szasar.recvall(s, filesize)
                    f.write(filedata)
            except:
                sendER(s, 10)
            else:
                sendOK(s)

        elif message.startswith(szasar.Command.Delete):
            if state != State.Main:
                sendER(s)
                continue
            if user == 0:
                sendER(s, 7)
                continue
            try:
                os.remove(os.path.join(FILES_PATH, message[4:]))
            except:
                sendER(s, 11)
            else:
                sendOK(s)

        elif message.startswith(szasar.Command.Exit):
            sendOK(s)
            return

        else:
            sendER(s)
Пример #17
0
	#if len( sys.argv ) >= 2:
	#	SERVER = sys.argv[1]
	#if len( sys.argv ) == 3:
	#	PORT = int( sys.argv[2])

	s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
	s.connect( (SERVER, PORT) )

	
	while True:
		#user = input( "Introduce el nombre de usuario: " )
		user= sys.argv[1]
		message = "{}{}\r\n".format( szasar.Command.User, user )
		s.sendall( message.encode( "ascii" ) )
		message = szasar.recvline( s ).decode( "ascii" )
		if iserror( message ):
			continue

		#password = input( "Introduce la contraseña: " )
		password= sys.argv[2]
		message = "{}{}\r\n".format( szasar.Command.Password, password )
		s.sendall( message.encode( "ascii" ) )
		message = szasar.recvline( s ).decode( "ascii" )
		if not iserror( message ):
			break


	while True:
		print("llamada a operation")
		option,filename,path = operation()
Пример #18
0
def session( s, i ):
	state = State.Identification
	f_path = FILES_PATH + str(i)
	while True:
		#print("Hola soy el serverBU{}. Mi filepath es: {}".format(i, f_path))
		message = szasar.recvline( s ).decode( "ascii" )
		#print("RECV: Estado: " + str(state) + "Msg: " + message)
		if not message:
			return

		if message.startswith( szasar.Command.User ):
			if( state != State.Identification ):
				sendER( s )
				continue
			try:
				user = USERS.index( message[4:] )
				username = message[4:]
				filespath = os.path.join( f_path, username )
				sendOK( s )
				helbidea, portua = s.getsockname()
				helbidea2 = s.getpeername()
				state = State.Main
			except Exception as e:
				#print("ERROR en ID: usuario recibido: {}" + str(message[4:]) + "yep")
				#print("Error en la identificacion")
				print(e)
				#sendER( s, 2 )


		# elif message.startswith( szasar.Command.Password ):
			# if state != State.Authentication:
				# sendER( s )
				# continue
			# if( user == 0 or PASSWORDS[user] == message[4:] ):
				# sendOK( s )
				# state = State.Main
			# else:
				# sendER( s, 3 )
				# state = State.Identification

		# elif message.startswith( szasar.Command.List ):
			# if state != State.Main:
				# sendER( s )
				# continue
			# try:
				# message = "OK\r\n"
				# for filename in os.listdir( f_path ):
					# filesize = os.path.getsize( os.path.join( f_path, filename ) )
					# message += "{}?{}\r\n".format( filename, filesize )
				# message += "\r\n"
			# except:
				# sendER( s, 4 )
			# else:
				# s.sendall( message.encode( "ascii" ) )

		elif message.startswith( szasar.Command.Download ):
			print("Mensaje de descarga detectado")
			if state != State.Main:
				sendER( s )
				continue
			filename = os.path.join( f_path, message[4:] )
			try:
				filesize = os.path.getsize( filename )
			except:
				sendER( s, 5 )
				continue
			else:
				sendOK( s, filesize )
				state = State.Downloading

		elif message.startswith( szasar.Command.Download2 ):
			if state != State.Downloading:
				sendER( s )
				continue
			state = State.Identification
			try:
				with open( filename, "rb" ) as f:
					filedata = f.read()
			except:
				sendER( s, 6 )
			else:
				sendOK( s )
				s.sendall( filedata )

		elif message.startswith( szasar.Command.Upload ):
			if state != State.Main:
				sendER( s )
				continue
			if user == 0:
				sendER( s, 7 )
				continue
			filename, filesize = message[4:].split('?')
			filesize = int(filesize)
			if filesize > MAX_FILE_SIZE:
				sendER( s, 8 )
				continue
			svfs = os.statvfs( f_path )
			if filesize + SPACE_MARGIN > svfs.f_bsize * svfs.f_bavail:
				sendER( s, 9 )
				continue
			sendOK( s )
			state = State.Uploading

		elif message.startswith( szasar.Command.Upload2 ):
			if state != State.Uploading:
				sendER( s )
				continue
			state = State.Identification
			try:
				directories = separate_path(filename)
				for i in range(len(directories)):
					if i==0:
						finalpath = ""
					else:
						finalpath = os.path.join(finalpath,directories[i])
						if(os.path.exists(os.path.join( filespath, finalpath))==False):
							if(i!=len(directories)-1):
								os.mkdir(os.path.join( filespath, finalpath))
				with open( os.path.join( filespath, filename), "wb" ) as f:
					filedata = szasar.recvall( s, filesize )
					f.write( filedata )
				print (e)
			except:
				sendER( s, 10 )
			else:
				sendOK( s )

		elif message.startswith( szasar.Command.Delete ):
			if state != State.Main:
				sendER( s )
				continue
			if user == 0:
				sendER( s, 7 )
				continue
			state = State.Identification
			try:
				os.remove( os.path.join( filespath, message[4:] ) )
			except:
				sendER( s, 11 )
			else:
				sendOK( s )

		elif message.startswith( szasar.Command.Exit ):
			sendOK( s )
			return

		else:
			sendER( s )