Refactoring, fix

This commit is contained in:
Ugo Cirmignani
2018-03-11 05:26:45 -07:00
parent 45a9cbf091
commit a612652d15
27 changed files with 390 additions and 432 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -50,15 +50,12 @@ int parseCommandUser(clientDataType *theClientData)
char *theName; char *theName;
theName = getFtpCommandArg("USER", theClientData->theCommandReceived); theName = getFtpCommandArg("USER", theClientData->theCommandReceived);
printTimeStamp();
printf("The Name: %s", theName);
if (strlen(theName) >= 1) if (strlen(theName) >= 1)
{ {
char *theResponse = "331 User ok, Waiting for the password.\r\n"; char *theResponse = "331 User ok, Waiting for the password.\r\n";
setDynamicStringDataType(&theClientData->login.name, theName, strlen(theName)); setDynamicStringDataType(&theClientData->login.name, theName, strlen(theName));
write(theClientData->socketDescriptor, theResponse, strlen(theResponse)); write(theClientData->socketDescriptor, theResponse, strlen(theResponse));
printf("\nUSER COMMAND OK, USERNAME IS: %s", theClientData->login.name.text); //printf("\nUSER COMMAND OK, USERNAME IS: %s", theClientData->login.name.text);
return 1; return 1;
} }
else else
@ -75,10 +72,7 @@ int parseCommandSite(clientDataType *theClientData)
char *theCommand; char *theCommand;
theCommand = getFtpCommandArg("SITE", theClientData->theCommandReceived); theCommand = getFtpCommandArg("SITE", theClientData->theCommandReceived);
printTimeStamp(); if(compareStringCaseInsensitive(theCommand, "CHMOD", strlen("CHMOD")) == 1)
printf("\ntheCommand:%s", theCommand);
if(strncmp(theCommand, "CHMOD", strlen("CHMOD")) == 0 ||
strncmp(theCommand, "chmod", strlen("chmod")) == 0)
{ {
setPermissions(theCommand, theClientData->login.absolutePath.text); setPermissions(theCommand, theClientData->login.absolutePath.text);
char *theResponse = "200 Permissions changed\r\n"; char *theResponse = "200 Permissions changed\r\n";
@ -89,21 +83,18 @@ int parseCommandSite(clientDataType *theClientData)
char *theResponse = "500 unknown extension\r\n"; char *theResponse = "500 unknown extension\r\n";
write(theClientData->socketDescriptor, theResponse, strlen(theResponse)); write(theClientData->socketDescriptor, theResponse, strlen(theResponse));
} }
return 1;
//site chmod 777 test //site chmod 777 test
//200 Permissions changed on test //200 Permissions changed on test
//500 SITE ciao is an unknown extension //500 SITE ciao is an unknown extension
return 1;
} }
int parseCommandPass(ftpDataType * data, int socketId) int parseCommandPass(ftpDataType * data, int socketId)
{ {
char *thePass; char *thePass;
thePass = getFtpCommandArg("PASS", data->clients[socketId].theCommandReceived); thePass = getFtpCommandArg("PASS", data->clients[socketId].theCommandReceived);
printTimeStamp();
printf("The Pass is: %s", thePass);
if (strlen(thePass) >= 1) if (strlen(thePass) >= 1)
{ {
@ -115,7 +106,7 @@ int parseCommandPass(ftpDataType * data, int socketId)
{ {
char *theResponse = "430 Invalid username or password\r\n"; char *theResponse = "430 Invalid username or password\r\n";
write(data->clients[socketId].socketDescriptor, theResponse, strlen(theResponse)); write(data->clients[socketId].socketDescriptor, theResponse, strlen(theResponse));
printf("\nLogin Error recorded no such username or password"); //printf("\nLogin Error recorded no such username or password");
} }
else else
{ {
@ -129,12 +120,12 @@ int parseCommandPass(ftpDataType * data, int socketId)
write(data->clients[socketId].socketDescriptor, theResponse, strlen(theResponse)); write(data->clients[socketId].socketDescriptor, theResponse, strlen(theResponse));
printTimeStamp(); printTimeStamp();
printf("PASS COMMAND OK, PASSWORD IS: %s", data->clients[socketId].login.password.text); //printf("PASS COMMAND OK, PASSWORD IS: %s", data->clients[socketId].login.password.text);
printf("\nheClientData->login.homePath: %s", data->clients[socketId].login.homePath.text); //printf("\nheClientData->login.homePath: %s", data->clients[socketId].login.homePath.text);
printf("\nheClientData->login.ftpPath: %s", data->clients[socketId].login.ftpPath.text); //printf("\nheClientData->login.ftpPath: %s", data->clients[socketId].login.ftpPath.text);
printf("\nheClientData->login.absolutePath: %s", data->clients[socketId].login.absolutePath.text); //printf("\nheClientData->login.absolutePath: %s", data->clients[socketId].login.absolutePath.text);
} }
return 1; return 1;
} }
else else
@ -147,10 +138,10 @@ int parseCommandPass(ftpDataType * data, int socketId)
int parseCommandAuth(clientDataType *theClientData) int parseCommandAuth(clientDataType *theClientData)
{ {
char *theAuth; //char *theAuth;
theAuth = getFtpCommandArg("AUTH", theClientData->theCommandReceived); //theAuth = getFtpCommandArg("AUTH", theClientData->theCommandReceived);
printTimeStamp(); //printTimeStamp();
printf("The Auth is: %s", theAuth); //printf("The Auth is: %s", theAuth);
char *theResponse = "502 Security extensions not implemented.\r\n"; char *theResponse = "502 Security extensions not implemented.\r\n";
write(theClientData->socketDescriptor, theResponse, strlen(theResponse)); write(theClientData->socketDescriptor, theResponse, strlen(theResponse));
return 1; return 1;
@ -239,7 +230,7 @@ int parseCommandPasv(ftpDataType * data, int socketId)
void *pReturn; void *pReturn;
pthread_cancel(data->clients[socketId].workerData.workerThread); pthread_cancel(data->clients[socketId].workerData.workerThread);
pthread_join(data->clients[socketId].workerData.workerThread, &pReturn); pthread_join(data->clients[socketId].workerData.workerThread, &pReturn);
printf("\nThread has been cancelled."); //printf("\nThread has been cancelled.");
} }
else else
{ {
@ -261,11 +252,11 @@ int parseCommandPort(ftpDataType * data, int socketId)
int portBytes[2]; int portBytes[2];
theIpAndPort = getFtpCommandArg("PORT", data->clients[socketId].theCommandReceived); theIpAndPort = getFtpCommandArg("PORT", data->clients[socketId].theCommandReceived);
sscanf(theIpAndPort, "%d,%d,%d,%d,%d,%d", &ipAddressBytes[0], &ipAddressBytes[1], &ipAddressBytes[2], &ipAddressBytes[3], &portBytes[0], &portBytes[1]); sscanf(theIpAndPort, "%d,%d,%d,%d,%d,%d", &ipAddressBytes[0], &ipAddressBytes[1], &ipAddressBytes[2], &ipAddressBytes[3], &portBytes[0], &portBytes[1]);
printf("\ntheIpAndPort: %s", theIpAndPort); //printf("\ntheIpAndPort: %s", theIpAndPort);
data->clients[socketId].workerData.connectionPort = (portBytes[0]*256)+portBytes[1]; data->clients[socketId].workerData.connectionPort = (portBytes[0]*256)+portBytes[1];
sprintf(data->clients[socketId].workerData.activeIpAddress, "%d.%d.%d.%d", ipAddressBytes[0],ipAddressBytes[1],ipAddressBytes[2],ipAddressBytes[3]); sprintf(data->clients[socketId].workerData.activeIpAddress, "%d.%d.%d.%d", ipAddressBytes[0],ipAddressBytes[1],ipAddressBytes[2],ipAddressBytes[3]);
printf("\ndata->clients[socketId].workerData.connectionPort: %d", data->clients[socketId].workerData.connectionPort); //printf("\ndata->clients[socketId].workerData.connectionPort: %d", data->clients[socketId].workerData.connectionPort);
printf("\ndata->clients[socketId].workerData.activeIpAddress: %s", data->clients[socketId].workerData.activeIpAddress); //printf("\ndata->clients[socketId].workerData.activeIpAddress: %s", data->clients[socketId].workerData.activeIpAddress);
/* Create worker thread */ /* Create worker thread */
if (data->clients[socketId].workerData.threadIsAlive == 1) if (data->clients[socketId].workerData.threadIsAlive == 1)
@ -273,7 +264,7 @@ int parseCommandPort(ftpDataType * data, int socketId)
void *pReturn; void *pReturn;
pthread_cancel(data->clients[socketId].workerData.workerThread); pthread_cancel(data->clients[socketId].workerData.workerThread);
pthread_join(data->clients[socketId].workerData.workerThread, &pReturn); pthread_join(data->clients[socketId].workerData.workerThread, &pReturn);
printf("\nThread has been cancelled."); //printf("\nThread has been cancelled.");
} }
else else
{ {
@ -306,7 +297,7 @@ int parseCommandAbor(ftpDataType * data, int socketId)
void *pReturn; void *pReturn;
pthread_cancel(data->clients[socketId].workerData.workerThread); pthread_cancel(data->clients[socketId].workerData.workerThread);
pthread_join(data->clients[socketId].workerData.workerThread, &pReturn); pthread_join(data->clients[socketId].workerData.workerThread, &pReturn);
printf("\nThread has been cancelled due to ABOR request."); //printf("\nThread has been cancelled due to ABOR request.");
memset(theResponse, 0, FTP_COMMAND_ELABORATE_CHAR_BUFFER); memset(theResponse, 0, FTP_COMMAND_ELABORATE_CHAR_BUFFER);
sprintf(theResponse, "426 ABORT\r\n"); sprintf(theResponse, "426 ABORT\r\n");
@ -345,17 +336,14 @@ int parseCommandList(ftpDataType * data, int socketId)
-t Sort by modification time -t Sort by modification time
*/ */
int isSafePath = 0; int isSafePath = 0;
char *theNameToList; char *theNameToList;
theNameToList = getFtpCommandArg("LIST", data->clients[socketId].theCommandReceived); theNameToList = getFtpCommandArg("LIST", data->clients[socketId].theCommandReceived);
getFtpCommandArgWithOptions("LIST", data->clients[socketId].theCommandReceived, &data->clients[socketId].workerData.ftpCommand); getFtpCommandArgWithOptions("LIST", data->clients[socketId].theCommandReceived, &data->clients[socketId].workerData.ftpCommand);
printf("\nLIST COMMAND ARG: %s", data->clients[socketId].workerData.ftpCommand.commandArgs.text); // printf("\nLIST COMMAND ARG: %s", data->clients[socketId].workerData.ftpCommand.commandArgs.text);
printf("\nLIST COMMAND OPS: %s", data->clients[socketId].workerData.ftpCommand.commandOps.text); // printf("\nLIST COMMAND OPS: %s", data->clients[socketId].workerData.ftpCommand.commandOps.text);
cleanDynamicStringDataType(&data->clients[socketId].workerData.ftpCommand.commandArgs, 0); cleanDynamicStringDataType(&data->clients[socketId].workerData.ftpCommand.commandArgs, 0);
cleanDynamicStringDataType(&data->clients[socketId].workerData.ftpCommand.commandOps, 0); cleanDynamicStringDataType(&data->clients[socketId].workerData.ftpCommand.commandOps, 0);
@ -454,7 +442,7 @@ int parseCommandStor(ftpDataType * data, int socketId)
if (isSafePath == 1) if (isSafePath == 1)
{ {
pthread_mutex_lock(&data->clients[socketId].workerData.conditionMutex); pthread_mutex_lock(&data->clients[socketId].workerData.conditionMutex);
printf("data->clients[%d].fileToStor = %s", socketId, data->clients[socketId].fileToStor.text); //printf("data->clients[%d].fileToStor = %s", socketId, data->clients[socketId].fileToStor.text);
memset(data->clients[socketId].workerData.theCommandReceived, 0, CLIENT_COMMAND_STRING_SIZE); memset(data->clients[socketId].workerData.theCommandReceived, 0, CLIENT_COMMAND_STRING_SIZE);
strcpy(data->clients[socketId].workerData.theCommandReceived, data->clients[socketId].theCommandReceived); strcpy(data->clients[socketId].workerData.theCommandReceived, data->clients[socketId].theCommandReceived);
data->clients[socketId].workerData.commandReceived = 1; data->clients[socketId].workerData.commandReceived = 1;
@ -529,7 +517,7 @@ int parseCommandCwd(clientDataType *theClientData)
if (FILE_IsDirectory(theClientData->login.absolutePath.text) == 1) if (FILE_IsDirectory(theClientData->login.absolutePath.text) == 1)
{ {
printf("\nDirectory ok found, theClientData->login.ftpPath.text = %s", theClientData->login.ftpPath.text); //printf("\nDirectory ok found, theClientData->login.ftpPath.text = %s", theClientData->login.ftpPath.text);
int theSizeToMalloc = strlen("250 OK. Current directory is ")+theClientData->login.ftpPath.textLen+1; int theSizeToMalloc = strlen("250 OK. Current directory is ")+theClientData->login.ftpPath.textLen+1;
theResponse = (char *) malloc (theSizeToMalloc); theResponse = (char *) malloc (theSizeToMalloc);
memset(theResponse, 0, theSizeToMalloc); memset(theResponse, 0, theSizeToMalloc);
@ -538,7 +526,7 @@ int parseCommandCwd(clientDataType *theClientData)
} }
else else
{ {
printf("\n%s does not exist", theClientData->login.absolutePath.text); //printf("\n%s does not exist", theClientData->login.absolutePath.text);
setDynamicStringDataType(&theClientData->login.absolutePath, absolutePathPrevious.text, absolutePathPrevious.textLen); setDynamicStringDataType(&theClientData->login.absolutePath, absolutePathPrevious.text, absolutePathPrevious.textLen);
setDynamicStringDataType(&theClientData->login.ftpPath, ftpPathPrevious.text, ftpPathPrevious.textLen); setDynamicStringDataType(&theClientData->login.ftpPath, ftpPathPrevious.text, ftpPathPrevious.textLen);
int theSizeToMalloc = strlen("550 Can't change directory to : No such file or directory")+10+strlen(theClientData->login.ftpPath.text); int theSizeToMalloc = strlen("550 Can't change directory to : No such file or directory")+10+strlen(theClientData->login.ftpPath.text);
@ -553,9 +541,9 @@ int parseCommandCwd(clientDataType *theClientData)
write(theClientData->socketDescriptor, theResponse, strlen(theResponse)); write(theClientData->socketDescriptor, theResponse, strlen(theResponse));
printTimeStamp(); printTimeStamp();
printf("\nCwd response : %s", theResponse); //printf("\nCwd response : %s", theResponse);
printf("\nUSER COMMAND OK, NEW PATH IS: %s", theClientData->login.absolutePath.text); //printf("\nUSER COMMAND OK, NEW PATH IS: %s", theClientData->login.absolutePath.text);
printf("\nUSER COMMAND OK, NEW LOCAL PATH IS: %s", theClientData->login.ftpPath.text); //printf("\nUSER COMMAND OK, NEW LOCAL PATH IS: %s", theClientData->login.ftpPath.text);
cleanDynamicStringDataType(&absolutePathPrevious, 0); cleanDynamicStringDataType(&absolutePathPrevious, 0);
cleanDynamicStringDataType(&ftpPathPrevious, 0); cleanDynamicStringDataType(&ftpPathPrevious, 0);
@ -608,9 +596,6 @@ int parseCommandRest(clientDataType *theClientData)
} }
} }
printTimeStamp();
printf(" REST set to: %s", theSize);
fflush(0);
FILE_AppendToString(&theResponse, theSize); FILE_AppendToString(&theResponse, theSize);
FILE_AppendToString(&theResponse, " \r\n"); FILE_AppendToString(&theResponse, " \r\n");
@ -627,7 +612,7 @@ int parseCommandMkd(clientDataType *theClientData)
char *theDirectoryFilename; char *theDirectoryFilename;
dynamicStringDataType theResponse; dynamicStringDataType theResponse;
dynamicStringDataType mkdFileName; dynamicStringDataType mkdFileName;
theDirectoryFilename = getFtpCommandArg("MKD", theClientData->theCommandReceived); theDirectoryFilename = getFtpCommandArg("MKD", theClientData->theCommandReceived);
cleanDynamicStringDataType(&theResponse, 1); cleanDynamicStringDataType(&theResponse, 1);
@ -638,7 +623,7 @@ int parseCommandMkd(clientDataType *theClientData)
if (isSafePath == 1) if (isSafePath == 1)
{ {
int returnStatus; int returnStatus;
printf("\nThe directory to make is: %s", mkdFileName.text); //printf("\nThe directory to make is: %s", mkdFileName.text);
returnStatus = mkdir(mkdFileName.text, S_IRWXU | S_IRWXG | S_IRWXO); returnStatus = mkdir(mkdFileName.text, S_IRWXU | S_IRWXG | S_IRWXO);
setDynamicStringDataType(&theResponse, "257 \"", strlen("257 \"")); setDynamicStringDataType(&theResponse, "257 \"", strlen("257 \""));
appendToDynamicStringDataType(&theResponse, theDirectoryFilename, strlen(theDirectoryFilename)); appendToDynamicStringDataType(&theResponse, theDirectoryFilename, strlen(theDirectoryFilename));
@ -659,9 +644,9 @@ int parseCommandMkd(clientDataType *theClientData)
int parseCommandOpts(clientDataType *theClientData) int parseCommandOpts(clientDataType *theClientData)
{ {
char *theCommand; //char *theCommand;
theCommand = getFtpCommandArg("OPTS", theClientData->theCommandReceived); //theCommand = getFtpCommandArg("OPTS", theClientData->theCommandReceived);
printf("\nThe command received: %s", theCommand); //printf("\nThe command received: %s", theCommand);
char *theResponse = "200 OK\r\n"; char *theResponse = "200 OK\r\n";
write(theClientData->socketDescriptor, theResponse, strlen(theResponse)); write(theClientData->socketDescriptor, theResponse, strlen(theResponse));
return 1; return 1;
@ -684,7 +669,7 @@ int parseCommandDele(clientDataType *theClientData)
if (isSafePath == 1) if (isSafePath == 1)
{ {
printf("\nThe file to delete is: %s", deleFileName.text); //printf("\nThe file to delete is: %s", deleFileName.text);
returnStatus = remove(deleFileName.text); returnStatus = remove(deleFileName.text);
setDynamicStringDataType(&theResponse, "250 Deleted ", strlen("250 Deleted ")); setDynamicStringDataType(&theResponse, "250 Deleted ", strlen("250 Deleted "));
appendToDynamicStringDataType(&theResponse, theFileToDelete, strlen(theFileToDelete)); appendToDynamicStringDataType(&theResponse, theFileToDelete, strlen(theFileToDelete));
@ -744,7 +729,7 @@ int parseCommandRmd(clientDataType *theClientData)
if (isSafePath == 1) if (isSafePath == 1)
{ {
printf("\nThe directory to delete is: %s", rmdFileName.text); //printf("\nThe directory to delete is: %s", rmdFileName.text);
returnStatus = rmdir(rmdFileName.text); returnStatus = rmdir(rmdFileName.text);
setDynamicStringDataType(&theResponse, "250 The directory was successfully removed\r\n", strlen("250 The directory was successfully removed\r\n")); setDynamicStringDataType(&theResponse, "250 The directory was successfully removed\r\n", strlen("250 The directory was successfully removed\r\n"));
write(theClientData->socketDescriptor, theResponse.text, theResponse.textLen); write(theClientData->socketDescriptor, theResponse.text, theResponse.textLen);
@ -780,7 +765,7 @@ int parseCommandSize(clientDataType *theClientData)
if (isSafePath == 1) if (isSafePath == 1)
{ {
printf("\nThe file to get the size is: %s", getSizeFromFileName.text); // printf("\nThe file to get the size is: %s", getSizeFromFileName.text);
if (FILE_IsFile(getSizeFromFileName.text)==1) if (FILE_IsFile(getSizeFromFileName.text)==1)
{ {
@ -824,7 +809,7 @@ int parseCommandRnfr(clientDataType *theClientData)
(FILE_IsFile(theClientData->renameFromFile.text) == 1 || (FILE_IsFile(theClientData->renameFromFile.text) == 1 ||
FILE_IsDirectory(theClientData->renameFromFile.text) == 1)) FILE_IsDirectory(theClientData->renameFromFile.text) == 1))
{ {
printf("\nThe file to check is: %s", theClientData->renameFromFile.text); // printf("\nThe file to check is: %s", theClientData->renameFromFile.text);
if (FILE_IsFile(theClientData->renameFromFile.text) == 1 || if (FILE_IsFile(theClientData->renameFromFile.text) == 1 ||
FILE_IsDirectory(theClientData->renameFromFile.text) == 1) FILE_IsDirectory(theClientData->renameFromFile.text) == 1)
@ -862,7 +847,7 @@ int parseCommandRnto(clientDataType *theClientData)
if (isSafePath == 1 && if (isSafePath == 1 &&
theClientData->renameFromFile.textLen > 0) theClientData->renameFromFile.textLen > 0)
{ {
printf("\nThe file to check is: %s", theClientData->renameFromFile.text); // printf("\nThe file to check is: %s", theClientData->renameFromFile.text);
if (FILE_IsFile(theClientData->renameFromFile.text) == 1 || if (FILE_IsFile(theClientData->renameFromFile.text) == 1 ||
FILE_IsDirectory(theClientData->renameFromFile.text) == 1) FILE_IsDirectory(theClientData->renameFromFile.text) == 1)
@ -913,9 +898,9 @@ int parseCommandCdup(clientDataType *theClientData)
FILE_AppendToString(&theResponse, " \r\n"); FILE_AppendToString(&theResponse, " \r\n");
write(theClientData->socketDescriptor, theResponse, strlen(theResponse)); write(theClientData->socketDescriptor, theResponse, strlen(theResponse));
printTimeStamp(); // printTimeStamp();
printf("USER COMMAND OK, NEW PATH IS: %s", theClientData->login.absolutePath.text); // printf("USER COMMAND OK, NEW PATH IS: %s", theClientData->login.absolutePath.text);
printf("\nUSER COMMAND OK, NEW LOCAL PATH IS: %s", theClientData->login.ftpPath.text); //printf("\nUSER COMMAND OK, NEW LOCAL PATH IS: %s", theClientData->login.ftpPath.text);
free(theResponse); free(theResponse);
return 1; return 1;
} }
@ -929,7 +914,7 @@ int writeRetrFile(char * theFilename, int thePasvSocketConnection, int startFrom
long long int theFileSize; long long int theFileSize;
char buffer[FTP_COMMAND_ELABORATE_CHAR_BUFFER]; char buffer[FTP_COMMAND_ELABORATE_CHAR_BUFFER];
printf("\nOpening: %s", theFilename); //printf("\nOpening: %s", theFilename);
retrFP = fopen(theFilename, "rb"); retrFP = fopen(theFilename, "rb");
if (retrFP == NULL) if (retrFP == NULL)
@ -942,9 +927,9 @@ int writeRetrFile(char * theFilename, int thePasvSocketConnection, int startFrom
if (startFrom > 0) if (startFrom > 0)
{ {
printf("\nSeek startFrom: %d", startFrom); //printf("\nSeek startFrom: %d", startFrom);
currentPosition = (long int) lseek(fileno(retrFP), startFrom, SEEK_SET); currentPosition = (long int) lseek(fileno(retrFP), startFrom, SEEK_SET);
printf("\nSeek result: %ld", currentPosition); // printf("\nSeek result: %ld", currentPosition);
if (currentPosition == -1) if (currentPosition == -1)
{ {
fclose(retrFP); fclose(retrFP);
@ -957,7 +942,7 @@ int writeRetrFile(char * theFilename, int thePasvSocketConnection, int startFrom
toReturn = toReturn + write(thePasvSocketConnection, buffer, readen); toReturn = toReturn + write(thePasvSocketConnection, buffer, readen);
} }
printf("\n Bytes written: %ld", toReturn); //printf("\n Bytes written: %ld", toReturn);
fclose(retrFP); fclose(retrFP);
return toReturn; return toReturn;
@ -1066,7 +1051,6 @@ int getFtpCommandArgWithOptions(char * theCommand, char *theCommandString, ftpCo
setDynamicStringDataType(&ftpCommand->commandOps, argSecondary, argSecondaryIndex); setDynamicStringDataType(&ftpCommand->commandOps, argSecondary, argSecondaryIndex);
return 1; return 1;
} }
int setPermissions(char * permissionsCommand, char * basePath) int setPermissions(char * permissionsCommand, char * basePath)
@ -1118,15 +1102,15 @@ int setPermissions(char * permissionsCommand, char * basePath)
permissionsCommandCursor++; permissionsCommandCursor++;
} }
printf("\n thePermissionString = %s ", thePermissionString); //printf("\n thePermissionString = %s ", thePermissionString);
printf("\n theLocalPathCursor = %s ", theLocalPath); //printf("\n theLocalPathCursor = %s ", theLocalPath);
if (basePath[strlen(basePath)-1] != '/') if (basePath[strlen(basePath)-1] != '/')
sprintf(theFinalCommand, "chmod %s %s/%s", thePermissionString, basePath, theLocalPath); sprintf(theFinalCommand, "chmod %s %s/%s", thePermissionString, basePath, theLocalPath);
else else
sprintf(theFinalCommand, "chmod %s %s%s", thePermissionString, basePath, theLocalPath); sprintf(theFinalCommand, "chmod %s %s%s", thePermissionString, basePath, theLocalPath);
printf("\n theFinalCommand = %s ", theFinalCommand); //printf("\n theFinalCommand = %s ", theFinalCommand);
system(theFinalCommand); system(theFinalCommand);

View File

@ -23,20 +23,6 @@
*/ */
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: ftpCommandsElaborate.h
* Author: ugo
*
* Created on 8 ottobre 2017, 12.40
*/
#ifndef FTPCOMMANDSELABORATE_H #ifndef FTPCOMMANDSELABORATE_H
#define FTPCOMMANDSELABORATE_H #define FTPCOMMANDSELABORATE_H

View File

@ -178,14 +178,12 @@ int getSafePath(dynamicStringDataType *safePath, char *theDirectoryName, loginDa
void appendToDynamicStringDataType(dynamicStringDataType *dynamicString, char *theString, int stringLen) void appendToDynamicStringDataType(dynamicStringDataType *dynamicString, char *theString, int stringLen)
{ {
printf("\n Appending in %s --> %s", dynamicString->text, theString);
int theNewSize = dynamicString->textLen + stringLen; int theNewSize = dynamicString->textLen + stringLen;
dynamicString->text = realloc(dynamicString->text, theNewSize + 1); dynamicString->text = realloc(dynamicString->text, theNewSize + 1);
memset(dynamicString->text+dynamicString->textLen, 0, stringLen+1); memset(dynamicString->text+dynamicString->textLen, 0, stringLen+1);
memcpy(dynamicString->text+dynamicString->textLen, theString, stringLen); memcpy(dynamicString->text+dynamicString->textLen, theString, stringLen);
dynamicString->text[theNewSize] = '\0'; dynamicString->text[theNewSize] = '\0';
dynamicString->textLen = theNewSize; dynamicString->textLen = theNewSize;
printf("\n Append done --> %s", dynamicString->text);
} }
void setRandomicPort(ftpDataType *data, int socketPosition) void setRandomicPort(ftpDataType *data, int socketPosition)
@ -193,7 +191,6 @@ void setRandomicPort(ftpDataType *data, int socketPosition)
static unsigned short int randomizeInteger = 0; static unsigned short int randomizeInteger = 0;
unsigned short int randomicPort = 5000; unsigned short int randomicPort = 5000;
int i; int i;
time_t t;
randomizeInteger += 7; randomizeInteger += 7;
@ -206,13 +203,12 @@ void setRandomicPort(ftpDataType *data, int socketPosition)
randomicPort = ((rand() + socketPosition + randomizeInteger) % (10000 - 50000)) + 10000; randomicPort = ((rand() + socketPosition + randomizeInteger) % (10000 - 50000)) + 10000;
i = 0; i = 0;
printf("randomicPort = %d", randomicPort);
while (i < data->ftpParameters.maxClients) while (i < data->ftpParameters.maxClients)
{ {
if (randomicPort == data->clients[i].workerData.connectionPort) if (randomicPort == data->clients[i].workerData.connectionPort)
{ {
printf("randomicPort already in use = %d", randomicPort);
randomicPort = ((rand() + socketPosition + i + randomizeInteger) % (10000 - 50000)) + 10000; randomicPort = ((rand() + socketPosition + i + randomizeInteger) % (10000 - 50000)) + 10000;
i = 0; i = 0;
} }
@ -262,7 +258,7 @@ void getListDataInfo(char * thePath, DYNV_VectorGenericDataType *directoryInfo)
} }
if (data.isDirectory == 0 && data.isFile == 0) if (data.isDirectory == 0 && data.isFile == 0)
{ {
printf("\nNot a directory, not a file, broken link"); //printf("\nNot a directory, not a file, broken link");
continue; continue;
} }
@ -344,58 +340,36 @@ void deleteListDataInfoVector(void *TheElementToDelete)
{ {
ftpListDataType *data = (ftpListDataType *)TheElementToDelete; ftpListDataType *data = (ftpListDataType *)TheElementToDelete;
if (data->owner != NULL) if (data->owner != NULL)
{ {
printf("\nDeleting data->owner:%s", data->owner);
fflush(0);
free(data->owner); free(data->owner);
} }
printf("\nDone");
fflush(0);
if (data->groupOwner != NULL) if (data->groupOwner != NULL)
{ {
printf("\nDeleting data->groupOwner:%s", data->groupOwner);
fflush(0);
free(data->groupOwner); free(data->groupOwner);
} }
printf("\nDone");
fflush(0);
if (data->inodePermissionString != NULL) if (data->inodePermissionString != NULL)
{ {
printf("\nDeleting data->inodePermissionString:%s", data->inodePermissionString);
fflush(0);
free(data->inodePermissionString); free(data->inodePermissionString);
} }
printf("\nDone");
fflush(0);
if (data->fileNameWithPath != NULL) if (data->fileNameWithPath != NULL)
{ {
printf("\nDeleting data->fileNameWithPath:%s", data->fileNameWithPath);
fflush(0);
free(data->fileNameWithPath); free(data->fileNameWithPath);
} }
printf("\nDone");
fflush(0);
if (data->finalStringPath != NULL) if (data->finalStringPath != NULL)
{ {
printf("\nDeleting data->finalStringPath:%s", data->finalStringPath);
fflush(0);
free(data->finalStringPath); free(data->finalStringPath);
} }
printf("\nDone");
fflush(0);
if (data->linkPath != NULL) if (data->linkPath != NULL)
{ {
printf("\nDeleting data->linkPath:%s", data->linkPath);
fflush(0);
free(data->linkPath); free(data->linkPath);
} }
printf("\nDone");
fflush(0);
} }
void resetWorkerData(workerDataType *workerData, int isInitialization) void resetWorkerData(workerDataType *workerData, int isInitialization)
@ -444,7 +418,7 @@ void resetClientData(clientDataType *clientData, int isInitialization)
void *pReturn; void *pReturn;
pthread_cancel(clientData->workerData.workerThread); pthread_cancel(clientData->workerData.workerThread);
pthread_join(clientData->workerData.workerThread, &pReturn); pthread_join(clientData->workerData.workerThread, &pReturn);
printf("\nThread has been cancelled."); //printf("\nThread has been cancelled.");
} }
else else
{ {
@ -492,4 +466,55 @@ void resetClientData(clientDataType *clientData, int isInitialization)
clientData->lastActivityTimeStamp = 0; clientData->lastActivityTimeStamp = 0;
}
int compareStringCaseInsensitive(char * stringIn, char * stringRef, int stringLenght)
{
int i = 0;
char * alfaLowerCase = "qwertyuiopasdfghjklzxcvbnm ";
char * alfaUpperCase = "QWERTYUIOPASDFGHJKLZXCVBNM ";
int stringInIndex;
int stringRefIndex;
for (i = 0; i <stringLenght; i++)
{
stringInIndex = isCharInString(alfaUpperCase, strlen(alfaUpperCase), stringIn[i]);
if (stringInIndex == -1)
{
stringInIndex = isCharInString(alfaLowerCase, strlen(alfaLowerCase), stringIn[i]);
}
stringRefIndex = isCharInString(alfaUpperCase, strlen(alfaUpperCase), stringRef[i]);
if (stringRefIndex == -1)
{
stringRefIndex = isCharInString(alfaLowerCase, strlen(alfaLowerCase), stringRef[i]);
}
if (stringRefIndex == -1 || stringInIndex == -1)
{
return 0;
}
if (stringRefIndex != stringInIndex)
{
return 0;
}
}
return 1;
}
int isCharInString(char *theString, int stringLen, char theChar)
{
int i;
for (i = 0; i < stringLen; i++)
{
if (theString[i] == theChar)
{
return i;
}
}
return -1;
} }

View File

@ -23,20 +23,6 @@
*/ */
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: ftpData.h
* Author: ugo
*
* Created on 8 ottobre 2017, 13.14
*/
#ifndef FTPDATA_H #ifndef FTPDATA_H
#define FTPDATA_H #define FTPDATA_H
@ -224,6 +210,8 @@ void getListDataInfo(char * thePath, DYNV_VectorGenericDataType *directoryInfo);
void deleteListDataInfoVector(void *TheElementToDelete); void deleteListDataInfoVector(void *TheElementToDelete);
void resetWorkerData(workerDataType *pasvData, int isInitialization); void resetWorkerData(workerDataType *pasvData, int isInitialization);
void resetClientData(clientDataType *clientData, int isInitialization); void resetClientData(clientDataType *clientData, int isInitialization);
int compareStringCaseInsensitive(char *stringIn, char* stringRef, int stringLenght);
int isCharInString(char *theString, int stringLen, char theChar);
#ifdef __cplusplus #ifdef __cplusplus
} }
#endif #endif

View File

@ -50,8 +50,6 @@
ftpDataType ftpData; ftpDataType ftpData;
static int processCommand(int processingElement); static int processCommand(int processingElement);
void workerCleanup(void *socketId) void workerCleanup(void *socketId)
@ -327,7 +325,6 @@ void *connectionWorkerHandle(void * socketId)
break; break;
} }
pthread_exit((void *)1); pthread_exit((void *)1);
pthread_cleanup_pop(0); pthread_cleanup_pop(0);
pthread_exit((void *)2); pthread_exit((void *)2);
@ -338,7 +335,7 @@ void *connectionWorkerHandle(void * socketId)
void runFtpServer(void) void runFtpServer(void)
{ {
/* Needed for Select*/ /* Needed for Select*/
static int processingSock = 0; static int processingSock = 0, returnCode = 0;
/* Handle signals */ /* Handle signals */
signalHandlerInstall(); signalHandlerInstall();
@ -346,7 +343,7 @@ void runFtpServer(void)
/*Read the configuration file */ /*Read the configuration file */
configurationRead(&ftpData.ftpParameters); configurationRead(&ftpData.ftpParameters);
/* apply the readen configuration */ /* apply the reden configuration */
applyConfiguration(&ftpData.ftpParameters); applyConfiguration(&ftpData.ftpParameters);
/* initialize the ftp data structure */ /* initialize the ftp data structure */
@ -359,12 +356,13 @@ void runFtpServer(void)
/* init fd set needed for select */ /* init fd set needed for select */
fdInit(&ftpData); fdInit(&ftpData);
/* the maximum socket fd is now the main socket descriptor */
ftpData.connectionData.maxSocketFD = ftpData.connectionData.theMainSocket+1; ftpData.connectionData.maxSocketFD = ftpData.connectionData.theMainSocket+1;
//Endless loop ftp process //Endless loop ftp process
while (1) while (1)
{ {
/* Check for socket activity, if timeout check maximum idle timeout */ /* waits for socket activity, if no activity then checks for client socket timeouts */
if (selectWait(&ftpData) == 0) if (selectWait(&ftpData) == 0)
{ {
checkClientConnectionTimeout(&ftpData); checkClientConnectionTimeout(&ftpData);
@ -380,82 +378,13 @@ void runFtpServer(void)
continue; continue;
} }
if (FD_ISSET(ftpData.connectionData.theMainSocket, &ftpData.connectionData.rset)) /* Check if there are client pending connections, accept the connection if possible otherwise reject */
{ returnCode = evaluateClientSocketConnection(&ftpData);
int socketIndex, availableSocketIndex;
availableSocketIndex = -1; /* no data to check client is not connected, continue to check other clients */
if (isClientConnected(&ftpData, processingSock) == 0)
for (socketIndex = 0; socketIndex < ftpData.ftpParameters.maxClients; socketIndex++)
{
if (ftpData.clients[socketIndex].socketDescriptor < 0 &&
ftpData.clients[socketIndex].socketIsConnected == 0 )
{
availableSocketIndex = socketIndex;
break;
}
}
if (availableSocketIndex != -1)
{
if ((ftpData.clients[availableSocketIndex].socketDescriptor = accept(ftpData.connectionData.theMainSocket, (struct sockaddr *)&ftpData.clients[availableSocketIndex].client_sockaddr_in, (socklen_t*)&ftpData.clients[availableSocketIndex].sockaddr_in_size))!=-1)
{
int error;
ftpData.connectedClients++;
ftpData.clients[availableSocketIndex].socketIsConnected = 1;
error = fcntl(ftpData.clients[availableSocketIndex].socketDescriptor, F_SETFL, O_NONBLOCK);
FD_SET(ftpData.clients[availableSocketIndex].socketDescriptor, &ftpData.connectionData.rsetAll);
FD_SET(ftpData.clients[availableSocketIndex].socketDescriptor, &ftpData.connectionData.wsetAll);
FD_SET(ftpData.clients[availableSocketIndex].socketDescriptor, &ftpData.connectionData.esetAll);
ftpData.connectionData.maxSocketFD = getMaximumSocketFd(ftpData.connectionData.theMainSocket, &ftpData) + 1;
error = getsockname(ftpData.clients[availableSocketIndex].socketDescriptor, (struct sockaddr *)&ftpData.clients[availableSocketIndex].server_sockaddr_in, (socklen_t*)&ftpData.clients[availableSocketIndex].sockaddr_in_server_size);
inet_ntop(AF_INET, &(ftpData.clients[availableSocketIndex].server_sockaddr_in.sin_addr), ftpData.clients[availableSocketIndex].serverIpAddress, INET_ADDRSTRLEN);
printf("\n Server IP: %s", ftpData.clients[availableSocketIndex].serverIpAddress);
printf("Server: New client connected with id: %d", availableSocketIndex);
printf("\nServer: Clients connected: %d", ftpData.connectedClients);
sscanf (ftpData.clients[availableSocketIndex].serverIpAddress,"%d.%d.%d.%d", &ftpData.clients[availableSocketIndex].serverIpAddressInteger[0],
&ftpData.clients[availableSocketIndex].serverIpAddressInteger[1],
&ftpData.clients[availableSocketIndex].serverIpAddressInteger[2],
&ftpData.clients[availableSocketIndex].serverIpAddressInteger[3]);
error = inet_ntop(AF_INET, &(ftpData.clients[availableSocketIndex].client_sockaddr_in.sin_addr), ftpData.clients[availableSocketIndex].clientIpAddress, INET_ADDRSTRLEN);
printf("\n Client IP: %s", ftpData.clients[availableSocketIndex].clientIpAddress);
ftpData.clients[availableSocketIndex].clientPort = (int) ntohs(ftpData.clients[availableSocketIndex].client_sockaddr_in.sin_port);
printf("\nClient port is: %d\n", ftpData.clients[availableSocketIndex].clientPort);
ftpData.clients[availableSocketIndex].connectionTimeStamp = (int)time(NULL);
ftpData.clients[availableSocketIndex].lastActivityTimeStamp = (int)time(NULL);
write(ftpData.clients[availableSocketIndex].socketDescriptor, ftpData.welcomeMessage, strlen(ftpData.welcomeMessage));
}
else
{
printf("\nErrno = %d", errno);
}
}
else
{
int socketRefuseFd, socketRefuse_in_size;
socketRefuse_in_size = sizeof(struct sockaddr_in);
struct sockaddr_in socketRefuse_sockaddr_in;
if ((socketRefuseFd = accept(ftpData.connectionData.theMainSocket, (struct sockaddr *)&socketRefuse_sockaddr_in, (socklen_t*)&socketRefuse_in_size))!=-1)
{
char *messageToWrite = "530 Server reached the maximum number of connection, please try later.\r\n";
write(socketRefuseFd, messageToWrite, strlen(messageToWrite));
shutdown(socketRefuseFd, SHUT_RDWR);
close(socketRefuseFd);
}
else
{
printf("\nErrno = %d", errno);
}
}
}
if (ftpData.clients[processingSock].socketDescriptor < 0 ||
ftpData.clients[processingSock].socketIsConnected == 0)
{ {
/* socket is not conneted */
continue; continue;
} }
@ -463,29 +392,21 @@ void runFtpServer(void)
FD_ISSET(ftpData.clients[processingSock].socketDescriptor, &ftpData.connectionData.eset)) FD_ISSET(ftpData.clients[processingSock].socketDescriptor, &ftpData.connectionData.eset))
{ {
printf("\nClient r: %d, e: %d", FD_ISSET(ftpData.clients[processingSock].socketDescriptor, &ftpData.connectionData.rset), FD_ISSET(ftpData.clients[processingSock].socketDescriptor, &ftpData.connectionData.eset));
//The client is not connected anymore //The client is not connected anymore
if ((ftpData.clients[processingSock].bufferIndex = read(ftpData.clients[processingSock].socketDescriptor, ftpData.clients[processingSock].buffer, CLIENT_BUFFER_STRING_SIZE)) == 0) if ((ftpData.clients[processingSock].bufferIndex = read(ftpData.clients[processingSock].socketDescriptor, ftpData.clients[processingSock].buffer, CLIENT_BUFFER_STRING_SIZE)) == 0)
{ {
fdRemove(&ftpData, processingSock);
FD_CLR(ftpData.clients[processingSock].socketDescriptor, &ftpData.connectionData.rsetAll);
FD_CLR(ftpData.clients[processingSock].socketDescriptor, &ftpData.connectionData.wsetAll);
FD_CLR(ftpData.clients[processingSock].socketDescriptor, &ftpData.connectionData.esetAll);
closeSocket(&ftpData, processingSock); closeSocket(&ftpData, processingSock);
ftpData.connectionData.maxSocketFD = getMaximumSocketFd(ftpData.connectionData.theMainSocket, &ftpData);
printf("\nSocket is closed!\n"); printf("\nA client has been disconnected!\n");
ftpData.connectionData.maxSocketFD = ftpData.connectionData.theMainSocket+1;
ftpData.connectionData.maxSocketFD = getMaximumSocketFd(ftpData.connectionData.theMainSocket, &ftpData) + 1;
} }
if (ftpData.clients[processingSock].bufferIndex < 0) //Debug print errors
{ if (ftpData.clients[processingSock].bufferIndex < 0)
printf("\nErrno = %d", errno); {
perror("Error: "); printf("\nErrno = %d", errno);
} perror("Error: ");
}
//Some commands has been received //Some commands has been received
if (ftpData.clients[processingSock].bufferIndex > 0) if (ftpData.clients[processingSock].bufferIndex > 0)
@ -509,8 +430,7 @@ void runFtpServer(void)
if (commandProcessStatus == 0) if (commandProcessStatus == 0)
{ {
char * theNotSupportedString = "500 Unknown command\r\n"; char * theNotSupportedString = "500 Unknown command\r\n";
//write(ftpData.clients[processingSock].socketDescriptor, ftpData.clients[processingSock].buffer, ftpData.clients[processingSock].bufferIndex); write(ftpData.clients[processingSock].socketDescriptor, theNotSupportedString, strlen(theNotSupportedString));
//write(ftpData.clients[processingSock].socketDescriptor, theNotSupportedString, strlen(theNotSupportedString));
printf("\n COMMAND NOT SUPPORTED ********* %s", ftpData.clients[processingSock].buffer); printf("\n COMMAND NOT SUPPORTED ********* %s", ftpData.clients[processingSock].buffer);
} }
else else
@ -522,9 +442,11 @@ void runFtpServer(void)
else else
{ {
//Command overflow can't be processed //Command overflow can't be processed
char * theNotSupportedString = "500 Unknown command\r\n";
ftpData.clients[processingSock].commandIndex = 0; ftpData.clients[processingSock].commandIndex = 0;
memset(ftpData.clients[processingSock].theCommandReceived, 0, CLIENT_COMMAND_STRING_SIZE); memset(ftpData.clients[processingSock].theCommandReceived, 0, CLIENT_COMMAND_STRING_SIZE);
//Write some error message to the client //Write some error message to the client
write(ftpData.clients[processingSock].socketDescriptor, theNotSupportedString, strlen(theNotSupportedString));
break; break;
} }
} }
@ -542,320 +464,201 @@ void runFtpServer(void)
return; return;
} }
int createPassiveSocket(int port)
{
int sock, returnCode, flags;
struct sockaddr_in temp;
//Socket creation
sock = socket(AF_INET, SOCK_STREAM, 0);
temp.sin_family = AF_INET;
temp.sin_addr.s_addr = INADDR_ANY;
temp.sin_port = htons(port);
int reuse = 1;
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) < 0)
perror("setsockopt(SO_REUSEADDR) failed");
if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (const char*)&reuse, sizeof(reuse)) < 0)
perror("setsockopt(SO_REUSEPORT) failed");
//Bind socket
returnCode = bind(sock,(struct sockaddr*) &temp,sizeof(temp));
//Number of client allowed
returnCode = listen(sock, 1);
return sock;
}
int createActiveSocket(int port, char *ipAddress)
{
int sockfd;
struct sockaddr_in serv_addr;
struct hostent *hostnm; /* server host name information */
memset(&serv_addr, 0, sizeof(struct sockaddr_in));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
if(inet_pton(AF_INET, ipAddress, &serv_addr.sin_addr)<=0)
{
printf("\n inet_pton error occured\n");
return -1;
}
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Error : Could not create socket \n");
return -1;
}
else
{
printf("\n sockfd = %d \n", sockfd);
}
int reuse = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) < 0)
perror("setsockopt(SO_REUSEADDR) failed");
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, (const char*)&reuse, sizeof(reuse)) < 0)
perror("setsockopt(SO_REUSEPORT) failed");
if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\n Error : Connect Failed \n");
return -1;
}
printf("\n Connection socket %d is going to start ip: %s:%d \n",sockfd, ipAddress, port);
return sockfd;
}
static int processCommand(int processingElement) static int processCommand(int processingElement)
{ {
int toReturn = 0; int toReturn = 0;
printTimeStamp(); printTimeStamp();
printf ("Command received from (%d): %s", processingElement, ftpData.clients[processingElement].theCommandReceived); printf ("Command received from (%d): %s", processingElement, ftpData.clients[processingElement].theCommandReceived);
//printf ("\nstrncmp(ftpData.clients[processingElement].theCommandReceived, \"USER\", strlen(\"USER\")) %d", strncmp(ftpData.clients[processingElement].theCommandReceived, "USER", strlen("USER")));
//printf ("\nstrncmp(ftpData.clients[processingElement].theCommandReceived, \"user\", strlen(\"user\")) %d", strncmp(ftpData.clients[processingElement].theCommandReceived, "user", strlen("user")));
//printf ("\nstrncmp(ftpData.clients[processingElement].theCommandReceived, \"PASS\", strlen(\"PASS\")) %d", strncmp(ftpData.clients[processingElement].theCommandReceived, "PASS", strlen("PASS")));
//printf ("\nstrncmp(ftpData.clients[processingElement].theCommandReceived, \"pass\", strlen(\"pass\")) %d", strncmp(ftpData.clients[processingElement].theCommandReceived, "pass", strlen("pass")));
cleanDynamicStringDataType(&ftpData.clients[processingElement].ftpCommand.commandArgs, 0); cleanDynamicStringDataType(&ftpData.clients[processingElement].ftpCommand.commandArgs, 0);
cleanDynamicStringDataType(&ftpData.clients[processingElement].ftpCommand.commandOps, 0); cleanDynamicStringDataType(&ftpData.clients[processingElement].ftpCommand.commandOps, 0);
if (ftpData.clients[processingElement].login.userLoggedIn == 0 && if (ftpData.clients[processingElement].login.userLoggedIn == 0 &&
(strncmp(ftpData.clients[processingElement].theCommandReceived, "USER", strlen("USER")) != 0 && (compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "USER", strlen("USER")) != 1 &&
strncmp(ftpData.clients[processingElement].theCommandReceived, "user", strlen("user")) != 0 && compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "PASS", strlen("PASS")) != 1 &&
strncmp(ftpData.clients[processingElement].theCommandReceived, "PASS", strlen("PASS")) != 0 && compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "QUIT", strlen("QUIT")) != 1 &&
strncmp(ftpData.clients[processingElement].theCommandReceived, "pass", strlen("pass")) != 0 && compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "AUTH", strlen("AUTH")) != 1))
strncmp(ftpData.clients[processingElement].theCommandReceived, "QUIT", strlen("QUIT")) != 0 &&
strncmp(ftpData.clients[processingElement].theCommandReceived, "quit", strlen("quit")) != 0) &&
strncmp(ftpData.clients[processingElement].theCommandReceived, "AUTH", strlen("AUTH")) != 0 &&
strncmp(ftpData.clients[processingElement].theCommandReceived, "auth", strlen("auth")) != 0)
{ {
toReturn = notLoggedInMessage(&ftpData.clients[processingElement]); toReturn = notLoggedInMessage(&ftpData.clients[processingElement]);
ftpData.clients[processingElement].commandIndex = 0;
memset(ftpData.clients[processingElement].theCommandReceived, 0, CLIENT_COMMAND_STRING_SIZE);
return 1; return 1;
} }
//Process Command //Process Command
if(strncmp(ftpData.clients[processingElement].theCommandReceived, "USER", strlen("USER")) == 0 || if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "USER", strlen("USER")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "user", strlen("user")) == 0)
{ {
printf("\nUSER COMMAND RECEIVED"); printf("\nUSER COMMAND RECEIVED");
toReturn = parseCommandUser(&ftpData.clients[processingElement]); toReturn = parseCommandUser(&ftpData.clients[processingElement]);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "PASS", strlen("PASS")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "PASS", strlen("PASS")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "pass", strlen("pass")) == 0)
{ {
printf("\nPASS COMMAND RECEIVED"); printf("\nPASS COMMAND RECEIVED");
toReturn = parseCommandPass(&ftpData, processingElement); toReturn = parseCommandPass(&ftpData, processingElement);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "SITE", strlen("SITE")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "SITE", strlen("SITE")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "site", strlen("site")) == 0)
{ {
printf("\nSITE COMMAND RECEIVED"); printf("\nSITE COMMAND RECEIVED");
toReturn = parseCommandSite(&ftpData.clients[processingElement]); toReturn = parseCommandSite(&ftpData.clients[processingElement]);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "AUTH", strlen("AUTH")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "AUTH", strlen("AUTH")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "auth", strlen("auth")) == 0)
{ {
printf("\nAUTH COMMAND RECEIVED"); printf("\nAUTH COMMAND RECEIVED");
toReturn = parseCommandAuth(&ftpData.clients[processingElement]); toReturn = parseCommandAuth(&ftpData.clients[processingElement]);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "PWD", strlen("PWD")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "PWD", strlen("PWD")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "pwd", strlen("pwd")) == 0)
{ {
printf("\nPWD COMMAND RECEIVED"); printf("\nPWD COMMAND RECEIVED");
toReturn = parseCommandPwd(&ftpData.clients[processingElement]); toReturn = parseCommandPwd(&ftpData.clients[processingElement]);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "SYST", strlen("SYST")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "SYST", strlen("SYST")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "syst", strlen("syst")) == 0)
{ {
printf("\nSYST COMMAND RECEIVED"); printf("\nSYST COMMAND RECEIVED");
toReturn = parseCommandSyst(&ftpData.clients[processingElement]); toReturn = parseCommandSyst(&ftpData.clients[processingElement]);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "FEAT", strlen("FEAT")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "FEAT", strlen("FEAT")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "feat", strlen("feat")) == 0)
{ {
printf("\nFEAT COMMAND RECEIVED"); printf("\nFEAT COMMAND RECEIVED");
toReturn = parseCommandFeat(&ftpData.clients[processingElement]); toReturn = parseCommandFeat(&ftpData.clients[processingElement]);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "TYPE I", strlen("TYPE I")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "TYPE I", strlen("TYPE I")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "type i", strlen("type i")) == 0)
{ {
printf("\nTYPE I COMMAND RECEIVED"); printf("\nTYPE I COMMAND RECEIVED");
toReturn = parseCommandTypeI(&ftpData.clients[processingElement]); toReturn = parseCommandTypeI(&ftpData.clients[processingElement]);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "STRU F", strlen("STRU F")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "STRU F", strlen("STRU F")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "stru f", strlen("stru f")) == 0)
{ {
printf("\nTYPE I COMMAND RECEIVED"); printf("\nTYPE I COMMAND RECEIVED");
toReturn = parseCommandStruF(&ftpData.clients[processingElement]); toReturn = parseCommandStruF(&ftpData.clients[processingElement]);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "MODE S", strlen("TMODE S")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "MODE S", strlen("MODE S")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "mode s", strlen("mode s")) == 0)
{ {
printf("\nMODE S COMMAND RECEIVED"); printf("\nMODE S COMMAND RECEIVED");
toReturn = parseCommandModeS(&ftpData.clients[processingElement]); toReturn = parseCommandModeS(&ftpData.clients[processingElement]);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "TYPE A", strlen("TYPE A")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "TYPE A", strlen("TYPE A")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "type a", strlen("type a")) == 0)
{ {
printf("\nTYPE A COMMAND RECEIVED"); printf("\nTYPE A COMMAND RECEIVED");
toReturn = parseCommandTypeI(&ftpData.clients[processingElement]); toReturn = parseCommandTypeI(&ftpData.clients[processingElement]);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "PASV", strlen("PASV")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "PASV", strlen("PASV")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "pasv", strlen("pasv")) == 0)
{ {
printf("\nPASV COMMAND RECEIVED"); printf("\nPASV COMMAND RECEIVED");
setRandomicPort(&ftpData, processingElement); setRandomicPort(&ftpData, processingElement);
toReturn = parseCommandPasv(&ftpData, processingElement); toReturn = parseCommandPasv(&ftpData, processingElement);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "PORT", strlen("PORT")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "PORT", strlen("PORT")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "port", strlen("port")) == 0)
{ {
printf("\nPORT COMMAND RECEIVED"); printf("\nPORT COMMAND RECEIVED");
toReturn = parseCommandPort(&ftpData, processingElement); toReturn = parseCommandPort(&ftpData, processingElement);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "LIST", strlen("LIST")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "LIST", strlen("LIST")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "list", strlen("list")) == 0)
{ {
printf("\nLIST COMMAND RECEIVED"); printf("\nLIST COMMAND RECEIVED");
toReturn = parseCommandList(&ftpData, processingElement); toReturn = parseCommandList(&ftpData, processingElement);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "CWD", strlen("CWD")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "CWD", strlen("CWD")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "cwd", strlen("cwd")) == 0)
{ {
printf("\nCWD COMMAND RECEIVED"); printf("\nCWD COMMAND RECEIVED");
toReturn = parseCommandCwd(&ftpData.clients[processingElement]); toReturn = parseCommandCwd(&ftpData.clients[processingElement]);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "CDUP", strlen("CDUP")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "CDUP", strlen("CDUP")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "cdup", strlen("cdup")) == 0)
{ {
printf("\nCDUP COMMAND RECEIVED"); printf("\nCDUP COMMAND RECEIVED");
toReturn = parseCommandCdup(&ftpData.clients[processingElement]); toReturn = parseCommandCdup(&ftpData.clients[processingElement]);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "REST", strlen("REST")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "REST", strlen("REST")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "rest", strlen("rest")) == 0)
{ {
printf("\nREST COMMAND RECEIVED"); printf("\nREST COMMAND RECEIVED");
toReturn = parseCommandRest(&ftpData.clients[processingElement]); toReturn = parseCommandRest(&ftpData.clients[processingElement]);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "RETR", strlen("RETR")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "RETR", strlen("RETR")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "retr", strlen("retr")) == 0)
{ {
printf("\nRETR COMMAND RECEIVED"); printf("\nRETR COMMAND RECEIVED");
toReturn = parseCommandRetr(&ftpData, processingElement); toReturn = parseCommandRetr(&ftpData, processingElement);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "STOR", strlen("STOR")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "STOR", strlen("STOR")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "stor", strlen("stor")) == 0)
{ {
printf("\nSTOR COMMAND RECEIVED"); printf("\nSTOR COMMAND RECEIVED");
toReturn = parseCommandStor(&ftpData, processingElement); toReturn = parseCommandStor(&ftpData, processingElement);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "MKD", strlen("MKD")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "MKD", strlen("MKD")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "mkd", strlen("mkd")) == 0)
{ {
printf("\nMKD command received"); printf("\nMKD command received");
toReturn = parseCommandMkd(&ftpData.clients[processingElement]); toReturn = parseCommandMkd(&ftpData.clients[processingElement]);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "ABOR", strlen("ABOR")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "ABOR", strlen("ABOR")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "abor", strlen("abor")) == 0)
{ {
printf("\nABOR command received"); printf("\nABOR command received");
toReturn = parseCommandAbor(&ftpData, processingElement); toReturn = parseCommandAbor(&ftpData, processingElement);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "DELE", strlen("DELE")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "DELE", strlen("DELE")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "dele", strlen("dele")) == 0)
{ {
printf("\nDELE command received"); printf("\nDELE command received");
toReturn = parseCommandDele(&ftpData.clients[processingElement]); toReturn = parseCommandDele(&ftpData.clients[processingElement]);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "OPTS", strlen("OPTS")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "OPTS", strlen("OPTS")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "opts", strlen("opts")) == 0)
{ {
printf("\nOPTS command received"); printf("\nOPTS command received");
toReturn = parseCommandOpts(&ftpData.clients[processingElement]); toReturn = parseCommandOpts(&ftpData.clients[processingElement]);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "MTDM", strlen("MTDM")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "MTDM", strlen("MTDM")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "mtdm", strlen("mtdm")) == 0)
{ {
printf("\nMTDM command received"); printf("\nMTDM command received");
//To implement //To implement
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "NLST", strlen("NLST")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "NLST", strlen("NLST")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "nlst", strlen("nlst")) == 0)
{ {
printf("\nNLST command received"); printf("\nNLST command received");
toReturn = parseCommandNlst(&ftpData, processingElement); toReturn = parseCommandNlst(&ftpData, processingElement);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "PORT", strlen("PORT")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "PORT", strlen("PORT")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "port", strlen("port")) == 0)
{ {
printf("\nPORT command received"); printf("\nPORT command received");
//To implement //To implement
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "QUIT", strlen("QUIT")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "QUIT", strlen("QUIT")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "quit", strlen("quit")) == 0)
{ {
printf("\nQUIT command received"); printf("\nQUIT command received");
toReturn = parseCommandQuit(&ftpData, processingElement); toReturn = parseCommandQuit(&ftpData, processingElement);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "RMD", strlen("RMD")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "RMD", strlen("RMD")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "rmd", strlen("rmd")) == 0)
{ {
printf("\nRMD command received"); printf("\nRMD command received");
toReturn = parseCommandRmd(&ftpData.clients[processingElement]); toReturn = parseCommandRmd(&ftpData.clients[processingElement]);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "RNFR", strlen("RNFR")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "RNFR", strlen("RNFR")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "rnfr", strlen("rnfr")) == 0)
{ {
printf("\nRNFR command received"); printf("\nRNFR command received");
toReturn = parseCommandRnfr(&ftpData.clients[processingElement]); toReturn = parseCommandRnfr(&ftpData.clients[processingElement]);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "RNTO", strlen("RNTO")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "RNTO", strlen("RNTO")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "rnto", strlen("rnto")) == 0)
{ {
printf("\nRNTO command received"); printf("\nRNTO command received");
toReturn = parseCommandRnto(&ftpData.clients[processingElement]); toReturn = parseCommandRnto(&ftpData.clients[processingElement]);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "SIZE", strlen("SIZE")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "SIZE", strlen("SIZE")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "size", strlen("size")) == 0)
{ {
printf("\nSIZE command received"); printf("\nSIZE command received");
toReturn = parseCommandSize(&ftpData.clients[processingElement]); toReturn = parseCommandSize(&ftpData.clients[processingElement]);
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "APPE", strlen("APPE")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "APPE", strlen("APPE")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "appe", strlen("appe")) == 0)
{ {
printf("\nAPPE command received"); printf("\nAPPE command received");
//To implement //To implement
} }
else if(strncmp(ftpData.clients[processingElement].theCommandReceived, "NOOP", strlen("NOOP")) == 0 || else if(compareStringCaseInsensitive(ftpData.clients[processingElement].theCommandReceived, "NOOP", strlen("NOOP")) == 1)
strncmp(ftpData.clients[processingElement].theCommandReceived, "noop", strlen("noop")) == 0)
{ {
printf("\nNOOP command received"); printf("\nNOOP command received");
toReturn = parseCommandNoop(&ftpData.clients[processingElement]); toReturn = parseCommandNoop(&ftpData.clients[processingElement]);
} }
else else
{ {
//Parse unsupported command ; //Parse unsupported command not needed
} }
ftpData.clients[processingElement].commandIndex = 0; ftpData.clients[processingElement].commandIndex = 0;
memset(ftpData.clients[processingElement].theCommandReceived, 0, CLIENT_COMMAND_STRING_SIZE); memset(ftpData.clients[processingElement].theCommandReceived, 0, CLIENT_COMMAND_STRING_SIZE);
return toReturn; return toReturn;
} }

