udp tftp: recvfrom() returns a positive but buff is empty

166 Views Asked by At
            uint32_t ip=time_count.rbegin()->first;
            clientAddress=ip_to_struct.find(ip)->second;
            for(auto i=time_count.begin();i!=time_count.end();i++){
                i->second+=timeOut_int-time_count.rbegin()->second;
            }
            time_count.erase(ip);
            time_count.insert(std::pair<uint32_t,int> (ip,0));
            }
            char buff[MAX_WRQ_SIZE];
            /*int recievedOPcode = */if(recvfrom(udp_fd, buff,MAX_WRQ_SIZE, 0,
            (struct sockaddr *) &clientAddress, &sockLen)<0){
            perror("TTFTP_ERROR4");
            exit(1);
            }
            if (strlen(buff)>0){
                for(int i =0;i<MAX_WRQ_SIZE;i++){
                cout<<"the buff cont is "<<buff[i]<<endl;
                }
            }
            else{
                cout<<"the buff is empty or worse"<<endl;
            }
            cout<<"buff is "<<buff;
            char opCodeChar[2];
            memcpy(opCodeChar,buff,2);
            if(atoi(opCodeChar)==WRQ_OPCODE){
                recieve_WRQ(buff,udp_fd,clientAddress);
            }
            else if(atoi(opCodeChar)==DATA_OPCODE){
                recieve_DATA(buff,udp_fd,clientAddress);
            }
            else{
                ERROR send_err_msg =
                {htons(ERROR_OPCODE), htons(4), "Illegal TFTP operation"};
                if(sendto(udp_fd, &send_err_msg, MAX_PACKET, 0,
                (struct sockaddr *) &clientAddress,
                sizeof(clientAddress)) <0){
                    cout<<"client address<0"<<endl;
                    perror("TTFTP_ERROR6");
                }
            }

        }

So basically I get "the buff is empty or worse" even though the return value of recvfrom is positive.

edit: basically what interests me is why the buffer appears empty. I have edited the code to include the line where I try to read from the buffer. when I print I get nothing (empty). What can I do?

1

There are 1 best solutions below

9
Steffen Ullrich On
        if (strlen(buff)>0){

strlen does not give the size of the buffer. It gives the number of bytes until the first \0 byte. Especially with binary data \0 bytes are pretty common in the middle of data. And there might even no \0 at all in the transmitted data - for example if only the characters of a string are transmitted (i.e. strlen bytes) but not a final \0. In this check might return a length larger than the actual data or might crash because unmapped memory is accessed.

To get the size of the transmitted data check the return code of recvfrom instead.