noobboomer
noobboomer

Reputation: 11

OSError: [Errno 9] Bad file descriptor

I initially tried using python to run but there were different errors so I tried using python3 and received the error in the title. I am trying to connect to server and download a file that has tls implemented.

import socket, ssl, pprint
import os, time
import threading

def main():
    s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ssl_sock = ssl.wrap_socket(s2,
                           server_side = False,
                           ca_certs="CA.crt",
                           cert_reqs=ssl.CERT_REQUIRED)
    s2.connect(('localhost',10024))
    filename = raw_input("What file do you wish to download? -> ")

    if filename != 'q':
        s2.send(filename)

        data = s2.recv(1024)
        if data [:7] == 'fEXISTS':
            fSize = long(data[7:])

            message = raw_input("The file you wish to download is " +str(fSize)+\
                        "bytes, would you like to proceed? (y/n): ")

            if message == 'y':
                s2.send ('OK')
                f = open('new_'+filename, 'wb')
                data = s2.recv(2000000)
                totalRecv = len(data)
                f.write(data)

                while totalRecv < fSize:
                    data = s2.recv(2000000)
                    totalRecv += len(data)
                    f.write(data)
                    progress = ((totalRecv/float(fSize))*100)
                    print ("{0: .2F}".format(progress)+\
                            "% Completed")
        else:
            print ("ERROR: File does not exist!")
    s2.close()

if __name__ == '__main__':
    main()

Upvotes: 1

Views: 5133

Answers (1)

Gil Hamilton
Gil Hamilton

Reputation: 12357

After wrapping the socket in an SSL context (with ssl.wrap_socket), you should not be using the original socket anymore.

You should be calling connect, send, recv, etc. on ssl_sock, not on s2.

(Specifically, when you call ssl.wrap_socket, the .detach method is called on the original socket which removes the file descriptor from it. The file descriptor is transferred to the SSL socket instance. The only thing you can do with the original then is close/destroy it.)

Upvotes: 1

Related Questions