View File

@ -23,20 +23,6 @@
*/ */
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: ftpServer.h
* Author: ugo
*
* Created on 7 ottobre 2017, 17.37
*/
#ifndef FTPSERVER_H #ifndef FTPSERVER_H
#define FTPSERVER_H #define FTPSERVER_H
@ -44,8 +30,7 @@
void runFtpServer(void); void runFtpServer(void);
int createPassiveSocket(int port);
int createActiveSocket(int port, char *ipAddress);
void *connectionWorkerHandle(void * socketId); void *connectionWorkerHandle(void * socketId);
void workerCleanup(void *socketId); void workerCleanup(void *socketId);

View File

@ -1,7 +1,7 @@
/* /*
* The MIT License * The MIT License
* *
* Copyright 2018 ugo. * Copyright 2018 Ugo Cirmignani.
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
@ -29,14 +29,13 @@
#include <arpa/inet.h> #include <arpa/inet.h>
#include <fcntl.h> #include <fcntl.h>
#include <stdlib.h> #include <stdlib.h>
#include <errno.h>
#include "../ftpData.h" #include <string.h>
#include "connection.h"
#include <unistd.h> #include <unistd.h>
#include <pthread.h> #include <pthread.h>
#include "../ftpData.h"
#include "connection.h"
/* Return the higher socket available*/ /* Return the higher socket available*/
int getMaximumSocketFd(int mainSocket, ftpDataType * ftpData) int getMaximumSocketFd(int mainSocket, ftpDataType * ftpData)
@ -50,7 +49,8 @@ int getMaximumSocketFd(int mainSocket, ftpDataType * ftpData)
toReturn = ftpData->clients[i].socketDescriptor; toReturn = ftpData->clients[i].socketDescriptor;
} }
} }
//Must be incremented by one
toReturn++;
return toReturn; return toReturn;
} }
@ -85,6 +85,80 @@ int createSocket(ftpDataType * ftpData)
return sock; return sock;
} }
int createPassiveSocket(int port)
{
int sock, returnCode;
struct sockaddr_in temp;
//Socket creation
sock = socket(AF_INET, SOCK_STREAM, 0);
temp.sin_family = AF_INET;
temp.sin_addr.s_addr = INADDR_ANY;
temp.sin_port = htons(port);
int reuse = 1;
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) < 0)
perror("setsockopt(SO_REUSEADDR) failed");
if (setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (const char*)&reuse, sizeof(reuse)) < 0)
perror("setsockopt(SO_REUSEPORT) failed");
//Bind socket
returnCode = bind(sock,(struct sockaddr*) &temp,sizeof(temp));
//Number of client allowed
returnCode = listen(sock, 1);
return sock;
}
int createActiveSocket(int port, char *ipAddress)
{
int sockfd;
struct sockaddr_in serv_addr;
memset(&serv_addr, 0, sizeof(struct sockaddr_in));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
if(inet_pton(AF_INET, ipAddress, &serv_addr.sin_addr)<=0)
{
printf("\n inet_pton error occured\n");
return -1;
}
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Error : Could not create socket \n");
return -1;
}
else
{
printf("\n sockfd = %d \n", sockfd);
}
int reuse = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) < 0)
perror("setsockopt(SO_REUSEADDR) failed");
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, (const char*)&reuse, sizeof(reuse)) < 0)
perror("setsockopt(SO_REUSEPORT) failed");
if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\n Error : Connect Failed \n");
return -1;
}
printf("\n Connection socket %d is going to start ip: %s:%d \n",sockfd, ipAddress, port);
return sockfd;
}
void fdInit(ftpDataType * ftpData) void fdInit(ftpDataType * ftpData)
{ {
FD_ZERO(&ftpData->connectionData.rset); FD_ZERO(&ftpData->connectionData.rset);
@ -99,6 +173,21 @@ void fdInit(ftpDataType * ftpData)
FD_SET(ftpData->connectionData.theMainSocket, &ftpData->connectionData.esetAll); FD_SET(ftpData->connectionData.theMainSocket, &ftpData->connectionData.esetAll);
} }
void fdAdd(ftpDataType * ftpData, int index)
{
FD_SET(ftpData->clients[index].socketDescriptor, &ftpData->connectionData.rsetAll);
FD_SET(ftpData->clients[index].socketDescriptor, &ftpData->connectionData.wsetAll);
FD_SET(ftpData->clients[index].socketDescriptor, &ftpData->connectionData.esetAll);
ftpData->connectionData.maxSocketFD = getMaximumSocketFd(ftpData->connectionData.theMainSocket, ftpData) + 1;
}
void fdRemove(ftpDataType * ftpData, int index)
{
FD_CLR(ftpData->clients[index].socketDescriptor, &ftpData->connectionData.rsetAll);
FD_CLR(ftpData->clients[index].socketDescriptor, &ftpData->connectionData.wsetAll);
FD_CLR(ftpData->clients[index].socketDescriptor, &ftpData->connectionData.esetAll);
}
void closeSocket(ftpDataType * ftpData, int processingSocket) void closeSocket(ftpDataType * ftpData, int processingSocket)
{ {
//Close the socket //Close the socket
@ -174,4 +263,105 @@ int selectWait(ftpDataType * ftpData)
ftpData->connectionData.wset = ftpData->connectionData.wsetAll; ftpData->connectionData.wset = ftpData->connectionData.wsetAll;
ftpData->connectionData.eset = ftpData->connectionData.esetAll; ftpData->connectionData.eset = ftpData->connectionData.esetAll;
return select(ftpData->connectionData.maxSocketFD, &ftpData->connectionData.rset, NULL, &ftpData->connectionData.eset, &selectMaximumLockTime); return select(ftpData->connectionData.maxSocketFD, &ftpData->connectionData.rset, NULL, &ftpData->connectionData.eset, &selectMaximumLockTime);
}
int isClientConnected(ftpDataType * ftpData, int cliendId)
{
if (ftpData->clients[cliendId].socketDescriptor < 0 ||
ftpData->clients[cliendId].socketIsConnected == 0)
{
return 0;
}
return 1;
}
int getAvailableClientSocketIndex(ftpDataType * ftpData)
{
int socketIndex;
for (socketIndex = 0; socketIndex < ftpData->ftpParameters.maxClients; socketIndex++)
{
if (isClientConnected(ftpData, socketIndex) == 0)
{
return socketIndex;
}
}
/* no socket are available for a new client connection */
return -1;
}
int evaluateClientSocketConnection(ftpDataType * ftpData)
{
if (FD_ISSET(ftpData->connectionData.theMainSocket, &ftpData->connectionData.rset))
{
int availableSocketIndex;
if ((availableSocketIndex = getAvailableClientSocketIndex(ftpData)) != -1) //get available socket
{
if ((ftpData->clients[availableSocketIndex].socketDescriptor = accept(ftpData->connectionData.theMainSocket, (struct sockaddr *)&ftpData->clients[availableSocketIndex].client_sockaddr_in, (socklen_t*)&ftpData->clients[availableSocketIndex].sockaddr_in_size))!=-1)
{
int error;
ftpData->connectedClients++;
ftpData->clients[availableSocketIndex].socketIsConnected = 1;
error = fcntl(ftpData->clients[availableSocketIndex].socketDescriptor, F_SETFL, O_NONBLOCK);
fdAdd(ftpData, availableSocketIndex);
error = getsockname(ftpData->clients[availableSocketIndex].socketDescriptor, (struct sockaddr *)&ftpData->clients[availableSocketIndex].server_sockaddr_in, (socklen_t*)&ftpData->clients[availableSocketIndex].sockaddr_in_server_size);
inet_ntop(AF_INET,
&(ftpData->clients[availableSocketIndex].server_sockaddr_in.sin_addr),
ftpData->clients[availableSocketIndex].serverIpAddress,
INET_ADDRSTRLEN);
printf("\n Server IP: %s", ftpData->clients[availableSocketIndex].serverIpAddress);
printf("Server: New client connected with id: %d", availableSocketIndex);
printf("\nServer: Clients connected: %d", ftpData->connectedClients);
sscanf (ftpData->clients[availableSocketIndex].serverIpAddress,"%d.%d.%d.%d", &ftpData->clients[availableSocketIndex].serverIpAddressInteger[0],
&ftpData->clients[availableSocketIndex].serverIpAddressInteger[1],
&ftpData->clients[availableSocketIndex].serverIpAddressInteger[2],
&ftpData->clients[availableSocketIndex].serverIpAddressInteger[3]);
inet_ntop(AF_INET,
&(ftpData->clients[availableSocketIndex].client_sockaddr_in.sin_addr),
ftpData->clients[availableSocketIndex].clientIpAddress,
INET_ADDRSTRLEN);
printf("\n Client IP: %s", ftpData->clients[availableSocketIndex].clientIpAddress);
ftpData->clients[availableSocketIndex].clientPort = (int) ntohs(ftpData->clients[availableSocketIndex].client_sockaddr_in.sin_port);
printf("\nClient port is: %d\n", ftpData->clients[availableSocketIndex].clientPort);
ftpData->clients[availableSocketIndex].connectionTimeStamp = (int)time(NULL);
ftpData->clients[availableSocketIndex].lastActivityTimeStamp = (int)time(NULL);
write(ftpData->clients[availableSocketIndex].socketDescriptor, ftpData->welcomeMessage, strlen(ftpData->welcomeMessage));
return 1;
}
else
{
printf("\nErrno = %d", errno);
return 0;
}
}
else
{
int socketRefuseFd, socketRefuse_in_size;
socketRefuse_in_size = sizeof(struct sockaddr_in);
struct sockaddr_in socketRefuse_sockaddr_in;
if ((socketRefuseFd = accept(ftpData->connectionData.theMainSocket, (struct sockaddr *)&socketRefuse_sockaddr_in, (socklen_t*)&socketRefuse_in_size))!=-1)
{
char *messageToWrite = "530 Server reached the maximum number of connection, please try later.\r\n";
write(socketRefuseFd, messageToWrite, strlen(messageToWrite));
shutdown(socketRefuseFd, SHUT_RDWR);
close(socketRefuseFd);
return 0;
}
else
{
printf("\nErrno = %d", errno);
return 0;
}
}
}
else
{
return 0;
}
} }

