std::string parseRequest(int skt) {
    std::vector<char*> headers;
    GetHeaderLines(headers,skt,0);
    std::string requestedResource = "";
    //parse index headers
    for(int i = 0; i < headers.size(); i++) {
        std::cout << headers[i] << std::endl;
        std::string tString(headers[i]);
        int idx;
        //find requested resource in request headers
        if((idx = tString.find("HTTP_GET")) >= 0) {
            std::cout << "FOUND! at index " << idx << std::endl;
            int sidx, eidx;
            sidx = tString.find(" ") + 1;
            eidx = tString.find(" ", sidx);
            requestedResource = tString.substr(sidx, eidx - sidx);
            std::cout << requestedResource << std::endl;
            return requestedResource;
        }
    }
    return STAT_404;
}
Example #2
0
int main(int argc, char *argv[]){

    int hSocket, hServerSocket;
    struct sockaddr_in Address;
    struct hostent* pHostInfo;
    int nAddressSize= sizeof(struct sockaddr_in);
    int nHostPort;
    char pBuffer[BUFFER_SIZE];
    char strHostName[HOST_NAME_SIZE];
    char *path;
    unsigned nReadAmount;
    long nHostAddress;
    int count, headers = 0;
    int holder;
    int param;
    // bound checking
    if (argc < 4){

        printf("\nUSAGE: download host-name host-port path [-c | -d]\n");
        return 0;
    }else{
        while( (param = getopt(argc, argv, "c:d")) != -1) {
            switch(param) {
                case 'c':
                    count = atoi(optarg);
                    break;
                case 'd':
                    headers = 1;
                    break;
                default:
                    abort();
            }
        }

        printf("headers = %d, count = %d\n", headers, count);
        strcpy(strHostName, argv[optind++]);
        nHostPort = atoi(argv[optind++]);
        path = argv[optind];

    }
    printf("\nMaking a socket\n");
    hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // this makes the document
    if(hSocket == SOCKET_ERROR){
        printf("\nFailed to make a socket\n");
        return 0;
    }

    
    pHostInfo = gethostbyname(strHostName); // get the IP address by name
    //printf("here\n");
     if(pHostInfo == NULL){
        printf("Unable to resolve dns name\n");
        return 0;
    }
    memcpy(&nHostAddress, pHostInfo->h_addr, pHostInfo->h_length);
	
    // fill the Address struct defined in the beginning
    Address.sin_addr.s_addr = nHostAddress;
    Address.sin_port = htons(nHostPort);
    Address.sin_family = AF_INET;
    //printf("here\n");
    // try connecting to the host

    printf("\nConnecting to %s (%X) on port %d\n\n", strHostName, nHostAddress, nHostPort);
    if(connect(hSocket, (struct sockaddr*) &Address, sizeof(Address)) == SOCKET_ERROR){
        printf("\nUnable to connect to host\n");
        return 0;
    }

    // Create the HTTP message
    char* message = (char*) malloc(GET_MAX);

    sprintf(message, "GET %s HTTP/1.1\r\nHost:%s:%d\r\n\r\n", path, strHostName, nHostPort);
    
    if(headers)
        printf("Request: %s\n", message);

    write(hSocket, message, strlen(message));

    // once I send the request read the response.
   // nReadAmount = read(hSocket, pBuffer, BUFFER_SIZE);
   

    vector<char*> header;
    char contentType[MAX_MSG_SZ];
    // read the status line

    char* startline = GetLine(hSocket);
    if(headers)
        printf("Status line: %s\n\n", startline);

    // read the header line
    //printf("Headers %d\n", headers);
    GetHeaderLines(header, hSocket, false);
    if(headers){
        //cout << "\nHere";
        for(int i =0; i < header.size(); i++){
            printf("%s\n", header[i]);

        }
    }

    if(count > 0){
        printf("Downloaded\n");
        for(int i=1; i < count; i++){
            //write(1, pBuffer, (unsigned)holder);
            write(hSocket, message, strlen(message));
            printf("Downloaded %d times\n", i+1);
        }
    }
    if(!count){
         while( (holder = read(hSocket, pBuffer, MAX_MSG_SZ)) > 0){
        write(1, pBuffer, (unsigned)holder);
        }

    }
   
    printf("\nClosing socket NOW\n");
    if(close(hSocket) == SOCKET_ERROR){
        printf("\nUnable to close socket\n");
        return 0;
    }


}
Example #3
0
int main(int argc, char *argv[])
{
	int hSocket;                 /* handle to socket */
	struct hostent *pHostInfo;   /* holds info about a machine */
	struct sockaddr_in Address;  /* Internet socket address stuct */
	long nHostAddress;
	char pBuffer[BUFFER_SIZE];
	unsigned nReadAmount;
	char strHostName[HOST_NAME_SIZE];
	int nHostPort;


	int c;
	int download_times = 1;
	int cFlag = 0;
	int dFlag = 0;
	int SuccessfulDownloads = 0;
	int FailedDownloads = 0;
	char *path;
	char contentType[MAX_MSG_SZ];
	vector<char *> headerLines;
	
	if (argc < 4 || argc > 6)
	{
		printf("\nUsage: download host port path [-c #ofdownloads | -d]\n");
		return 0;
	}
	else
	{
		while ((c = getopt(argc, argv, "c:d")) != -1)
		{
			switch (c)
			{
				case 'c':
					download_times = atoi(optarg);
					cFlag = 1;
					break;
				case 'd':
					dFlag = 1;
					break;
				default:
					perror("\nUsage: download host port path [-c #ofdownloads | -d]\n");
					return -1;
			}
		}
		//if there aren't 3 arguments after the option there is an error
		if (argc - optind != 3)
		{
			perror("\nUsage: download host port path [-c #ofdownload | -d]\n");
		}
		//if we are supposed to debug output 
		if (dFlag)
		{
			printf("download_times = %d, printHeaders = %d\n", download_times, dFlag);
		}
		//copy hostname from arugments
		strcpy(strHostName, argv[optind++]);
		//copy portname from arguments
		std::string port = argv[optind++];
		//make sure port is only digits and then copy
		if (port.find_first_not_of("0123456789") != string::npos)
		{
			perror("Port must only contain numbers.\n");
			return -1;
		}
		else
		{
			nHostPort = atoi(&port[0]);
		}
		
		//copy path from arugments
		path = argv[optind];
	}

	//until it has been downloaded the proper amount of times, repeat process
	while (FailedDownloads + SuccessfulDownloads < download_times)
	{
		if (dFlag)
		{
			printf("\nMaking a socket.\n");
		}

		/* make a socket */
		hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

		if (hSocket == SOCKET_ERROR)
		{
			perror("\nCould not make a socket.\n");
			return -1;
		}

		/* get IP address from name */
		pHostInfo = gethostbyname(strHostName);
		if (pHostInfo == NULL)
		{
			perror("\nCouldn't connect to host, because of IP address.\n");
			return -1;
		}

		/* copy address into long */
		memcpy(&nHostAddress, pHostInfo->h_addr, pHostInfo->h_length);

		/* fill address struct */	
		Address.sin_addr.s_addr = nHostAddress;
		Address.sin_port = htons(nHostPort);
		Address.sin_family = AF_INET;

		if(dFlag)
		{
			printf("\nConnecting to host:%s",strHostName);
		}

		/* connect to host */
		if (connect(hSocket, (struct sockaddr *) &Address, sizeof(Address)) == SOCKET_ERROR)
		{
			perror("\nCould not connect to host, because of Socket error\n");
			return -1;
		}

		// Create HTTP Message
		char *message = (char *) malloc(MAX_GET);
		sprintf(message, "GET %s HTTP/1.1\r\nHost:%s:%d\r\n\r\n", path, strHostName, nHostPort);

		// Send Message
		if (dFlag)
		{
			printf("Request to server: %s\n", message);
		}
		write(hSocket, message, strlen(message));

		// Read the status line of response
		char *startLine = GetLine(hSocket);
		if (dFlag)
		{
			printf("Status: %s.\n\n", startLine);
		}
		char status[2];
		status[0] = startLine[strlen(startLine) - 2];
		status[1] = startLine[strlen(startLine) - 1];
		//if end of status line is Not Fou  "nd" then print error
		if (status[0] == 'n' && status[1] == 'd')	
		{
			perror("Couldn't reach address.");
			return -1;
		}

		// Read the header lines
		headerLines.clear();	
		GetHeaderLines(headerLines, hSocket, false);
		if (dFlag)
		{
			// Now print them out
			for (int i = 0; i < headerLines.size(); i++)
			{
				printf("%s\n", headerLines[i]);
				if (strstr(headerLines[i], "Content-Type"))		
				{
					sscanf(headerLines[i], "Content-Type: %s", contentType);
				}		
			}
			printf("\n=======================\n");
			printf("Headers are finished, now read the file.\n");
			printf("Content Type is %s\n", contentType);
			printf("=======================\n\n");
		}

		// Now read and print the rest of the file
		if (!cFlag)
		{
			int rval;
			try
			{
				while ((rval = read(hSocket, pBuffer, MAX_MSG_SZ)) > 0)
				{
					write(1, pBuffer, (unsigned int) rval);
				}
			}
			catch (...)
			{
				perror("Error while writing file body.");
				return -1;
			}
		}

		/* close socket */
		if (dFlag)
		{
			printf("\nClosing socket.\n");
		}
		if (close(hSocket) == SOCKET_ERROR)
		{
			perror("\nCould not close socket.\n");
			return -1;
		}
        
		// Check to see if status gave the OK signal. If so, it was succssful
		if (status[0] == 'O' && status[1] == 'K')
		{
			SuccessfulDownloads++;
		}
		else
		{
			FailedDownloads++;
		}
	}
	if (cFlag)
	printf("\nSucceeded in Downloading file %d times. Failed to Download %d times.\n", SuccessfulDownloads, FailedDownloads);
}
Example #4
0
void serve(int hSocket){


	vector<char*> headers;
	GetHeaderLines(headers, hSocket, false);
	
	for(int i=0; i<headers.size(); i++){
		cout << headers[i] << endl;
	}
	cout << "**********" << endl;


	//set content type and length

//parse the get request use stat to determine type of request (folder, regular file, invalid 4040

//

	char pBuffer[BUFFER_SIZE];
	memset(pBuffer, 0, sizeof(pBuffer));

	int file_size = get_fiel_size("maxresdefault.jpg");
	sprintf(pBuffer, "HTTP/1.1 200 OK\r\nContent-Type: image/jpg\r\nContent-Lengh: %d\r\n\r\n", file_size);
//alwasys check system calls
	write(hSocket, pBuffer, strlen(pBuffer));
	FILE* fp = fopen("maxresdefault.jpg", "r");
	
	char *buffer = (char*)malloc(file_size); 
	fread(buffer, file_size, 1, fp);
//check above
	
	write(hSocket, buffer, file_size);


dfd

	std::string msg = ss.str();
	std::cout << "write" << std:: endl;
//	write(hSocket, msg.c_str(), msg.size());
	std::cout << "finished writing" << std:: endl;


	shutdown(hSocket, SHUT-RDWR);
	close(hSocket);
	string pBuffer = "HTTP/1.1 200 OK\nContent-Type: text/plain\nContent-Length: 9\r\n\r\nHeyGuys!";
        /* number returned by read() and write() is the number of bytes
        ** read or written, with -1 being that an error occured
        ** write what we received back to the server */
        write(hSocket,pBuffer.c_str(),pBuffer.length());


	cout << "*******************************" << endl;


    printf("\nClosing the socket");
        /* close socket */
        if(close(hSocket) == SOCKET_ERROR)
        {
         printf("\nCould not close socket\n");
         exit(0);
        }
}