View File

@ -1,7 +1,7 @@
/* /*
* The MIT License * The MIT License
* *
* Copyright 2018 ugo. * Copyright 2018 Ugo Cirmignani.
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
@ -22,12 +22,6 @@
* THE SOFTWARE. * THE SOFTWARE.
*/ */
/*
* File: connection.h
* Author: ugo
*
* Created on 25 febbraio 2018, 18.43
*/
#ifndef CONNECTION_H #ifndef CONNECTION_H
#define CONNECTION_H #define CONNECTION_H
@ -40,12 +34,21 @@ extern "C" {
int getMaximumSocketFd(int mainSocket, ftpDataType * data); int getMaximumSocketFd(int mainSocket, ftpDataType * data);
int createSocket(ftpDataType * ftpData); int createSocket(ftpDataType * ftpData);
int createPassiveSocket(int port);
int createActiveSocket(int port, char *ipAddress);
void fdInit(ftpDataType * ftpData); void fdInit(ftpDataType * ftpData);
void fdAdd(ftpDataType * ftpData, int index);
void fdRemove(ftpDataType * ftpData, int index);
void checkClientConnectionTimeout(ftpDataType * ftpData); void checkClientConnectionTimeout(ftpDataType * ftpData);
void closeSocket(ftpDataType * ftpData, int processingSocket); void closeSocket(ftpDataType * ftpData, int processingSocket);
void closeClient(ftpDataType * ftpData, int processingSocket); void closeClient(ftpDataType * ftpData, int processingSocket);
int selectWait(ftpDataType * ftpData); int selectWait(ftpDataType * ftpData);
int isClientConnected(ftpDataType * ftpData, int cliendId);
int getAvailableClientSocketIndex(ftpDataType * ftpData);
int evaluateClientSocketConnection(ftpDataType * ftpData);
#ifdef __cplusplus #ifdef __cplusplus
} }

View File

@ -50,9 +50,9 @@ int isProcessAlreadyRunning(void)
syslog(LOG_ERR, "cant open %s: %s", LOCKFILE, strerror(errno)); syslog(LOG_ERR, "cant open %s: %s", LOCKFILE, strerror(errno));
exit(1); exit(1);
} }
printf("\nFile pid opened."); //printf("\nFile pid opened.");
if (returnCode = FILE_LockFile(fd) < 0) if ((returnCode = FILE_LockFile(fd)) < 0)
{ {
if (errno == EACCES || errno == EAGAIN) if (errno == EACCES || errno == EAGAIN)
{ {
@ -63,7 +63,7 @@ int isProcessAlreadyRunning(void)
exit(1); exit(1);
} }
printf("\nFILE_LockFile returnCode = %d", returnCode); //printf("\nFILE_LockFile returnCode = %d", returnCode);
ftruncate(fd, 0); ftruncate(fd, 0);
sprintf(buf, "%ld", (long)getpid()); sprintf(buf, "%ld", (long)getpid());
write(fd, buf, strlen(buf)+1); write(fd, buf, strlen(buf)+1);
@ -132,5 +132,4 @@ void daemonize(const char *cmd)
fd0 = open("/dev/null", O_RDWR); fd0 = open("/dev/null", O_RDWR);
fd1 = dup(0); fd1 = dup(0);
fd2 = dup(0); fd2 = dup(0);
} }

View File

@ -22,13 +22,6 @@
* THE SOFTWARE. * THE SOFTWARE.
*/ */
/*
* File: signals.h
* Author: ugo
*
* Created on 24 febbraio 2018, 19.15
*/
#ifndef SIGNALS_H #ifndef SIGNALS_H
#define SIGNALS_H #define SIGNALS_H

View File

@ -6,6 +6,10 @@
</data> </data>
<editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="0"/> <editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="0"/>
<open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2"> <open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
<group/> <group>
<file>file:/home/ugo/NetBeansProjects/uFTP/ftpServer.c</file>
<file>file:/home/ugo/NetBeansProjects/uFTP/uFTP.c</file>
<file>file:/home/ugo/NetBeansProjects/uFTP/ftpData.h</file>
</group>
</open-files> </open-files>
</project-private> </project-private>

2
uFTP.c
View File

@ -22,12 +22,10 @@
* THE SOFTWARE. * THE SOFTWARE.
*/ */
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include "ftpServer.h" #include "ftpServer.h"
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
runFtpServer(); runFtpServer();