├── Makefile ├── README ├── connectBeacon.cc ├── incoming_connections.cc ├── indexSearch.cc ├── indexSearch.h ├── iniParser.cc ├── iniParser.h ├── keepAliveTimer.cc ├── keepAliveTimer.h ├── keyboard.cc ├── logEntry.cc ├── main.cc ├── main.h ├── metaData.cc ├── outgoing_connections.cc ├── signalHandler.cc ├── signalHandler.h ├── startnode.ini ├── statusResponseTimeout └── timer.cc /Makefile: -------------------------------------------------------------------------------- 1 | # Macros 2 | 3 | CC = g++ 4 | CFLAGS = -g -Wall -D_REENTRANT 5 | OBJ = main.o keyboard.o timer.o iniParser.o incoming_connections.o outgoing_connections.o signalHandler.o keepAliveTimer.o logEntry.o connectBeacon.o indexSearch.o metaData.o 6 | LIBS = -lcrypto -lpthread 7 | INC = 8 | #LIBS = -L/home.scf-22/csci551b/openssl/lib -lcrypto -lnsl -lsocket -lresolv 9 | #INC = -I/home/scf-22/csci551b/openssl/include 10 | 11 | # Explicit rule 12 | all: sv_node 13 | 14 | sv_node: $(OBJ) 15 | $(CC) $(CFLAGS) -o sv_node $(OBJ) $(INC) $(LIBS) 16 | # cp sv_node bnode1/ 17 | # cp sv_node bnode2/ 18 | # cp sv_node bnode3/ 19 | # cp sv_node nonbnode1/ 20 | # cp sv_node nonbnode2/ 21 | 22 | install: 23 | # cp sv_node bnode1/ 24 | # cp sv_node bnode2/ 25 | # cp sv_node bnode3/ 26 | # cp sv_node nonbnode1/ 27 | # cp sv_node nonbnode2/ 28 | 29 | clean: 30 | rm -rf *.o sv_node 31 | # rm bnode1/sv_node 32 | # rm bnode2/sv_node 33 | # rm bnode3/sv_node 34 | # rm nonbnode1/sv_node 35 | # rm nonbnode2/sv_node 36 | 37 | main.o: main.cc 38 | $(CC) $(CFLAGS) -c main.cc $(INC) 39 | keyboard.o: keyboard.cc 40 | $(CC) $(CFLAGS) -c keyboard.cc $(INC) 41 | timer.o: timer.cc 42 | $(CC) $(CFLAGS) -c timer.cc $(INC) 43 | iniParser.o: iniParser.cc 44 | $(CC) $(CFLAGS) -c iniParser.cc $(INC) 45 | incoming_connections.o: incoming_connections.cc 46 | $(CC) $(CFLAGS) -c incoming_connections.cc $(INC) 47 | outgoing_connections.o: outgoing_connections.cc 48 | $(CC) $(CFLAGS) -c outgoing_connections.cc $(INC) 49 | signalHandler.o: signalHandler.cc 50 | $(CC) $(CFLAGS) -c signalHandler.cc $(INC) 51 | keepAliveTimer.o: keepAliveTimer.cc 52 | $(CC) $(CFLAGS) -c keepAliveTimer.cc $(INC) 53 | logEntry.o: logEntry.cc 54 | $(CC) $(CFLAGS) -c logEntry.cc $(INC) 55 | connectBeacon.o: connectBeacon.cc 56 | $(CC) $(CFLAGS) -c connectBeacon.cc $(INC) 57 | indexSearch.o: indexSearch.cc 58 | $(CC) $(CFLAGS) -c indexSearch.cc $(INC) 59 | metaData.o: metaData.cc 60 | $(CC) $(CFLAGS) -c metaData.cc $(INC) 61 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | Team:- 2 | Aaveg Mittal - aavegmit@usc.edu (1523097378) 3 | Manu Bhadoria - mbhadori@usc.edu (7151287551) 4 | 5 | Peer to Peer File sharing System - Final Project Part(2) 6 | CSCI 551, Computer Compunication 7 | Spring 2011 8 | 9 | 10 | 11 | FILES: 12 | 13 | Below are the files in this prject, Part 2:- 14 | 15 | -main.cc 16 | 17 | This file includes the main body of the peer to peer file system. This is the main thread, and it creates multiple child thread which goes on to accept connection and other goes on to connect to the hostname and port number supplied. This file consist of Init() and cleanup() code which is used in Soft restart. 18 | 19 | -main.h 20 | 21 | Consist of declaration of multiple data structres used throughout the program and these data structres have been extern. Declaration of functions, variables. This header file is included in multiple files 22 | 23 | -incoming_connection.cc 24 | 25 | This file consist of accept thread, which accpets the connection and then creates the read and write threads for every incomming connections. This file includes read Thread which reads on the connected socket for the data and passes the data to function, which processes the header and the buffer part of the message, so as to respond or put the response in the message queue of the write thread accordingly. This file consist of message dispatcher, which puts the message into the queue of the write thread 26 | 27 | -outgoing_connection.cc 28 | 29 | consist of function which attempts to connect to the given hostname and port no. consist of write thread which process the message in the queue and then writes on the sockets accordingly. This file consist of join network function which is called whenever the init_neighbor_list is not given. GETUOID function is also present in this file, alongwith the function which write to the status file whenevr the user enters the "status neighbors" command on the command prompt 30 | 31 | -connectBeacon.cc 32 | 33 | This file is for Beacon Node, and consist of the part which attempts to send connect request to the other beacon node, so that fully connected mesh could be formed. Whenever the beacon node goes down, this thread retries conecting after the given retry period. 34 | 35 | -iniParser.cc 36 | 37 | This file consist of the complete iniParser, which parses the ".ini" file given at the command promopt, function has been self written. Not used the "Nicolas Devillard's iniparser". Consist of the function which removes the white spaces, and new line charcaters from the line read from the file. This file consist of function which sets the parameters of the node equal to the values read from the .ini file 38 | 39 | -iniParser.h 40 | 41 | declarartion of parameters for the node, data structre and iniParser function declaration 42 | 43 | -keepAliveTimer.cc 44 | 45 | consist of a thread which sends keepalive messages to the neighbors on the interval of keepAliveTimeOut/3. 46 | 47 | -keepAliveTimer.h 48 | 49 | declaration of the keepAliveTimer function 50 | 51 | -keyboard.cc 52 | 53 | thread which takes the user input by simulating the command prompt, either "shutdown" or "status neighbor" command 54 | 55 | -logEntry.cc 56 | 57 | This function is called to enter the formatted text into the log file, named "servant.log" present in the HOME DIRECTORY 58 | 59 | -signalHandler.cc 60 | 61 | handles the varios signals generated during the program flow, such as SIGINT or SIGTERM, for shutdown 62 | 63 | -signalHandler.h 64 | 65 | declaration of signal handler function 66 | 67 | -timer.cc 68 | 69 | timer thread which decrements the counter every 1 sec for multiple timers, such as autoShutDown, KeepAliveTimeOut, joinTimeOut, CheckResponseTimeout, statusTimeOut, messageLifeTimeTimer. and performs action when value reaches to 0, indicating timeout. 70 | 71 | 72 | - indexSearch.cc 73 | 74 | this file contains numerous functions related to mainting the data in name_index, sha1_index, kwrd_index. functions related to externalizng index, searching in the index, creating bit vector for the keywords, populating the index from external files, removing file entry from Index, writing data to files directory in the homedir, creating metadata and data files. 75 | 76 | -indexSearch.h 77 | 78 | declaration of functios defined in indexSearch.cc, functions related to index, i.e. sha1_index, name_index, kwrd_index 79 | 80 | - metaData.cc 81 | 82 | This file consist of functions creating metadata, which is to be written to meta files in files dir in homedir. parses the messages to give out metadata structures, populating with , file size, file name, sha1, nonce, bit vector, keywords. Functions, which produces metadata sturctes from the '.meta' files on filesystem, functions related to LRU, externalizing LRU, updating the lru, removing from lru, storing in the lru. 83 | 84 | - '.fileNumber' 85 | 86 | this is a hidden file stored in the HOME DIR, which containes a number which signifies the number system in the filesystem. To store a file in filesystem, a node will read the value from this file, increment the number, and rewrite the number to the file, and uses the number as a file name in it's filesystem. e.g. 5.meta, 5.data, 5.pass. If this file does not exist in the filesystem, node will create it when it starts up, and store the value as 0 in the file. 87 | 88 | - cacheLRU 89 | 90 | contains the list of 'number' i.e. int used for representing a file in it's file system. when node shutsdown, cache is externalized to this file. 91 | 92 | - kwrd_index 93 | 94 | this file is used to externalize the kwrd_index in memory, whenevr node shutsdown. the kwrd_index in memory has been implemnetd using STL MAPS, where the key is '128-byte string' and the value corresponding to the key is list of numbers, representing the files in the nodes file system. format of the file is give as:- 95 | 96 | <256 characters represnting 128byte of bit-vectors> 97 | 98 | e.g 99 | 100 | 3 000000000000000000000000002000000000000000000000000000000000000000000000000000002008000000000000000000000000000000040000000000000000000000000000 000000000000000000000000000040000800000000000000000000000000000000000000000000000000000000c000000000000000000000 4 5 6 101 | 102 | where, 3 is the number of files stored corresponding to the bitvector, and 4, 5 and 6 are the name of files in it's filesystem 103 | 104 | 105 | - sha1_index 106 | 107 | this file is used to externalize the sha1_index in memory, whenevr node shutsdown. the sha1_index in memory has been implemnetd using STL MAPS, where the key is '20-byte string' and the value corresponding to the key is list of numbers, representing the files in the node's file system. format of the file is give as:- 108 | 109 | <40 characters represnting 20byte of sha1 of file> 110 | 111 | e.g 112 | 113 | 3 e2d306e2b2000ebbe9060637d2a349b83c588b68 4 5 6 114 | 115 | where, 3 is the number of files stored corresponding to the 40 char long sha1, and 4, 5 and 6 are the names of files in it's filesystem 116 | 117 | 118 | - name_index 119 | 120 | this file is used to externalize the name_index in memory, whenevr node shutsdown. the name_index in memory has been implemnetd using STL MAPS, where the key is a 'String' and the value corresponding to the key is list of numbers, representing the files in the node's file system. format of the file is give as:- 121 | 122 | 123 | 124 | e.g 125 | 126 | 3 v.gif 4 5 6 127 | 128 | where, 3 is the number of files stored corresponding to the 'v.gif' file name, and 4, 5 and 6 are the names of files in it's filesystem 129 | 130 | - More files created in 'files' directory in homeDir:- 131 | 132 | - '.data' 133 | - '.meta' 134 | - '.pass' 135 | 136 | above files are created as the files are created or stored using 'store', 'get'. '.pass' is only created at the node which inititates the 'store' command. .pass file consist of 20 byte long password in binary mode. 137 | 138 | 139 | DESIGN DECISIONS : 140 | 141 | For BEACON NODE:- 142 | 143 | Parent thread creates the thread for Accept and creates thread for Connect, which keeps on trying whenever the connection breaks with the other beacon node, this thread gaurantees to attempt connection if any beacon node gets disconnected. Whenevr the connection takes place, a read and write thread is also created, which reads and writes on the connection to the neighbor. 144 | 145 | For NON-BEACN NODE:- 146 | 147 | Parent thread creats the accpet thread and then tries to connect to the neighbors as per the init_neighbor_list. If it does not get connected to min Neighbors, it inittaies the Soft Restart, which free up all the other resources. Whenevr the connection takes place, a read and write thread is also created, which reads and writes on the connection to the neighbor. 148 | 149 | 150 | 151 | Refrences abd Credits 152 | 153 | 154 | - Refered to "Begining Linux programming" by Wrox, taken thread code from that book 155 | - UOID code fragment used from: http://merlot.usc.edu/cs551-s11/projects/final.html#uoid 156 | 157 | -------------------------------------------------------------------------------- /connectBeacon.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "main.h" 4 | #include "iniParser.h" 5 | #include "signalHandler.h" 6 | 7 | 8 | //Connect thread of every beacon node 9 | //retries the connection, if connection broke, untill called for shutdown 10 | 11 | void* connectBeacon(void *args) 12 | { 13 | 14 | pthread_t myID = pthread_self(); 15 | myConnectThread[myID] = 0; 16 | struct node n; 17 | memset(&n, 0, sizeof(n)); 18 | n = *((struct node *)args); 19 | 20 | //stroes the read & write child of the connect thread 21 | list myChildThreadList; 22 | 23 | int resSock = 0; 24 | int res = 0; 25 | while(!shutDown){ 26 | 27 | //signal(SIGUSR2, my_handler); 28 | 29 | pthread_mutex_lock(&nodeConnectionMapLock) ; 30 | if (nodeConnectionMap.find(n)!=nodeConnectionMap.end()){ 31 | pthread_mutex_unlock(&nodeConnectionMapLock) ; 32 | } 33 | else { 34 | 35 | pthread_mutex_unlock(&nodeConnectionMapLock) ; 36 | 37 | //printf("Connecting to %s:%d\n", n.hostname, n.portNo) ; 38 | //sleep(1); 39 | resSock = connectTo((unsigned char *)n.hostname, n.portNo) ; 40 | if (resSock == -1 ){ 41 | // Connection could not be established 42 | } 43 | else{ 44 | struct connectionNode cn ; 45 | int mres = pthread_mutex_init(&cn.mesQLock, NULL) ; 46 | if (mres != 0){ 47 | 48 | //perror("Mutex initialization failed"); 49 | writeLogEntry((unsigned char *)"//Mutex lock initilization failed\n"); 50 | } 51 | int cres = pthread_cond_init(&cn.mesQCv, NULL) ; 52 | if (cres != 0){ 53 | //perror("CV initialization failed") ; 54 | writeLogEntry((unsigned char *)"//CV initilization failed\n"); 55 | } 56 | 57 | cn.shutDown = 0 ; 58 | cn.keepAliveTimer = myInfo->keepAliveTimeOut/2; 59 | cn.keepAliveTimeOut = myInfo->keepAliveTimeOut; 60 | cn.isReady = 0; 61 | cn.n = n; 62 | //signal(SIGUSR2, my_handler); 63 | 64 | pthread_mutex_lock(&connectionMapLock) ; 65 | connectionMap[resSock] = cn ; 66 | pthread_mutex_unlock(&connectionMapLock) ; 67 | // Push a Hello type message in the writing queue 68 | struct Message m ; 69 | m.type = 0xfa ; 70 | m.status = 0 ; 71 | m.fromConnect = 1 ; 72 | pushMessageinQ(resSock, m) ; 73 | // Create a read thread for this connection 74 | pthread_t re_thread ; 75 | res = pthread_create(&re_thread, NULL, read_thread , (void *)resSock); 76 | if (res != 0) { 77 | //perror("Thread creation failed"); 78 | writeLogEntry((unsigned char *)"//Read Thread Creation failed!!!!\n"); 79 | exit(EXIT_FAILURE); 80 | } 81 | myChildThreadList.push_front(re_thread); 82 | pthread_mutex_lock(&connectionMapLock) ; 83 | connectionMap[resSock].myReadId = re_thread; 84 | pthread_mutex_unlock(&connectionMapLock) ; 85 | // Create a write thread 86 | pthread_t wr_thread ; 87 | res = pthread_create(&wr_thread, NULL, write_thread , (void *)resSock); 88 | if (res != 0) { 89 | //perror("Thread creation failed"); 90 | writeLogEntry((unsigned char *)"//Write Thread Creation failed!!!!\n"); 91 | exit(EXIT_FAILURE); 92 | } 93 | myChildThreadList.push_front(wr_thread); 94 | pthread_mutex_lock(&connectionMapLock) ; 95 | connectionMap[resSock].myReadId = wr_thread; 96 | pthread_mutex_unlock(&connectionMapLock) ; 97 | 98 | 99 | //pthread Join here 100 | void* thread_result; 101 | for (list::iterator it = myChildThreadList.begin(); it != myChildThreadList.end(); ++it){ 102 | //printf("Value is : %d and SIze: %d\n", (int)(*it), (int)childThreadList.size()); 103 | res = pthread_join((*it), &thread_result); 104 | if (res != 0) { 105 | //writeLogEntry((char *)"//Thread Creation failed!!!!\n"); 106 | //exit(EXIT_FAILURE); 107 | } 108 | it = myChildThreadList.erase(it); 109 | --it; 110 | } 111 | if(shutDown) 112 | break; 113 | } 114 | }//end of else 115 | 116 | if(shutDown) 117 | break; 118 | 119 | // Wait for 'retry' time before making the connections again 120 | myConnectThread[myID] = 1; 121 | sleep(myInfo->retry) ; 122 | myConnectThread[myID] = 0; 123 | //printf("Hello I am here!!!\n"); 124 | 125 | } 126 | //printf("I am gone!!!\n"); 127 | myChildThreadList.clear(); 128 | pthread_exit(0); 129 | } 130 | -------------------------------------------------------------------------------- /indexSearch.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "main.h" 11 | #include "iniParser.h" 12 | #include "signalHandler.h" 13 | #include "keepAliveTimer.h" 14 | #include 15 | #include "indexSearch.h" 16 | 17 | #include 18 | // Indexed from 0 19 | // Read a bit from the array 20 | unsigned char readBit(unsigned char *str, int location){ 21 | int byte_loc = location / 8 ; 22 | int bit_loc = location % 8 ; 23 | 24 | unsigned char temp = str[byte_loc] ; 25 | 26 | temp = temp << bit_loc ; 27 | temp = temp >> 7 ; 28 | return temp ; 29 | 30 | } 31 | 32 | // Write a bit at the specified memory location 33 | void writeBit(unsigned char *str, int location, unsigned char value){ 34 | int byte_loc = location / 8 ; 35 | int bit_loc = location % 8 ; 36 | 37 | unsigned char temp = 0x80 ; 38 | temp = temp >> bit_loc ; 39 | 40 | if(value == 0x01){ 41 | str[byte_loc] = str[byte_loc] | temp ; 42 | } 43 | else{ 44 | str[byte_loc] = str[byte_loc] & ~temp ; 45 | } 46 | } 47 | 48 | // Compute the SHA1 49 | unsigned char *toSHA1(unsigned char *str) 50 | { 51 | unsigned char *sha1_str = (unsigned char *)malloc(sizeof(unsigned char)*20); 52 | SHA1(str, strlen((const char *)str), sha1_str); 53 | return sha1_str; 54 | } 55 | 56 | // Compute the MD5 57 | unsigned char *toMD5(unsigned char *str) 58 | { 59 | unsigned char *md5_str = (unsigned char *)malloc(sizeof(unsigned char)*20); 60 | MD5(str, strlen((const char *)str), md5_str); 61 | return md5_str; 62 | } 63 | 64 | 65 | // Method creates a bit vector 66 | void createBitVector(unsigned char *bitVector, unsigned char *keyword) 67 | { 68 | //unsigned short int sha1_int = 0; 69 | //unsigned short int md5_int = 0; 70 | 71 | uint16_t sha1_int = 0; 72 | uint16_t md5_int = 0; 73 | 74 | for(int i=0;keyword[i]!='\0';i++) 75 | keyword[i]=tolower(keyword[i]); 76 | 77 | unsigned char *sha1_str = toSHA1(keyword); 78 | unsigned char *md5_str = toMD5(keyword); 79 | /*printf("Sha1 obtained: \n"); 80 | for(int i=0;i<20;i++) 81 | printf("%02x", sha1_str[i]); 82 | printf("\nMd5 obtained: \n"); 83 | for(int i=0;i<16;i++) 84 | printf("%02x", md5_str[i]); 85 | printf("\n");*/ 86 | unsigned char sha1_str_temp[2]; 87 | unsigned char md5_str_temp[2]; 88 | 89 | unsigned char temp = readBit(sha1_str, 151); 90 | 91 | sha1_str_temp[0] = temp; 92 | sha1_str_temp[1] = sha1_str[19]; 93 | 94 | temp = readBit(md5_str, 119); 95 | md5_str_temp[0] = temp; 96 | md5_str_temp[1] = md5_str[15]; 97 | 98 | memcpy(&sha1_int, sha1_str_temp, 2); 99 | memcpy(&md5_int, md5_str_temp, 2); 100 | /*for(int i=0;i<2;i++) 101 | printf("sha1: %02x, md5: %02x\n", sha1_str_temp[i], md5_str_temp[i]); 102 | printf("Integer are sha1: %d, md5: %d\n", sha1_int, md5_int);*/ 103 | //unsigned char *bitVector = (unsigned char *)malloc(sizeof(unsigned char)*128); 104 | //unsigned char bitVector[128]; 105 | //memset(bitVector, 0, sizeof(bitVector)); 106 | /*writeBit(bitVector, 1023 , 0x01); 107 | bitVector = bitVector << md5_int; 108 | bitVector = bitVector << sha1_int;*/ 109 | writeBit(bitVector, 1023-(512 + sha1_int) , 0x01); 110 | writeBit(bitVector, 1023-md5_int , 0x01); 111 | 112 | /* for(int i=0;i<128;i++) 113 | printf("%02x", bitVector[i]); 114 | printf("\n\n"); 115 | */ 116 | //return bitVector; 117 | } 118 | 119 | //Search the files with bitVector 120 | list keywordSearch(unsigned char *completeStr) 121 | { 122 | unsigned char *str = NULL; 123 | unsigned char bitVector[128]; 124 | int existFlag = 0; 125 | int checkFlag = 0; 126 | list *tempList = new list(); 127 | list returnList; 128 | memset(bitVector, 0, sizeof(bitVector)); 129 | 130 | while((str = (unsigned char *)strtok((char *)completeStr, " "))!= NULL) 131 | { 132 | for(int i=0;str[i]!='\0';i++) 133 | str[i]=tolower(str[i]); 134 | tempList->push_back(string((char *)str)); 135 | 136 | createBitVector(bitVector, str); 137 | completeStr = NULL; 138 | } 139 | 140 | /* for(int i=0;i<128;i++) 141 | { 142 | printf("%02x", bitVector[i]); 143 | 144 | } 145 | */ 146 | unsigned char tempString[128]; 147 | memset(tempString, 0, sizeof(tempString)); 148 | for (map >::iterator it = bitVectorIndexMap.begin(); it != bitVectorIndexMap.end(); ++it){ 149 | //strncpy((char *)tempString, (*it).first.c_str(), 128); 150 | checkFlag=0; 151 | // printf("\n\nHere\n\n"); 152 | for(int i=0;i<128;i++) 153 | { 154 | tempString[i]=((*it).first).c_str()[i]; 155 | // printf("%02x", tempString[i]); 156 | } 157 | //printf("Hereagain\n\n"); 158 | for(int i=0;i<128;i++) 159 | { 160 | tempString[i] = tempString[i] & bitVector[i]; 161 | if(tempString[i]!=0x00) 162 | { 163 | checkFlag = 1; 164 | } 165 | //printf("%02x", tempString[i]); 166 | } 167 | //printf("\n\nlen is strlen: %d\n", (int)(strlen((char *)tempString))); 168 | if(checkFlag) 169 | { 170 | //now do the keyword search 171 | for (list::iterator it2 = (*it).second.begin(); it2 != (*it).second.end(); ++it2){ 172 | struct metaData metadata = populateMetaData(*it2); 173 | for (list::iterator it1 = tempList->begin(); it1 != tempList->end(); ++it1){ 174 | //search for all keywords in each of the file, need to parse the file now and get list of keywords 175 | list::iterator result = find(metadata.keywords->begin(), metadata.keywords->end(), (*it1)); 176 | if(result!=metadata.keywords->end()) 177 | { 178 | existFlag = 1; 179 | } 180 | else 181 | { 182 | existFlag = 0; 183 | break; 184 | } 185 | } 186 | if(existFlag) 187 | returnList.push_back((*it2)); 188 | } 189 | } 190 | } 191 | 192 | if(returnList.size()!=0) 193 | { 194 | for(list::iterator it = returnList.begin();it!=returnList.end();it++) 195 | { 196 | updateLRU((*it)); 197 | } 198 | } 199 | return returnList; 200 | } 201 | 202 | // Returns the list of indexes of files having this filename 203 | list fileNameSearch(unsigned char *fileName) 204 | { 205 | /*for(int i=0;i<(int)buf_len;i++) 206 | fileName[i]=tolower(fileName[i]);*/ 207 | map >::iterator it; 208 | list tempList; 209 | 210 | string searchString((const char *)fileName); 211 | 212 | it = fileNameIndexMap.find(searchString); 213 | if(it!=fileNameIndexMap.end()) 214 | { 215 | for (list::iterator it1 = (*it).second.begin(); it1 != (*it).second.end(); ++it1){ 216 | tempList.push_back((*it1)); 217 | } 218 | return tempList; 219 | } 220 | if(tempList.size()!=0) 221 | { 222 | for(list::iterator it = tempList.begin();it!=tempList.end();it++) 223 | { 224 | updateLRU((*it)); 225 | } 226 | } 227 | return tempList; 228 | } 229 | 230 | list sha1Search(unsigned char *sha1String) 231 | { 232 | map >::iterator it; 233 | list tempList; 234 | 235 | string searchString((const char *)sha1String, 20); 236 | it = sha1IndexMap.find(searchString); 237 | 238 | if(it!=sha1IndexMap.end()) 239 | { 240 | for (list::iterator it1 = (*it).second.begin(); it1 != (*it).second.end(); ++it1){ 241 | tempList.push_back((*it1)); 242 | } 243 | return tempList; 244 | } 245 | 246 | if(tempList.size()!=0) 247 | { 248 | for(list::iterator it = tempList.begin();it!=tempList.end();it++) 249 | { 250 | updateLRU((*it)); 251 | } 252 | } 253 | return tempList; 254 | } 255 | 256 | 257 | void populateBitVectorIndexMap(unsigned char *bitVector, unsigned int fileNumber) 258 | { 259 | string str((char *)bitVector, 128); 260 | bitVectorIndexMap[str].push_back((int)fileNumber); 261 | /*for (map >::iterator it1 = bitVectorIndexMap.begin(); it1 != bitVectorIndexMap.end(); ++it1){ 262 | for(int i=0;i<128;i++) 263 | { 264 | //printf("%02x", ((*it1).first).c_str()[i]); 265 | bitVector[i]=((*it1).first).c_str()[i]; 266 | } 267 | }*/ 268 | } 269 | 270 | void populateSha1IndexMap(unsigned char *sha1, unsigned int fileNumber) 271 | { 272 | /* printf("while populating: \n"); 273 | for(int i=0;i<20;i++) 274 | { 275 | printf("%02x", sha1[i]); 276 | //bitVector[i]=((*it1).first).c_str()[i]; 277 | } 278 | printf("\n"); 279 | */ 280 | string str((char *)sha1, 20); 281 | sha1IndexMap[str].push_back((int)fileNumber); 282 | } 283 | 284 | void populateFileNameIndexMap(unsigned char *fileName, unsigned int fileNumber) 285 | { 286 | fileNameIndexMap[string((char *)fileName)].push_back((int)fileNumber); 287 | } 288 | 289 | //Prints the Indexed Maps to corresponding files 290 | void writeIndexToFile() 291 | { 292 | //write to Keyword FILE 293 | /*unsigned char kwrd_index[256]; 294 | memset(kwrd_index, '\0', sizeof(kwrd_index)); 295 | 296 | sprintf((char *)kwrd_index, "%s/%s" ,myInfo->homeDir, "kwrd_index"); 297 | FILE *f = fopen((char *)kwrd_index, "wb");*/ 298 | unsigned char kwrd_index_file[256]; 299 | sprintf((char *)kwrd_index_file, "%s/kwrd_index", myInfo->homeDir); 300 | FILE *f = fopen((char *)kwrd_index_file, "w"); 301 | unsigned char bitVector_str[129]; 302 | for (map >::iterator it = bitVectorIndexMap.begin(); it != bitVectorIndexMap.end(); ++it){ 303 | //fwrite(&(*it).first,sizeof((*it).first), 1,f); 304 | //fwrite(&(*it).second,sizeof((*it).second), 1,f); 305 | //cout<<(*it).first<::iterator it1 = (*it).second.begin(); it1 != (*it).second.end(); ++it1){ 319 | fprintf(f, " %d", *it1); 320 | } 321 | } 322 | 323 | //fwrite(&bitVectorIndexMap,sizeof(bitVectorIndexMap), 1,f); 324 | fclose(f); 325 | 326 | //write to NAME FILE 327 | /*unsigned char name_index[256]; 328 | memset(name_index, '\0', sizeof(name_index)); 329 | 330 | sprintf((char *)name_index, "%s/%s" ,myInfo->homeDir, "name_index"); 331 | f = fopen((char *)name_index, "wb");*/ 332 | unsigned char name_index_file[256]; 333 | sprintf((char *)name_index_file, "%s/name_index", myInfo->homeDir); 334 | f = fopen((char *)name_index_file, "w"); 335 | //fwrite(&fileNameIndexMap,sizeof(fileNameIndexMap), 1,f); 336 | for (map >::iterator it = fileNameIndexMap.begin(); it != fileNameIndexMap.end(); ++it){ 337 | //fwrite(&(*it).first,sizeof((*it).first), 1,f); 338 | //fwrite(&(*it).second,sizeof((*it).second), 1,f); 339 | fprintf(f,"%d %s ",(int)((*it).second).size(), ((*it).first).c_str()); 340 | for(list::iterator it1 = (*it).second.begin(); it1 != (*it).second.end(); ++it1){ 341 | fprintf(f, "%d ", *it1); 342 | } 343 | } 344 | fclose(f); 345 | 346 | //write to SHA1 FILE 347 | /*unsigned char sha1_index[256]; 348 | memset(sha1_index, '\0', sizeof(sha1_index)); 349 | 350 | sprintf((char *)sha1_index, "%s/%s" ,myInfo->homeDir, "sha1_index"); 351 | f = fopen((char *)sha1_index, "wb");*/ 352 | unsigned char tempSha1[20]; 353 | memset(tempSha1, 0, 20); 354 | unsigned char sha1_index_file[256]; 355 | sprintf((char *)sha1_index_file, "%s/sha1_index", myInfo->homeDir); 356 | f = fopen((char *)sha1_index_file, "w"); 357 | for (map >::iterator it = sha1IndexMap.begin(); it != sha1IndexMap.end(); ++it){ 358 | //fwrite(&(*it).first,sizeof((*it).first), 1,f); 359 | //fwrite(&(*it).second,sizeof((*it).second), 1,f); 360 | fprintf(f,"%d ",(int)((*it).second).size()); 361 | for(int i=0;i<20;i++) 362 | { 363 | //fprintf(f, "%c",((*it).first).c_str()[i]); 364 | tempSha1[i] = ((*it).first).c_str()[i]; 365 | fprintf(f, "%02x",tempSha1[i]); 366 | } 367 | for(list::iterator it1 = (*it).second.begin(); it1 != (*it).second.end(); ++it1){ 368 | fprintf(f, " %d ", *it1); 369 | } 370 | memset(tempSha1, 0, 20); 371 | } 372 | //fwrite(&sha1IndexMap, sizeof(sha1IndexMap), 1,f); 373 | fclose(f); 374 | } 375 | 376 | //Populate Index from file 377 | void readIndexFromFile() 378 | { 379 | //write to Keyword FILE 380 | /*unsigned char kwrd_index[256]; 381 | memset(kwrd_index, '\0', sizeof(kwrd_index)); 382 | 383 | sprintf((char *)kwrd_index, "%s/%s" ,myInfo->homeDir, "kwrd_index"); 384 | FILE *f = fopen((char *)kwrd_index, "rb");*/ 385 | 386 | 387 | //fread(&bitVectorIndexMap,sizeof(bitVectorIndexMap), 1,f); 388 | /*for (map >::iterator it = bitVectorIndexMap.begin(); it != bitVectorIndexMap.end(); ++it){ 389 | 390 | fread(&str,sizeof(str), 1,f); 391 | fread(&(*it).second,sizeof((*it).second), 1,f); 392 | bitVectorIndexMap[str] = (*it).second; 393 | }*/ 394 | int ret = 1; 395 | int size; 396 | list tempList; 397 | unsigned char str[129]; 398 | unsigned char tempBitVector[256]; 399 | memset(str, 0, sizeof(str)); 400 | memset(tempBitVector, 0, 256); 401 | unsigned char kwrd_index_file[256]; 402 | sprintf((char *)kwrd_index_file, "%s/kwrd_index", myInfo->homeDir); 403 | FILE *f = fopen((char *)kwrd_index_file, "r"); 404 | if(f!=NULL) 405 | { 406 | while(fscanf(f, " %d ",&size)!=EOF) 407 | { 408 | /*for(int i=0;i<128;i++) 409 | fscanf(f, "%c", &str[i]);*/ 410 | for(int i=0;i<256;i++) 411 | { 412 | fscanf(f, "%c", &tempBitVector[i]); 413 | //printf("%c", tempBitVector[i]); 414 | } 415 | /*for(int i=0;i<128;i++) 416 | printf("%02x",tempBitVector[i]);*/ 417 | 418 | // printf("\n\n"); 419 | unsigned char *temp = (unsigned char *)toHex(tempBitVector, 128); 420 | 421 | //strncpy((char *)str, , 128); 422 | 423 | for(int i=0;i<128;i++) 424 | { 425 | str[i] = temp[i]; 426 | //printf("%02x",temp[i]); 427 | } 428 | 429 | for(int i=0;ihomeDir, "name_index"); 450 | f = fopen((char *)name_index, "rb");*/ 451 | ret=0; 452 | size=0; 453 | unsigned char fileName_str[256]; 454 | memset(fileName_str, 0, sizeof(fileName_str)); 455 | tempList.clear(); 456 | unsigned char name_index_file[256]; 457 | sprintf((char *)name_index_file, "%s/name_index", myInfo->homeDir); 458 | f = fopen((char *)name_index_file, "r"); 459 | if(f!=NULL) 460 | { 461 | while(fscanf(f, "%d %s ",&size,fileName_str)!=EOF) 462 | { 463 | for(int i=0;ihomeDir, "sha1_index"); 479 | f = fopen((char *)sha1_index, "rb");*/ 480 | ret=0; 481 | size=0; 482 | unsigned char sha1_str[20]; 483 | unsigned char tempSha1[40]; 484 | memset(sha1_str, 0, sizeof(sha1_str)); 485 | memset(tempSha1, 0, 40); 486 | tempList.clear(); 487 | unsigned char sha1_index_file[256]; 488 | sprintf((char *)sha1_index_file, "%s/sha1_index", myInfo->homeDir); 489 | f = fopen((char *)sha1_index_file, "r"); 490 | if(f!=NULL) 491 | { 492 | while(fscanf(f, "%d ",&size)!=EOF) 493 | { 494 | /*for(int i=0;i<20;i++) 495 | fscanf(f, "%c",&sha1_str[i]);*/ 496 | for(int i=0;i<40;i++) 497 | fscanf(f, "%c",&tempSha1[i]); 498 | strncpy((char *)sha1_str, (char *)toHex(tempSha1, 20), 20); 499 | for(int i=0;i getAllFiles() 517 | { 518 | list fileSystemList; 519 | 520 | for(map >::iterator it = fileNameIndexMap.begin();it!=fileNameIndexMap.end();it++) 521 | { 522 | for(list::iterator it1 = (*it).second.begin();it1!=(*it).second.end();it1++) 523 | { 524 | fileSystemList.push_back((*it1)); 525 | } 526 | } 527 | return fileSystemList; 528 | } 529 | 530 | void deleteFromIndex(int fileNumber) 531 | { 532 | bool breakFlag = 0; 533 | // printf("\nJust need to delete\n"); 534 | 535 | //delete from the Indexes and also from LRU + from harddisk 536 | for(map >::iterator it1 = bitVectorIndexMap.begin();it1!=bitVectorIndexMap.end();it1++) 537 | { 538 | for(list::iterator it2 = (*it1).second.begin();it2!=(*it1).second.end();it2++) 539 | { 540 | if((*it2) == fileNumber) 541 | { 542 | (*it1).second.remove((*it2)); 543 | breakFlag = 1; 544 | if((*it1).second.size() == 0) 545 | bitVectorIndexMap.erase((*it1).first); 546 | break; 547 | } 548 | } 549 | if(breakFlag) 550 | break; 551 | } 552 | 553 | breakFlag = 0; 554 | //deleting from FileNameIndexMap 555 | for(map >::iterator it1 = fileNameIndexMap.begin();it1!=fileNameIndexMap.end();it1++) 556 | { 557 | for(list::iterator it2 = (*it1).second.begin();it2!=(*it1).second.end();it2++) 558 | { 559 | if((*it2) == fileNumber) 560 | { 561 | (*it1).second.remove((*it2)); 562 | breakFlag = 1; 563 | if((*it1).second.size() == 0) 564 | fileNameIndexMap.erase((*it1).first); 565 | break; 566 | } 567 | } 568 | if(breakFlag) 569 | break; 570 | } 571 | 572 | breakFlag = 0; 573 | //deleting from sha1IndexMap 574 | for(map >::iterator it1 = sha1IndexMap.begin();it1!=sha1IndexMap.end();it1++) 575 | { 576 | for(list::iterator it2 = (*it1).second.begin();it2!=(*it1).second.end();it2++) 577 | { 578 | if((*it2) == fileNumber) 579 | { 580 | (*it1).second.remove((*it2)); 581 | breakFlag = 1; 582 | if((*it1).second.size() == 0) 583 | sha1IndexMap.erase((*it1).first); 584 | break; 585 | } 586 | } 587 | if(breakFlag) 588 | break; 589 | } 590 | 591 | //remove from cache 592 | list::iterator result = find(cacheLRU.begin(), cacheLRU.end(), (int)fileNumber); 593 | if(result!=cacheLRU.end()) 594 | { 595 | struct metaData metadata = populateMetaData(fileNumber); 596 | currentCacheSize -= metadata.fileSize; 597 | cacheLRU.remove((fileNumber)); 598 | } 599 | 600 | unsigned char removeString[256]; 601 | memset(removeString, '\0', 256); 602 | sprintf((char *)removeString, "%s/%d.data", filesDir, fileNumber); 603 | remove((char *)removeString); 604 | 605 | memset(removeString, '\0', 256); 606 | sprintf((char *)removeString, "%s/%d.meta", filesDir, fileNumber); 607 | remove((char *)removeString); 608 | 609 | memset(removeString, '\0', 256); 610 | sprintf((char *)removeString, "%s/%d.pass", filesDir, fileNumber); 611 | remove((char *)removeString); 612 | } 613 | 614 | // Clears all the filesystem. Used with reset command 615 | // option 616 | void deleteAllFiles() 617 | { 618 | unsigned char removeString[256]; 619 | 620 | for(map >::iterator it1 = bitVectorIndexMap.begin();it1!=bitVectorIndexMap.end();it1++) 621 | { 622 | for(list::iterator it2 = (*it1).second.begin();it2!=(*it1).second.end();it2++) 623 | { 624 | memset(removeString, '\0', 256); 625 | sprintf((char *)removeString, "%s/%d.data", filesDir, (*it2)); 626 | remove((char *)removeString); 627 | 628 | memset(removeString, '\0', 256); 629 | sprintf((char *)removeString, "%s/%d.meta", filesDir, (*it2)); 630 | remove((char *)removeString); 631 | 632 | memset(removeString, '\0', 256); 633 | sprintf((char *)removeString, "%s/%d.pass", filesDir, (*it2)); 634 | remove((char *)removeString); 635 | } 636 | } 637 | bitVectorIndexMap.clear(); 638 | sha1IndexMap.clear(); 639 | fileNameIndexMap.clear(); 640 | cacheLRU.clear(); 641 | currentCacheSize = 0; 642 | unsigned char kwrd_index_file[256]; 643 | sprintf((char *)kwrd_index_file, "%s/kwrd_index", myInfo->homeDir); 644 | unsigned char name_index_file[256]; 645 | sprintf((char *)name_index_file, "%s/name_index", myInfo->homeDir); 646 | unsigned char sha1_index_file[256]; 647 | sprintf((char *)sha1_index_file, "%s/sha1_index", myInfo->homeDir); 648 | unsigned char cacheLRU[256]; 649 | sprintf((char *)cacheLRU, "%s/cacheLRU", myInfo->homeDir); 650 | 651 | remove((char *)kwrd_index_file); 652 | remove((char *)name_index_file); 653 | remove((char *)sha1_index_file); 654 | remove((char *)cacheLRU); 655 | } 656 | 657 | 658 | // Save a tmp file in the permanent space of the filesystem 659 | void writeFileToPermanent(unsigned char *metadata_str, unsigned char *fileName) 660 | { 661 | bool replaceFlag = 1; 662 | struct metaData metadata = populateMetaDataFromString_noFileID(metadata_str); 663 | int ret_val = doesFileExist(metadata); 664 | if(ret_val != -1) 665 | { 666 | updateLRU(ret_val); 667 | // printf("File Exist already\n"); 668 | replaceFlag = 0; 669 | } 670 | 671 | FILE *f_ext = fopen((char *)extFile, "rb"); 672 | unsigned char input[10]; 673 | memset(input, '\0', 10); 674 | if(f_ext!=NULL) 675 | { 676 | printf("File Already exist, do you want to replace [Yes/No] "); 677 | scanf("%s", input); 678 | input[9] = '\0'; 679 | if(input[0] == 'y' || input[0] == 'Y') 680 | { 681 | fclose(f_ext); 682 | f_ext = fopen((char *)extFile, "wb"); 683 | 684 | } 685 | else 686 | { 687 | fclose(f_ext); 688 | return; 689 | } 690 | } 691 | else 692 | { 693 | f_ext = fopen((char *)extFile, "wb"); 694 | } 695 | 696 | 697 | int temp = 0; 698 | if(replaceFlag) 699 | temp = updateGlobalFileNumber(); 700 | 701 | //struct metaData metadata = populateMetaDataFromCPPString(string((char *)metadata_str)); 702 | 703 | //writeData(metadata); 704 | char ch; 705 | unsigned char tempFileName[256]; 706 | 707 | FILE *f, *f1; 708 | if(replaceFlag) 709 | { 710 | sprintf((char *)tempFileName, "%s/%d.data", filesDir, temp); 711 | f = fopen((char *)fileName, "rb"); 712 | f1 = fopen((char *)tempFileName, "wb"); 713 | while(fread(&ch,1,1,f)!=0) 714 | { 715 | fwrite(&ch, 1,1, f1); 716 | fwrite(&ch, 1,1, f_ext); 717 | } 718 | fclose(f); 719 | fclose(f1); 720 | fclose(f_ext); 721 | 722 | if(fclose(f1) != 0 || fclose(f_ext) != 0) 723 | { 724 | if(errno == EIO) 725 | { 726 | // printf("\nDisk Quota Reached, could not save file\n"); 727 | writeLogEntry((unsigned char *)"Disk Quota Reached, could not save file\n"); 728 | remove((char *)tempFileName); 729 | remove((char *)extFile); 730 | return; 731 | } 732 | } 733 | 734 | } 735 | else 736 | { 737 | f = fopen((char *)fileName, "rb"); 738 | while(fread(&ch,1,1,f)!=0) 739 | { 740 | fwrite(&ch, 1,1, f_ext); 741 | } 742 | fclose(f); 743 | fclose(f_ext); 744 | 745 | if(fclose(f_ext) != 0) 746 | { 747 | if(errno == EIO) 748 | { 749 | // printf("\nDisk Quota Reached, could not save file\n"); 750 | writeLogEntry((unsigned char *)"Disk Quota Reached, could not save file\n"); 751 | remove((char *)tempFileName); 752 | remove((char *)extFile); 753 | return; 754 | } 755 | } 756 | } 757 | 758 | 759 | if(replaceFlag) 760 | { 761 | writeMetaData(metadata, temp); 762 | populateBitVectorIndexMap(metadata.bitVector, temp); 763 | populateSha1IndexMap(metadata.sha1, temp); 764 | populateFileNameIndexMap(metadata.fileName, temp); 765 | } 766 | } 767 | 768 | 769 | // Save a file in the cache of the filesystem 770 | void writeFileToCache(unsigned char *metadata_str, unsigned char *fileName) 771 | { 772 | 773 | // printf("%s", metadata_str); 774 | struct metaData metadata = populateMetaDataFromString_noFileID(metadata_str); 775 | 776 | /*printf("After many things\n\n"); 777 | for(int i=0;i<20;i++) 778 | printf("%02x", metadata.sha1[i]); 779 | printf("\n\n");*/ 780 | int ret_val = doesFileExist(metadata); 781 | if(ret_val != -1) 782 | { 783 | updateLRU(ret_val); 784 | return; 785 | } 786 | 787 | int temp = updateGlobalFileNumber(); 788 | 789 | int ret = storeInLRU(metadata, temp); 790 | if(ret == -1) 791 | return; 792 | 793 | 794 | //writeData(metadata); 795 | char ch; 796 | unsigned char tempFileName[256]; 797 | sprintf((char *)tempFileName, "%s/%d.data", filesDir, temp); 798 | 799 | FILE *f = fopen((char *)fileName, "rb"); 800 | FILE *f1 = fopen((char *)tempFileName, "wb"); 801 | while(fread(&ch,1,1,f)!=0) 802 | fwrite(&ch, 1,1, f1); 803 | fclose(f); 804 | if(fclose(f1) != 0) 805 | { 806 | if(errno == EIO) 807 | { 808 | // printf("\nDisk Quota Reached, could not save file\n"); 809 | writeLogEntry((unsigned char *)"Disk Quota Reached, could not save file\n"); 810 | cacheLRU.remove(temp); 811 | remove((char *)tempFileName); 812 | return; 813 | } 814 | } 815 | writeMetaData(metadata, temp); 816 | populateBitVectorIndexMap(metadata.bitVector, temp); 817 | populateSha1IndexMap(metadata.sha1, temp); 818 | populateFileNameIndexMap(metadata.fileName, temp); 819 | 820 | } 821 | 822 | 823 | // Returns true if the file exists in the filesystem 824 | int doesFileExist(struct metaData metadata) 825 | { 826 | list tempList = fileNameSearch(metadata.fileName); 827 | for(list ::iterator it = tempList.begin();it!=tempList.end();it++) 828 | { 829 | struct metaData metadata_temp = populateMetaData((*it)); 830 | if(strncmp((char *)metadata_temp.nonce, (char *)metadata.nonce, 20)==0) 831 | return (*it); 832 | } 833 | return -1; 834 | } 835 | -------------------------------------------------------------------------------- /indexSearch.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | 21 | 22 | extern void createBitVector(unsigned char *, unsigned char *keyword); 23 | extern list keywordSearch(unsigned char *completeStr); 24 | extern list fileNameSearch(unsigned char *fileName); 25 | extern list sha1Search(unsigned char *sha1String); 26 | extern void writeIndexToFile(); 27 | extern void readIndexFromFile(); 28 | unsigned char *toSHA1(unsigned char *str); 29 | unsigned char *toMD5(unsigned char *str); 30 | -------------------------------------------------------------------------------- /iniParser.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include "iniParser.h" 10 | #include "main.h" 11 | 12 | using namespace std; 13 | 14 | 15 | //Creates the node instacne id, using the timestamp 16 | void setNodeInstanceId(){ 17 | // Should be called once node_id of the node is set 18 | time_t sec; 19 | sec = time (NULL) ; 20 | sprintf((char *)myInfo->node_instance_id, "%s_%ld", myInfo->node_id, (long)sec) ; 21 | // printf("%s\n", myInfo->node_instance_id) ; 22 | } 23 | 24 | 25 | 26 | //Initilaizing default values for myInfo, default values for the nodes parameters 27 | void populatemyInfo() 28 | { 29 | myInfo = (struct myStartInfo *)malloc(sizeof(myStartInfo)); 30 | myInfo->myBeaconList = new list ; 31 | myInfo->portNo = 0; 32 | gethostname((char *)myInfo->hostName, 256); 33 | myInfo->location = 0; 34 | memset(myInfo->homeDir, '\0', 512); 35 | strncpy((char *)myInfo->logFileName, "servant.log", strlen("servant.log")); 36 | myInfo->logFileName[strlen("servant.log")]='\0'; 37 | myInfo->autoShutDown = 900; 38 | myInfo->autoShutDown_permanent = 900; 39 | myInfo->ttl = 30; 40 | myInfo->msgLifeTime = 30; 41 | myInfo->getMsgLifeTime = 300; 42 | myInfo->initNeighbor = 3; 43 | myInfo->joinTimeOut = 15; 44 | myInfo->joinTimeOut_permanent = myInfo->joinTimeOut; 45 | myInfo->checkResponseTimeout = 15; 46 | myInfo->keepAliveTimeOut = 60; 47 | myInfo->minNeighbor = 2; 48 | myInfo->noCheck = 0; 49 | myInfo->cacheProb = 0.1; 50 | myInfo->storeProb = 0.1; 51 | myInfo->neighborStoreProb = 0.2; 52 | myInfo->cacheSize = 500; 53 | myInfo->isBeacon = false; 54 | //myInfo->retry = 30; 55 | myInfo->retry = 7; 56 | memset(myInfo->node_id, '\0', 265) ; 57 | memset(myInfo->node_instance_id, '\0', 300) ; 58 | 59 | } 60 | 61 | //function to print the values of myInfo, node default values 62 | void printmyInfo() 63 | { 64 | printf("Value for myInfo is:--\n\n"); 65 | 66 | printf("Port No: %d\n",myInfo->portNo); 67 | printf("hostName: %s\n",myInfo->hostName); 68 | printf("Location: %d\n",myInfo->location); 69 | printf("HomeDir: %s\n",myInfo->homeDir); 70 | printf("logFileName: %s\n",myInfo->logFileName); 71 | printf("autoShutDown: %d\n",myInfo->autoShutDown); 72 | printf("TTL: %d\n",myInfo->ttl); 73 | printf("msgLifeTime: %d\n",myInfo->msgLifeTime); 74 | printf("getMsgLifeTime: %d\n",myInfo->getMsgLifeTime); 75 | printf("initNeighbor: %d\n",myInfo->initNeighbor); 76 | printf("joinTimeOut: %d\n",myInfo->joinTimeOut); 77 | printf("keepAliveTimeOut: %d\n",myInfo->keepAliveTimeOut); 78 | printf("minNeighbor: %d\n",myInfo->minNeighbor); 79 | printf("noCheck: %d\n",myInfo->noCheck); 80 | printf("cacheProb: %lf\n",myInfo->cacheProb); 81 | printf("storeProb: %lf\n",myInfo->storeProb); 82 | printf("neighborStoreProb: %lf\n",myInfo->neighborStoreProb); 83 | printf("cacheSize: %d\n",myInfo->cacheSize); 84 | printf("retry: %d\n",myInfo->retry); 85 | printf("isBeacon: %d\n",myInfo->isBeacon); 86 | 87 | } 88 | 89 | // removes white spaces from the line read from file 90 | void removeSpaces(unsigned char *readLine) 91 | { 92 | unsigned char tempreadLine[512]; 93 | int j=0; 94 | 95 | for(int i=0;readLine[i]!='\0';i++) 96 | { 97 | if(readLine[i]=='\"') 98 | { 99 | i++; 100 | while(readLine[i]!='\"') 101 | { 102 | if(readLine[i]=='\0') 103 | { 104 | i--; 105 | break; 106 | } 107 | tempreadLine[j++]=readLine[i]; 108 | i++; 109 | } 110 | } 111 | else 112 | { 113 | if(readLine[i]==' ' || readLine[i]=='\n' || readLine[i]=='\t' || readLine[i]=='\r') 114 | continue; 115 | else 116 | { 117 | tempreadLine[j++]=readLine[i]; 118 | } 119 | } 120 | 121 | } 122 | tempreadLine[j]='\0'; 123 | strncpy((char *)readLine, (char *)tempreadLine, strlen((char *)tempreadLine)); 124 | readLine[strlen((char *)tempreadLine)]='\0'; 125 | } 126 | 127 | 128 | // Parses the ini file passed as command line argument, this function populates the myInfo structure of the node 129 | void parseINIfile(unsigned char *fileName) 130 | { 131 | FILE *f=fopen((char *)fileName,"r"); 132 | int initFlag=0, beaconFlag=0; 133 | int visitedFlag[20]; 134 | memset(&visitedFlag, 0, sizeof(visitedFlag)); 135 | 136 | if(f==NULL) 137 | { 138 | //printf("Error in file opening\n"); 139 | writeLogEntry((unsigned char *)"Error in Ini file opening\n"); 140 | exit(1); 141 | } 142 | 143 | 144 | //file passed, opened successfully 145 | unsigned char readLine[512]; 146 | unsigned char *key, *value; 147 | 148 | //reading the ini file to parse it 149 | while(fgets((char *)readLine, 511, f)!=NULL) 150 | { 151 | //removes trailing space, tabs, new line, CR 152 | removeSpaces(readLine); 153 | if(!(*readLine)) 154 | continue; 155 | //printf("2. readLine is: %s\n", readLine); 156 | 157 | if(strcasecmp((char *)readLine, "[init]")==0) 158 | { 159 | if(visitedFlag[0]==0) 160 | visitedFlag[0]=1; 161 | else 162 | { 163 | visitedFlag[0]=2; 164 | continue; 165 | } 166 | 167 | initFlag = 1; 168 | beaconFlag=0; 169 | continue; 170 | } 171 | else 172 | { 173 | if(strcasecmp((char *)readLine, "[beacons]")==0) 174 | { 175 | if(visitedFlag[1]==0) 176 | visitedFlag[1]=1; 177 | else 178 | { 179 | visitedFlag[1]=2; 180 | continue; 181 | } 182 | 183 | beaconFlag=1; 184 | initFlag=0; 185 | continue; 186 | } 187 | else 188 | { 189 | key=(unsigned char *)strtok((char *)readLine,"="); 190 | 191 | if(initFlag) 192 | { 193 | if(!strcasecmp((char *)key, "port")) 194 | { 195 | if(visitedFlag[2]==0) 196 | { 197 | if(visitedFlag[0]==2) 198 | continue; 199 | visitedFlag[2]=1; 200 | } 201 | else 202 | continue; 203 | 204 | value=(unsigned char *)strtok(NULL,"="); 205 | myInfo->portNo=atoi((char *)value); 206 | } 207 | else if(!strcasecmp((char *)key, "location")) 208 | { 209 | if(visitedFlag[3]==0) 210 | { 211 | if(visitedFlag[0]==2) 212 | continue; 213 | visitedFlag[3]=1; 214 | } 215 | else 216 | continue; 217 | 218 | value=(unsigned char *)strtok(NULL,"="); 219 | myInfo->location=atol((char *)value); 220 | } 221 | else if(!strcasecmp((char *)key, "homedir")) 222 | { 223 | if(visitedFlag[4]==0) 224 | { 225 | if(visitedFlag[0]==2) 226 | continue; 227 | visitedFlag[4]=1; 228 | } 229 | else 230 | continue; 231 | value=(unsigned char *)strtok(NULL,"="); 232 | strncpy((char *)myInfo->homeDir,(char *)value, strlen((char *)value)); 233 | myInfo->homeDir[strlen((char *)value)]='\0'; 234 | } 235 | else if(!strcasecmp((char *)key, "logfilename")) 236 | { 237 | if(visitedFlag[5]==0) 238 | { 239 | if(visitedFlag[0]==2) 240 | continue; 241 | visitedFlag[5]=1; 242 | } 243 | else 244 | continue; 245 | value=(unsigned char *)strtok(NULL,"="); 246 | strncpy((char *)myInfo->logFileName,(char *)value, strlen((char *)value)); 247 | myInfo->logFileName[strlen((char *)value)]='\0'; 248 | } 249 | else if(!strcasecmp((char *)key, "autoshutdown")) 250 | { 251 | if(visitedFlag[6]==0) 252 | { 253 | if(visitedFlag[0]==2) 254 | continue; 255 | visitedFlag[6]=1; 256 | } 257 | else 258 | continue; 259 | 260 | value=(unsigned char *)strtok(NULL,"="); 261 | myInfo->autoShutDown=atoi((char *)value); 262 | } 263 | else if(!strcasecmp((char *)key, "ttl")) 264 | { 265 | if(visitedFlag[7]==0) 266 | { 267 | if(visitedFlag[0]==2) 268 | continue; 269 | visitedFlag[7]=1; 270 | } 271 | else 272 | continue; 273 | value=(unsigned char *)strtok(NULL,"="); 274 | myInfo->ttl=atoi((char *)value); 275 | } 276 | else if(!strcasecmp((char *)key, "msglifetime")) 277 | { 278 | if(visitedFlag[8]==0) 279 | { 280 | if(visitedFlag[0]==2) 281 | continue; 282 | visitedFlag[8]=1; 283 | } 284 | else 285 | continue; 286 | value=(unsigned char *)strtok(NULL,"="); 287 | myInfo->msgLifeTime=atoi((char *)value); 288 | } 289 | else if(!strcasecmp((char *)key, "getmsglifetime")) 290 | { 291 | if(visitedFlag[9]==0) 292 | { 293 | if(visitedFlag[0]==2) 294 | continue; 295 | visitedFlag[9]=1; 296 | } 297 | else 298 | continue; 299 | value=(unsigned char *)strtok(NULL,"="); 300 | myInfo->getMsgLifeTime=atoi((char *)value); 301 | } 302 | else if(!strcasecmp((char *)key, "initneighbors")) 303 | { 304 | if(visitedFlag[10]==0) 305 | { 306 | if(visitedFlag[0]==2) 307 | continue; 308 | visitedFlag[10]=1; 309 | } 310 | else 311 | continue; 312 | value=(unsigned char *)strtok(NULL,"="); 313 | myInfo->initNeighbor=atoi((char *)value); 314 | } 315 | else if(!strcasecmp((char *)key, "jointimeout")) 316 | { 317 | if(visitedFlag[11]==0) 318 | { 319 | if(visitedFlag[0]==2) 320 | continue; 321 | visitedFlag[11]=1; 322 | } 323 | else 324 | continue; 325 | value=(unsigned char *)strtok(NULL,"="); 326 | myInfo->joinTimeOut=atoi((char *)value); 327 | myInfo->checkResponseTimeout=atoi((char *)value); 328 | } 329 | else if(!strcasecmp((char *)key, "keepalivetimeout")) 330 | { 331 | if(visitedFlag[12]==0) 332 | { 333 | if(visitedFlag[0]==2) 334 | continue; 335 | visitedFlag[12]=1; 336 | } 337 | else 338 | continue; 339 | value=(unsigned char *)strtok(NULL,"="); 340 | myInfo->keepAliveTimeOut=atoi((char *)value); 341 | } 342 | else if(!strcasecmp((char *)key, "minneighbors")) 343 | { 344 | if(visitedFlag[13]==0) 345 | { 346 | if(visitedFlag[0]==2) 347 | continue; 348 | visitedFlag[13]=1; 349 | } 350 | else 351 | continue; 352 | value=(unsigned char *)strtok(NULL,"="); 353 | myInfo->minNeighbor=atoi((char *)value); 354 | } 355 | else if(!strcasecmp((char *)key, "nocheck")) 356 | { 357 | if(visitedFlag[14]==0) 358 | { 359 | if(visitedFlag[0]==2) 360 | continue; 361 | visitedFlag[14]=1; 362 | } 363 | else 364 | continue; 365 | value=(unsigned char *)strtok(NULL,"="); 366 | myInfo->noCheck=atoi((char *)value); 367 | } 368 | else if(!strcasecmp((char *)key, "cacheprob")) 369 | { 370 | if(visitedFlag[15]==0) 371 | { 372 | if(visitedFlag[0]==2) 373 | continue; 374 | visitedFlag[15]=1; 375 | } 376 | else 377 | continue; 378 | value=(unsigned char *)strtok(NULL,"="); 379 | myInfo->cacheProb=atof((char *)value); 380 | } 381 | else if(!strcasecmp((char *)key, "storeprob")) 382 | { 383 | if(visitedFlag[16]==0) 384 | { 385 | if(visitedFlag[0]==2) 386 | continue; 387 | visitedFlag[16]=1; 388 | } 389 | else 390 | continue; 391 | value=(unsigned char *)strtok(NULL,"="); 392 | myInfo->storeProb=atof((char *)value); 393 | } 394 | else if(!strcasecmp((char *)key, "neighborstoreprob")) 395 | { 396 | if(visitedFlag[17]==0) 397 | { 398 | if(visitedFlag[0]==2) 399 | continue; 400 | visitedFlag[17]=1; 401 | } 402 | else 403 | continue; 404 | value=(unsigned char *)strtok(NULL,"="); 405 | myInfo->neighborStoreProb=atof((char *)value); 406 | } 407 | else if(!strcasecmp((char *)key, "cachesize")) 408 | { 409 | if(visitedFlag[18]==0) 410 | { 411 | if(visitedFlag[0]==2) 412 | continue; 413 | visitedFlag[18]=1; 414 | } 415 | else 416 | continue; 417 | value=(unsigned char *)strtok(NULL,"="); 418 | myInfo->cacheSize=atoi((char *)value); 419 | } 420 | } 421 | else 422 | { 423 | if(!strcasecmp((char *)key, "retry")) 424 | { 425 | if(visitedFlag[19]==0) 426 | { 427 | if(visitedFlag[1]==2) 428 | continue; 429 | visitedFlag[19]=1; 430 | } 431 | else 432 | { 433 | continue; 434 | } 435 | value=(unsigned char *)strtok(NULL, "="); 436 | myInfo->retry=atoi((char *)value); 437 | } 438 | else 439 | { 440 | value=(unsigned char *)strtok((char *)key, ":"); 441 | struct beaconList *beaconNode = (struct beaconList *)malloc(sizeof(struct beaconList)); 442 | //strncpy((char *)beaconNode->hostName, (char *)value, strlen((char *)value)); 443 | for(unsigned int i=0;ihostName[i] = value[i]; 445 | beaconNode->hostName[strlen((char *)value)] = '\0'; 446 | value=(unsigned char *)strtok(NULL,":"); 447 | beaconNode->portNo = (unsigned int)atoi((char *)value); 448 | myInfo->myBeaconList->push_back(beaconNode); 449 | //printf("Host name is : %s\tHost Port no: %d\n", beaconNode->hostName, beaconNode->portNo); 450 | } 451 | 452 | } 453 | } 454 | } 455 | } 456 | fclose(f) ; 457 | } 458 | -------------------------------------------------------------------------------- /iniParser.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | 22 | using namespace std; 23 | 24 | struct beaconList 25 | { 26 | unsigned char hostName[256]; 27 | unsigned short int portNo; 28 | }; 29 | 30 | struct myStartInfo 31 | { 32 | unsigned char hostName[256]; 33 | unsigned short int portNo; 34 | uint32_t location; 35 | unsigned char homeDir[512]; 36 | unsigned char logFileName[256]; 37 | unsigned int autoShutDown; 38 | unsigned int autoShutDown_permanent; 39 | uint8_t ttl; 40 | unsigned int msgLifeTime; 41 | unsigned int getMsgLifeTime; 42 | unsigned int initNeighbor; 43 | unsigned int joinTimeOut; 44 | unsigned int joinTimeOut_permanent; 45 | unsigned int keepAliveTimeOut; 46 | unsigned int minNeighbor; 47 | unsigned int noCheck; 48 | double cacheProb; 49 | double storeProb; 50 | double neighborStoreProb; 51 | unsigned int cacheSize; 52 | unsigned int retry; 53 | list *myBeaconList; 54 | 55 | bool isBeacon; // to check if the current node is beacon or not 56 | unsigned char node_id[265] ; // To store the unique node ID of this node 57 | unsigned char node_instance_id[300]; // To store the node instance ID, node_id + time when node started 58 | uint8_t status_ttl ; 59 | unsigned char status_file[256] ; 60 | unsigned int statusResponseTimeout ; 61 | unsigned int checkResponseTimeout ; 62 | }; 63 | 64 | extern struct myStartInfo *myInfo; 65 | 66 | extern void parseINIfile(unsigned char *fileName); 67 | 68 | extern void populatemyInfo(); 69 | 70 | void printmyInfo(); 71 | 72 | extern void setNodeInstanceId() ; 73 | 74 | -------------------------------------------------------------------------------- /keepAliveTimer.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #include "main.h" 7 | #include "keepAliveTimer.h" 8 | 9 | 10 | //Keep alive timer thread, sends the KEEP ALIVE message every keepalivetimeout/3 11 | //this message indicates that the node is still alive 12 | void *keepAliveTimer_thread(void *arg){ 13 | 14 | while(!shutDown) 15 | { 16 | sleep(1); 17 | 18 | //global flag denttoing shutdown of the nodes 19 | if(shutDown) 20 | { 21 | //printf("KeepAlive thread halted\n"); 22 | break; 23 | } 24 | //for (map::iterator it = connectionMap.begin(); it != connectionMap.end(); ++it){ 25 | //iterate through the neighbprs list and send KEEP ALIVE messages 26 | pthread_mutex_lock(&nodeConnectionMapLock) ; 27 | for (map::iterator it = nodeConnectionMap.begin(); it != nodeConnectionMap.end(); ++it){ 28 | //printf("Hi I am here!!!!\n"); 29 | pthread_mutex_lock(&connectionMapLock) ; 30 | if(connectionMap[(*it).second].keepAliveTimer > 0) 31 | connectionMap[(*it).second].keepAliveTimer--; 32 | else 33 | { 34 | if(connectionMap[(*it).second].keepAliveTimeOut!=-1 && connectionMap[(*it).second].isReady==2) 35 | { 36 | struct Message mes; 37 | mes.type = 0xf8; 38 | mes.status = 0; 39 | //printf("Sent Keep Alive Message to: %d\n", (*it).first); 40 | pushMessageinQ((*it).second, mes); 41 | } 42 | } 43 | pthread_mutex_unlock(&connectionMapLock) ; 44 | } 45 | pthread_mutex_unlock(&nodeConnectionMapLock) ; 46 | } 47 | pthread_exit(0); 48 | return 0; 49 | } 50 | 51 | -------------------------------------------------------------------------------- /keepAliveTimer.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | extern void *keepAliveTimer_thread(void *arg); 6 | -------------------------------------------------------------------------------- /keyboard.cc: -------------------------------------------------------------------------------- 1 | #include "main.h" 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include "iniParser.h" 7 | #include "signalHandler.h" 8 | #include "indexSearch.h" 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include "indexSearch.h" 20 | 21 | using namespace std ; 22 | 23 | //This thread is a keborad thread, which tajes input from user, such as 24 | // shutdown and STATUS NEIGHBORS..... 25 | // handling of SIGINT 26 | void *keyboard_thread(void *arg){ 27 | fd_set rfds; 28 | //struct timeval tv; 29 | //char *inp = new char[512] ; 30 | bool checkFlag = 0; 31 | char *inp; 32 | inp = (char *)malloc(1024 * sizeof(char)) ; 33 | memset(inp, '\0', 1024) ; 34 | FD_ZERO(&rfds); 35 | FD_SET(0, &rfds); 36 | signal(SIGUSR2, my_handler); 37 | sigset_t new_t ; 38 | sigemptyset(&new_t); 39 | sigaddset(&new_t, SIGINT); 40 | pthread_sigmask(SIG_UNBLOCK, &new_t, NULL); 41 | //signal(SIGINT, my_handler); 42 | //alarm(myInfo->autoShutDown); 43 | 44 | while(!shutDown){ 45 | /*pthread_sigmask(SIG_UNBLOCK, &new_t, NULL);*/ 46 | signal(SIGINT, my_handler); 47 | printf("\nservant:%d> ", myInfo->portNo) ; 48 | if(shutDown) 49 | break; 50 | //string inpS ; 51 | //getline(cin, inpS) ; 52 | //inp = const_cast (inpS.c_str()) ; 53 | fgets((char *)inp, 511, stdin); 54 | 55 | if(shutDown) 56 | break; 57 | 58 | 59 | //User enters the 'shutdown' command, nodes shutdown after sending the notify message to it's neighbors 60 | if(!strcasecmp((char *)inp, "shutdown\n")) 61 | { 62 | /*sigset_t new_t; 63 | sigemptyset(&new_t); 64 | sigaddset(&new_t, SIGUSR2); 65 | pthread_sigmask(SIG_BLOCK, &new_t, NULL);*/ 66 | 67 | shutDown = 1 ; 68 | 69 | //for (map::iterator it = connectionMap.begin(); it != connectionMap.end(); ++it) 70 | pthread_mutex_lock(&nodeConnectionMapLock) ; 71 | for (map::iterator it = nodeConnectionMap.begin(); it != nodeConnectionMap.end(); ++it){ 72 | notifyMessageSend((*it).second, 1); 73 | } 74 | pthread_mutex_unlock(&nodeConnectionMapLock) ; 75 | sleep(1); 76 | //sending the SIGTERM signal to the main thread, for shutdown 77 | kill(node_pid, SIGTERM); 78 | break; 79 | } 80 | //user enters the status neighbors command, this inittates the flooding of status message 81 | // creates the status file, nam file and shows the network 82 | else if(strstr((char *)inp, "status neighbors")!=NULL) 83 | { 84 | 85 | //fprintf(stdin, "%s ", inp); 86 | checkFlag = 0; 87 | 88 | unsigned char *value = (unsigned char *)strtok((char *)inp, " "); 89 | value = (unsigned char *)strtok(NULL, " "); 90 | 91 | unsigned char fileName[256]; 92 | memset(&fileName, '\0', 256); 93 | 94 | //gets the ttl value here 95 | value = (unsigned char *)strtok(NULL, " "); 96 | if(value ==NULL) 97 | continue; 98 | //check if the entered value id digit or not 99 | for(int j=0;j<(int)strlen((char *)value);j++) 100 | if(isdigit(value[j]) == 0) 101 | continue; 102 | myInfo->status_ttl = (uint8_t)atoi((char *)value); 103 | 104 | //name of the status file 105 | value = (unsigned char *)strtok(NULL, "\n"); 106 | if(value ==NULL) 107 | continue; 108 | strncpy((char *)myInfo->status_file, (char *)value, strlen((char *)value)) ; 109 | myInfo->status_file[strlen((char *)myInfo->status_file)] = '\0'; 110 | 111 | myInfo->statusResponseTimeout = myInfo->msgLifeTime + 10 ; 112 | FILE *fp = fopen((char *)myInfo->status_file, "w") ; 113 | if (fp == NULL){ 114 | //fprintf(stderr,"File open failed\n") ; 115 | writeLogEntry((unsigned char *)"In Keyborad thread: Status File open failed\n"); 116 | exit(0) ; 117 | } 118 | fputs("V -t * -v 1.0a5\n", fp) ; 119 | fclose(fp) ; 120 | getStatus() ; 121 | 122 | // waiting for status time out, so that command prompt can be returned 123 | pthread_mutex_lock(&statusMsgLock) ; 124 | statusTimerFlag = 1 ; 125 | pthread_cond_wait(&statusMsgCV, &statusMsgLock); 126 | pthread_mutex_unlock(&statusMsgLock) ; 127 | //printf("WOW!!!! %d\n", myInfo->statusResponseTimeout); 128 | writeToStatusFile() ; 129 | } 130 | else if(strstr((char *)inp, "status files")!=NULL) 131 | { 132 | 133 | //fprintf(stdin, "%s ", inp); 134 | checkFlag = 0; 135 | 136 | unsigned char *value = (unsigned char *)strtok((char *)inp, " "); 137 | value = (unsigned char *)strtok(NULL, " "); 138 | if(value == NULL) 139 | continue; 140 | 141 | unsigned char fileName[256]; 142 | memset(&fileName, '\0', 256); 143 | 144 | //gets the ttl value here 145 | value = (unsigned char *)strtok(NULL, " "); 146 | if(value ==NULL) 147 | continue; 148 | //check if the entered value id digit or not 149 | bool contFlag1 = 0; 150 | // for(int j=0;j<(int)strlen((char *)value);j++) 151 | // if(isdigit(value[j]) == 0) 152 | // { 153 | // contFlag1 = 1; 154 | // break; 155 | // } 156 | if(atoi((char *)value) == 0){ 157 | for(int i=0;i<(int)strlen((char *)value);i++) 158 | if(value[i] != '0' ) 159 | { 160 | contFlag1 = 1; 161 | break; 162 | } 163 | } 164 | if(contFlag1) 165 | continue; 166 | myInfo->status_ttl = (uint8_t)atoi((char *)value); 167 | 168 | //name of the status file 169 | value = (unsigned char *)strtok(NULL, "\n"); 170 | if(value ==NULL) 171 | continue; 172 | strncpy((char *)myInfo->status_file, (char *)value, strlen((char *)value)) ; 173 | myInfo->status_file[strlen((char *)myInfo->status_file)] = '\0'; 174 | 175 | myInfo->statusResponseTimeout = myInfo->msgLifeTime + 10 ; 176 | FILE *fp = fopen((char *)myInfo->status_file, "w") ; 177 | if (fp == NULL){ 178 | //fprintf(stderr,"File open failed\n") ; 179 | writeLogEntry((unsigned char *)"In Keyborad thread: Status File open failed\n"); 180 | exit(0) ; 181 | } 182 | fclose(fp) ; 183 | if(myInfo->status_ttl > 0) 184 | getStatusTypeFiles() ; 185 | 186 | // waiting for status time out, so that command prompt can be returned 187 | pthread_mutex_lock(&statusMsgLock) ; 188 | statusTimerFlag = 1 ; 189 | pthread_cond_wait(&statusMsgCV, &statusMsgLock); 190 | pthread_mutex_unlock(&statusMsgLock) ; 191 | //printf("WOW!!!! %d\n", myInfo->statusResponseTimeout); 192 | writeToStatusFile_TypeFiles() ; 193 | } 194 | else if(strncasecmp((char *)inp, "store ", 6) == 0) 195 | { 196 | //inp[strlen((char *)inp)-1] = '\0'; 197 | checkFlag = 0; 198 | 199 | struct metaData metadata; 200 | unsigned char *key; 201 | memset(&metadata, 0, sizeof(metadata)); 202 | memset(&metadata.bitVector, 0, 128); 203 | metadata.keywords = new list(); 204 | 205 | unsigned char *value = (unsigned char *)strtok((char *)inp, " "); 206 | value = (unsigned char *)strtok(NULL, " "); 207 | if(value == NULL) 208 | continue; 209 | strncpy((char *)metadata.fileName, (char *)value, strlen((char *)value));//file Name stored 210 | 211 | //fileSize needed to be stored 212 | struct stat st; 213 | stat((char *)metadata.fileName, &st); 214 | metadata.fileSize = (long int)st.st_size; 215 | 216 | //sha1 value needed to be stored 217 | unsigned char buffer; 218 | //memset(buffer, '\0', 256); 219 | FILE *f = fopen((char *)metadata.fileName, "rb"); 220 | if(f==NULL) 221 | { 222 | printf("File Does not exist!!!\n"); 223 | exit(0); 224 | } 225 | SHA_CTX *c = (SHA_CTX *)malloc(sizeof(SHA_CTX)); 226 | //memset(c, 0, sizeof(c)); 227 | memset(c, 0, sizeof(c)); 228 | 229 | SHA1_Init(c); 230 | while(fread(&buffer,1,1,f)!=0) 231 | { 232 | SHA1_Update(c, &buffer, 1); 233 | } 234 | SHA1_Final(metadata.sha1, c); 235 | 236 | 237 | // printf("Sha1 calculated is: \n"); 238 | // for(int i=0;i<20;i++) 239 | // printf("%02x", metadata.sha1[i]); 240 | // printf("\n\n"); 241 | free(c); 242 | fclose(f); 243 | 244 | /*unsigned char password[SHA_DIGEST_LENGTH] ; 245 | GetUOID( const_cast ("password"), password, sizeof(password)) ; 246 | strncpy((char *)metadata.nonce, (char *)toSHA1(password), 20);*/ 247 | 248 | bool contFlag1 = 0; 249 | value = (unsigned char *)strtok(NULL, " "); //ttl value 250 | // for(int i=0;i<(int)strlen((char *)value);i++) 251 | // if(isdigit(value[i]) == 0 ) 252 | // { 253 | // contFlag1 = 1; 254 | // break; 255 | // } 256 | if(atoi((char *)value) == 0){ 257 | for(int i=0;i<(int)strlen((char *)value);i++) 258 | if(value[i] != '0' ) 259 | { 260 | contFlag1 = 1; 261 | break; 262 | } 263 | } 264 | 265 | if(contFlag1) 266 | continue; 267 | 268 | myInfo->status_ttl = atoi((char *)value) ; 269 | 270 | value = (unsigned char *)strtok(NULL, "\n"); 271 | 272 | if(value == NULL) 273 | continue; 274 | //unsigned char *temp_temp_value = (unsigned char *)strtok((char *)value, "?"); 275 | //printf("Vlaue is: %s\n", value); 276 | 277 | /*unsigned char temp_value[strlen((char *)value)]; 278 | memset(temp_value, '\0', sizeof(temp_value)); 279 | sprintf((char *)temp_value, "%s", (char *)value);*/ 280 | //while(sscanf((char *)value, "%s=%s ", key, temp_value)!=EOF) //keywords 281 | /*unsigned char key1[256], value1[256], input[256]; 282 | list *tempList; 283 | tempList = new list (); 284 | while(sscanf((char *)value, "%s=\"%s\"", key1, value1)!=EOF) 285 | { 286 | sprintf((char *)input, "%s=%s", key1, value1); 287 | printf("Input : %s %s\n", key1, value1); 288 | tempList->push_back(string((char *)input)); 289 | //tempList->push_back(string(value1)); 290 | } 291 | for (list::iterator it = tempList->begin(); it != tempList->end(); ++it){ 292 | printf("Values are: %s\n", (*it).c_str()); 293 | } 294 | free(tempList);*/ 295 | //printf("value is before: %s\n", value); 296 | for(int i=0;value[i]!='\0';i++) 297 | { 298 | if(value[i] == '"') 299 | { 300 | while(value[++i]!='"') 301 | { 302 | if(value[i]==' ') 303 | value[i] = '^'; 304 | } 305 | } 306 | } 307 | //printf("value is now: %s\n", value); 308 | unsigned char *saveptr1, *saveptr2, *saveptr3; 309 | bool contFlag = 0; 310 | while((key = (unsigned char *)strtok_r((char *)value, " ", (char **)&saveptr1))!=NULL) 311 | { 312 | //printf("String is %s, len %d\n", key, (int)strlen((char *)key)); 313 | /*unsigned char *temp_temp_value = (unsigned char *)malloc(strlen((char *)key)); 314 | sprintf((char *)temp_temp_value, "%s", (char *)temp_temp_value);*/ 315 | //printf("String is %s, len %d\n", temp_value, (int)strlen((char *)temp_value)); 316 | unsigned char *temp_key = (unsigned char *)strtok_r((char *)key, "=", (char **)&saveptr2); 317 | if(temp_key == NULL) 318 | { 319 | contFlag = 1; 320 | break; 321 | } 322 | 323 | //puts((char *)key); 324 | //printf("String is %s, len %d\n", key, (int)strlen((char *)key)); 325 | //unsigned char temp_str[256]; 326 | //sprintf((char *)temp_str, "%s", (char *)key);*/ 327 | string str_str((const char *)temp_key, strlen((char *)temp_key)); 328 | //cout << str_str; 329 | metadata.keywords->push_back(str_str); 330 | //metadata.keywords[str_str] = 1; 331 | 332 | temp_key = (unsigned char *)strtok_r(NULL, "=", (char **)&saveptr2); 333 | if(temp_key == NULL) 334 | { 335 | contFlag = 1; 336 | break; 337 | } 338 | 339 | //if(key[0] == '"') 340 | if(temp_key[0] == '"') 341 | { 342 | unsigned char *temp = (unsigned char *)malloc(sizeof(unsigned char)*(strlen((char *)temp_key)-2)); 343 | strncpy((char *)temp, (char *)temp_key+1, strlen((char *)temp_key)-2); 344 | temp[strlen((char *)temp_key)-2]='\0'; 345 | unsigned char *temp_key_1 = (unsigned char *)strtok_r((char *)temp, "^", (char **)&saveptr3); 346 | //printf("Key is : %s\n", temp); 347 | metadata.keywords->push_back(string((char *)temp_key_1)); 348 | //metadata.keywords[string((char *)key)] = 1; 349 | //unsigned char *temp_temp_key; 350 | while((temp_key_1 = (unsigned char *)strtok_r(NULL, "^", (char **)&saveptr3))!=NULL) //keywords 351 | { 352 | metadata.keywords->push_back(string((char *)temp_key_1)); 353 | //metadata.keywords[string((char *)key)] = 1; 354 | } 355 | free(temp); 356 | } 357 | else 358 | { 359 | metadata.keywords->push_back(string((char *)temp_key)); 360 | //metadata.keywords[string((char *)key)] = 1; 361 | } 362 | /*free(temp_value); 363 | temp_temp_value = (unsigned char *)strtok(NULL, "?"); 364 | if(temp_temp_value == NULL) 365 | break;*/ 366 | value = NULL; 367 | } 368 | 369 | if(contFlag) 370 | continue; 371 | 372 | //populate BitVector 373 | memset(metadata.bitVector, 0, sizeof(metadata.bitVector)); 374 | 375 | for (list::iterator it = metadata.keywords->begin(); it != metadata.keywords->end(); ++it){ 376 | //for (map::iterator it = metadata.keywords.begin(); it != metadata.keywords.end(); ++it){ 377 | createBitVector(metadata.bitVector, (unsigned char *)(*it).c_str()); 378 | /*printf("%s:\n", (*it).c_str()); 379 | for(int i=0;i<128;i++) 380 | printf("%02x", metadata.bitVector[i]); 381 | printf("\n\n");*/ 382 | } 383 | /* printf("\n"); 384 | for(int i=0;i<128;i++) 385 | printf("%02x", metadata.bitVector[i]); 386 | printf("\n");*/ 387 | //Update the global file Number 388 | int globalFileNumber = updateGlobalFileNumber(); 389 | 390 | //determine nonce 391 | unsigned char password[SHA_DIGEST_LENGTH] ; 392 | GetUOID( const_cast ("password"), password, sizeof(password)) ; 393 | unsigned char passwordFileName[256]; 394 | sprintf((char *)passwordFileName, "%s/%d.pass", filesDir, globalFileNumber); 395 | 396 | 397 | FILE *f1 = fopen((char *)passwordFileName, "w"); 398 | fprintf(f1,"%s",password); 399 | fclose(f1); 400 | 401 | strncpy((char *)metadata.nonce, (char *)toSHA1(password), 20); 402 | 403 | writeMetaData(metadata, globalFileNumber); 404 | writeData(metadata, globalFileNumber); 405 | populateBitVectorIndexMap(metadata.bitVector, globalFileNumber); 406 | populateSha1IndexMap(metadata.sha1, globalFileNumber); 407 | populateFileNameIndexMap(metadata.fileName, globalFileNumber); 408 | if(myInfo->status_ttl > 0) 409 | initiateStore( MetaDataToStr(metadata), string((char *)metadata.fileName) ) ; 410 | } 411 | else if(strncasecmp((char *)inp, "search ", 6) == 0) 412 | { 413 | unsigned char *value; 414 | unsigned char *key = (unsigned char *)strtok((char *)inp, " "); 415 | key = (unsigned char *)strtok(NULL, "\n"); 416 | if(key==NULL) 417 | continue; 418 | /*value = (unsigned char *)malloc(sizeof(unsigned char)*strlen((char *)key)); 419 | memset(value, '\0',sizeof(value));*/ 420 | value = (unsigned char *)strtok((char *)key, "="); 421 | 422 | if(strcasecmp((char *)value, "filename")==0) 423 | { 424 | value = (unsigned char *)strtok(NULL, "="); 425 | if(value==NULL) 426 | continue; 427 | // list tempList = fileNameSearch(value); 428 | // for(list::iterator it = tempList.begin();it!=tempList.end();it++) 429 | // { 430 | // printf("File name is: %d\n", (*it)); 431 | // //now updating the FILEID MAP 432 | // struct metaData metadata = populateMetaData((*it)); 433 | // fileIDMap[string((char *)metadata.fileID, 20)] = (*it); 434 | // } 435 | // Initiate the search method with the type filename 436 | initiateSearch(0x01, value) ; 437 | checkFlag = 1; 438 | } 439 | else if(strcasecmp((char *)value, "sha1hash")==0) 440 | { 441 | value = (unsigned char *)strtok(NULL, "\n"); 442 | if(value == NULL) 443 | continue; 444 | unsigned char *str = toHex(value, 20); 445 | initiateSearch(0x02, str) ; 446 | checkFlag = 1; 447 | } 448 | else if(strcasecmp((char *)value, "keywords")==0) 449 | { 450 | 451 | value = (unsigned char *)strtok(NULL, "\n"); 452 | if(value==NULL) 453 | continue; 454 | if(value[0] == '"') 455 | { 456 | 457 | unsigned char *temp = (unsigned char *)malloc(sizeof(unsigned char)*(strlen((char *)value)-2)); 458 | strncpy((char *)temp, (char *)value+1, strlen((char *)value)-2); 459 | temp[strlen((char *)value)-2]='\0'; 460 | initiateSearch(0x03, temp) ; 461 | 462 | free(temp); 463 | checkFlag = 1; 464 | } 465 | else 466 | { 467 | initiateSearch(0x03, value) ; 468 | checkFlag = 1; 469 | } 470 | } 471 | pthread_mutex_lock(&searchMsgLock) ; 472 | pthread_cond_wait(&searchMsgCV, &searchMsgLock); 473 | pthread_mutex_unlock(&searchMsgLock) ; 474 | //sleep(5); 475 | } 476 | /*else if(strstr((char *) inp, "find ")!=NULL) 477 | { 478 | unsigned char *value = (unsigned char *)strtok(inp, " "); 479 | value = (unsigned char *)strtok(NULL, "\n"); 480 | unsigned char *temp_value = toHex(value, 20); 481 | printf("The value is : %d\n", fileIDMap[string((char*)temp_value, 20)]); 482 | }*/ 483 | else if(strstr((char *) inp, "delete ")!=NULL) 484 | { 485 | checkFlag = 0; 486 | 487 | unsigned char *value; 488 | unsigned char temp_str[256]; 489 | unsigned char message[256]; 490 | unsigned char *saveptr1, *saveptr2; 491 | int toFloodFlag = 0 ; 492 | list tempList; 493 | memset(temp_str, '\0', sizeof(temp_str)); 494 | memset(message, '\0', sizeof(message)); 495 | value = (unsigned char *)strtok_r(inp, " ", (char **)&saveptr1); 496 | bool contFlag = 0; 497 | while((value = (unsigned char *)strtok_r(NULL, " ", (char **)&saveptr1))!=NULL) 498 | { 499 | if(strstr((char *)value, "FileName=")!=NULL) 500 | { 501 | sprintf((char *)temp_str, "%s\r\n", value); 502 | strcat((char *)message, (char *)temp_str); 503 | unsigned char *key = (unsigned char *)strtok_r((char *)value, "=", (char **)&saveptr2); 504 | if(key == NULL) 505 | { 506 | contFlag = 1; 507 | break; 508 | } 509 | key = (unsigned char *)strtok_r(NULL, "=", (char **)&saveptr2); 510 | if(key == NULL) 511 | { 512 | contFlag = 1; 513 | break; 514 | } 515 | 516 | tempList = fileNameSearch(key); 517 | } 518 | else if (strstr((char *)value, "Nonce=")!=NULL) 519 | { 520 | value = (unsigned char *)strtok((char*)value, "\n"); 521 | 522 | sprintf((char *)temp_str, "%s\r\n", value); 523 | strcat((char *)message, (char *)temp_str); 524 | unsigned char *key = (unsigned char *)strtok_r((char *)value, "=", (char **)&saveptr2); 525 | if(key == NULL) 526 | { 527 | contFlag = 1; 528 | break; 529 | } 530 | key = (unsigned char *)strtok_r(NULL, "=", (char **)&saveptr2); 531 | if(key == NULL) 532 | { 533 | contFlag = 1; 534 | break; 535 | } 536 | key = toHex(key, 20); 537 | unsigned char passFile[256]; 538 | unsigned char tempPassword[20]; 539 | memset(tempPassword,'\0', sizeof(tempPassword)); 540 | FILE *f; 541 | for(list ::iterator it = tempList.begin();it!=tempList.end();it++) 542 | { 543 | struct metaData metadata = populateMetaData((*it)); 544 | //printf("Hi %s & nonce: %s\n", key, metadata.nonce); 545 | 546 | /*for(int i=0;i<20;i++) 547 | { 548 | printf("%02x",metadata.nonce[i]); 549 | } 550 | 551 | for(int i=0;i<20;i++) 552 | { 553 | printf("%02x",key[i]); 554 | }*/ 555 | 556 | if(strncmp((char *)key,(char *)metadata.nonce, 20)==0) 557 | { 558 | memset(passFile,'\0', sizeof(passFile)); 559 | memset(tempPassword,'\0', sizeof(tempPassword)); 560 | sprintf((char *)passFile, "%s/%d.pass", filesDir, (*it)); 561 | f = fopen((char *)passFile, "r"); 562 | if(f!=NULL) 563 | { 564 | fread(tempPassword, 20, 1, f); 565 | //fscanf(f, "%s", tempPassword); 566 | unsigned char temp_str1[40]; 567 | memset(temp_str1, 0, 40); 568 | for(int i=0;i<20;i++) 569 | sprintf((char *)&temp_str1[i*2], "%02x", tempPassword[i]); 570 | sprintf((char *)temp_str, "Password=%s\r\n", temp_str1); 571 | toFloodFlag = 1 ; 572 | strcat((char *)message, (char *)temp_str); 573 | fclose(f); 574 | //printf("hi\n\n%s", message); 575 | } 576 | else 577 | { 578 | //generate random password 579 | unsigned char val[10]; 580 | memset(val, '\0', 10); 581 | printf("\nNo one-time password found.\nOkay to use a random password [yes/no]? "); 582 | scanf("%s", val); 583 | val[9]='\0'; 584 | if(val[0]=='y' || val[0]=='Y') 585 | { 586 | memset(tempPassword,'\0', sizeof(tempPassword)); 587 | unsigned char temp_str1[40]; 588 | memset(temp_str1, '\0', 40); 589 | GetUOID( const_cast ("password"), tempPassword, sizeof(tempPassword)) ; 590 | for(int i=0;i<20;i++) 591 | sprintf((char *)&temp_str1[i*2], "%02x", tempPassword[i]); 592 | sprintf((char *)temp_str, "Password=%s\r\n", temp_str1); 593 | toFloodFlag = 1 ; 594 | strcat((char *)message, (char *)temp_str); 595 | } 596 | else 597 | { 598 | contFlag = 1; 599 | break; 600 | } 601 | } 602 | } 603 | } 604 | 605 | if(contFlag) 606 | break; 607 | if(strcmp((char *)tempPassword, "\0") == 0) 608 | { 609 | /*unsigned char val[10]; 610 | memset(val, '\0', 10); 611 | printf("\nNo one-time password found.\nOkay to use a random password [yes/no]? "); 612 | scanf("%s", val); 613 | val[9]='\0'; 614 | if(val[0]=='y' || val[0]=='Y') 615 | { 616 | memset(tempPassword,'\0', sizeof(tempPassword)); 617 | unsigned char temp_str1[40]; 618 | memset(temp_str1, '\0', 40); 619 | GetUOID( const_cast ("password"), tempPassword, sizeof(tempPassword)) ; 620 | for(int i=0;i<20;i++) 621 | sprintf((char *)&temp_str1[i*2], "%02x", tempPassword[i]); 622 | sprintf((char *)temp_str, "Password=%s\r\n", temp_str1); 623 | toFloodFlag = 1 ; 624 | strcat((char *)message, (char *)temp_str); 625 | } 626 | else 627 | continue;*/ 628 | // printf("No such file present in the file system\n"); 629 | contFlag = 1; 630 | break; 631 | } 632 | 633 | } 634 | else if (strstr((char *)value, "SHA1=")!=NULL) 635 | { 636 | sprintf((char *)temp_str, "%s\r\n", value); 637 | strcat((char *)message, (char *)temp_str); 638 | } 639 | saveptr2 = NULL; 640 | } 641 | 642 | if(contFlag) 643 | continue; 644 | 645 | // printf("\nMessage to be passed is: \n%s", message); 646 | string tempMes((char *)message) ; 647 | if (toFloodFlag) 648 | initiateDelete((unsigned char *)tempMes.c_str()) ; 649 | struct parsedDeleteMessage pd = parseDeleteMessage(message); 650 | deleteFile(pd); 651 | } 652 | else if(strstr((char *)inp, "get ")!=NULL) 653 | { 654 | if(checkFlag==0) 655 | continue; 656 | unsigned char *value = (unsigned char *)strtok((char *)inp, " "); 657 | value = (unsigned char *)strtok(NULL, " "); 658 | if(value == NULL) 659 | continue; 660 | int indexNumber = atoi((char *)value); 661 | if(getFileIDMap.find(indexNumber)==getFileIDMap.end()) 662 | { 663 | // printf("No such entry\n"); 664 | continue; 665 | } 666 | struct metaData metadata = getFileIDMap[indexNumber]; 667 | 668 | value = (unsigned char *)strtok(NULL, "\n"); 669 | memset(extFile, '\0', 256); 670 | if(value == NULL) 671 | strncpy((char *)extFile, (char *)metadata.fileName, strlen((char *)metadata.fileName)); 672 | //sprintf((char *)extFile, "%s/%s", myInfo->homeDir, metadata.fileName); 673 | else 674 | strncpy((char *)extFile, (char *)value, strlen((char *)value)); 675 | //sprintf((char *)extFile, "%s/%s", myInfo->homeDir, value); 676 | 677 | map::iterator result = fileIDMap.find(string((char *)metadata.fileID, 20)); 678 | if(result != fileIDMap.end()) 679 | { 680 | //updateLRU((*result).second); 681 | list::iterator result1 = find(cacheLRU.begin(), cacheLRU.end(), (int)(*result).second); 682 | if(result1!=cacheLRU.end()) 683 | { 684 | cacheLRU.erase(result1); 685 | } 686 | if(fopen((char *)extFile, "rb") == NULL) 687 | writeToFileFromData(extFile, (*result).second); 688 | continue; 689 | } 690 | 691 | // printf("You have found the entry and now flood to get it!!!\n"); 692 | checkFlag = 1; 693 | initiateGet(metadata) ; 694 | 695 | pthread_mutex_lock(&getMsgLock) ; 696 | pthread_cond_wait(&getMsgCV, &getMsgLock); 697 | pthread_mutex_unlock(&getMsgLock) ; 698 | } 699 | 700 | memset(inp, '\0', 1024) ; 701 | //cin.clear() ; 702 | // fflush(stdin); 703 | } 704 | 705 | //printf("KeyBoardThread Halted\n"); 706 | free(inp); 707 | pthread_exit(0); 708 | return 0; 709 | } 710 | 711 | -------------------------------------------------------------------------------- /logEntry.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "iniParser.h" 5 | #include "main.h" 6 | 7 | unsigned char data[256]; 8 | unsigned char finalData[512]; 9 | unsigned char msg_type[5]; 10 | struct node n; 11 | uint32_t data_len=0; 12 | 13 | //gets the neighbors hostname and port no for logging purposes 14 | void getNeighbor(int sockfd) 15 | { 16 | pthread_mutex_lock(&connectionMapLock); 17 | n = connectionMap[sockfd].n; 18 | pthread_mutex_unlock(&connectionMapLock); 19 | } 20 | 21 | //determinse the type of message on the basis of the messg_type code 22 | void messageType(uint8_t message_type) 23 | { 24 | //char *msg_type = (char *)malloc(sizeof(char)*4); 25 | //char msg_type[4]; 26 | memset(&msg_type, '\0', 4); 27 | const char *temp_msg_type; 28 | 29 | switch(message_type) 30 | { 31 | 32 | case 0xfc : //strncpy((char *)msg_type, "JNRQ", 4); 33 | temp_msg_type = "JNRQ"; 34 | break; 35 | case 0xfb : //strncpy((char *)msg_type, "JNRS", 4); 36 | temp_msg_type ="JNRS"; 37 | break; 38 | case 0xfa : //strncpy((char *)msg_type, "HLLO", 4); 39 | temp_msg_type ="HLLO"; 40 | break; 41 | case 0xf8 : //strncpy((char *)msg_type, "KPAV", 4); 42 | temp_msg_type ="KPAV"; 43 | break; 44 | case 0xf7 : //strncpy((char *)msg_type, "NTFY", 4); 45 | temp_msg_type ="NTFY"; 46 | break; 47 | case 0xf6 : //strncpy((char *)msg_type, "CKRQ", 4); 48 | temp_msg_type ="CKRQ"; 49 | break; 50 | case 0xf5 : //strncpy((char *)msg_type, "CKRS", 4); 51 | temp_msg_type ="CKRS"; 52 | break; 53 | case 0xac : //strncpy((char *)msg_type, "STRQ", 4); 54 | temp_msg_type ="STRQ"; 55 | break; 56 | case 0xab : //strncpy((char *)msg_type, "STRS", 4); 57 | temp_msg_type ="STRS"; 58 | break; 59 | case 0xec : //strncpy((char *)msg_type, "STRS", 4); 60 | temp_msg_type ="SHRQ"; 61 | break; 62 | case 0xeb : //strncpy((char *)msg_type, "STRS", 4); 63 | temp_msg_type ="SHRS"; 64 | break; 65 | case 0xdc : 66 | temp_msg_type = "GTRQ"; 67 | break; 68 | case 0xdb : 69 | temp_msg_type = "GTRS"; 70 | break; 71 | case 0xcc : 72 | temp_msg_type = "STOR"; 73 | break; 74 | case 0xbc : 75 | temp_msg_type = "DELT"; 76 | break; 77 | default : break; 78 | } 79 | for(unsigned int i=0;i<4;i++) 80 | msg_type[i]=temp_msg_type[i]; 81 | msg_type[4] = '\0'; 82 | } 83 | 84 | //setting the data filed for logging, extarcting the values from the buffer 85 | void dataFromBuffer(uint8_t message_type, unsigned char *buffer) 86 | { 87 | //unsigned char portNo[2]; 88 | unsigned short int portNo; 89 | memset(&portNo, '\0', sizeof(portNo)); 90 | unsigned char uoid[4]; 91 | memset(&uoid, '\0', sizeof(uoid)); 92 | uint32_t distance; 93 | memset(&distance, '\0', sizeof(distance)); 94 | unsigned char hostName[256]; 95 | memset(&hostName, '\0', sizeof(hostName)); 96 | uint8_t errorCode = 0; 97 | uint8_t statusType = 0x00; 98 | 99 | switch(message_type) 100 | { 101 | case 0xfc : //Join Request 102 | memcpy(&portNo, buffer+4, 2) ; 103 | for(unsigned int i=0;i < data_len-6;i++) 104 | hostName[i] = buffer[i+6]; 105 | //strncpy((char *)hostName, (char *)buffer+2, strlen((char *)buffer)-2) ; 106 | sprintf((char *)data, "%d %s", portNo, (char *)hostName); 107 | break; 108 | 109 | case 0xfb : //Join Response 110 | //memcpy(uoid, &buffer[17], 4); 111 | for(unsigned int i=0;i < 4;i++) 112 | uoid[i] = buffer[16+i]; 113 | memcpy(&distance, &buffer[20], 4) ; 114 | memcpy(&portNo, &buffer[24], 2) ; 115 | for(unsigned int i=26;i < data_len;i++) 116 | hostName[i-26] = buffer[i]; 117 | //strncpy((char *)hostName, ((char *)buffer+26), strlen((char *)buffer)-26) ; 118 | sprintf((char *)data, "%02x%02x%02x%02x %d %d %s", uoid[0], uoid[1], uoid[2], uoid[3], distance, portNo, hostName); 119 | break; 120 | 121 | case 0xfa : //Hello Message 122 | memcpy(&portNo, buffer, 2) ; 123 | //strncpy((char *)hostName, (char *)buffer+2, strlen((char *)buffer)-2) ; 124 | for(unsigned int i=0;i < data_len-2;i++) 125 | hostName[i] = buffer[i+2]; 126 | sprintf((char *)data, "%d %s", portNo, (char *)hostName); 127 | break; 128 | 129 | case 0xf8 : //msg_type = "KPAV" 130 | break; 131 | case 0xf7 : //msg_type = "NTFY" 132 | memcpy(&errorCode, buffer, 1); 133 | sprintf((char *)data, "%d", errorCode); 134 | break; 135 | case 0xf6 : //msg_type = "CKRQ" 136 | 137 | break; 138 | case 0xf5 : //msg_type = "CKRS" 139 | for(unsigned int i=0;i < 4;i++) 140 | uoid[i] = buffer[16+i]; 141 | sprintf((char *)data, "%02x%02x%02x%02x", uoid[0], uoid[1], uoid[2], uoid[3]); 142 | break; 143 | case 0xac : //msg_type = "STRQ" 144 | memcpy(&statusType, buffer, 1) ; 145 | if(statusType == 0x01) 146 | sprintf((char *)data, "%s", "neighbors"); 147 | else 148 | sprintf((char *)data, "%s", "files"); 149 | break; 150 | case 0xab : //msg_type = "STRS" 151 | for(unsigned int i=0;i < 4;i++) 152 | uoid[i] = buffer[16+i]; 153 | sprintf((char *)data, "%02x%02x%02x%02x", uoid[0], uoid[1], uoid[2], uoid[3]); 154 | break; 155 | case 0xec : //strncpy((char *)msg_type, "STRS", 4); 156 | { //temp_msg_type ="SHRQ"; 157 | memcpy(&statusType, buffer, 1) ; 158 | if(statusType == 0x01) 159 | { 160 | unsigned char *temp = (unsigned char *)malloc(sizeof(unsigned char )*(data_len-1)); 161 | for(unsigned int i=0;i 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "main.h" 11 | #include "iniParser.h" 12 | #include "signalHandler.h" 13 | #include "keepAliveTimer.h" 14 | #include "indexSearch.h" 15 | 16 | bool resetFlag = 0; 17 | bool shutDown = 0 ; 18 | int accept_pid; 19 | int keepAlive_pid; 20 | int toBeClosed; 21 | int joinTimeOutFlag = 0; 22 | int inJoinNetwork = 0; 23 | int node_pid; 24 | int nSocket_accept = 0; 25 | int statusTimerFlag = 0 ; 26 | int searchTimerFlag = 0 ; 27 | int checkTimerFlag = 0 ; 28 | //int globalFileNumber = 0; 29 | unsigned char *fileName = NULL; 30 | unsigned char tempLogFile[512], tempInitFile[512]; 31 | unsigned char extFile[256]; 32 | unsigned char filesDir[256]; 33 | int softRestartFlag = 0 ; 34 | int globalSearchCount = 0 ; 35 | int currentCacheSize = 0; 36 | 37 | pthread_t k_thread; 38 | FILE *f_log = NULL; 39 | struct myStartInfo *myInfo ; 40 | map connectionMap; 41 | map nodeConnectionMap; 42 | list childThreadList ; 43 | //list myConnectThread ; 44 | map myConnectThread; 45 | set joinResponse ; 46 | set< set > statusResponse ; 47 | map< struct node, list > statusResponseTypeFiles ; 48 | map > bitVectorIndexMap; 49 | map > fileNameIndexMap; 50 | map > sha1IndexMap; 51 | map fileIDMap; 52 | list cacheLRU; 53 | map getFileIDMap; 54 | list tmpFileNameList; 55 | //list metadataList; 56 | 57 | pthread_mutex_t connectionMapLock ; 58 | pthread_mutex_t nodeConnectionMapLock ; 59 | pthread_mutex_t MessageDBLock ; 60 | pthread_mutex_t statusMsgLock ; 61 | pthread_mutex_t searchMsgLock ; 62 | pthread_mutex_t getMsgLock ; 63 | pthread_mutex_t logEntryLock ; 64 | pthread_cond_t statusMsgCV; 65 | pthread_cond_t searchMsgCV; 66 | pthread_cond_t getMsgCV; 67 | 68 | void my_handler(int nSig); 69 | void resetValues(); 70 | unsigned char *createBitVector(unsigned char *keyword); 71 | list keywordSearch(unsigned char *completeStr); 72 | list fileNameSearch(unsigned char *fileName); 73 | list sha1Search(unsigned char *sha1String); 74 | 75 | int usage() 76 | { 77 | printf("Incorrect command line argument--\n\nUsage is: \"sv_node [-reset] <.ini file>\"\n"); 78 | return false; 79 | } 80 | 81 | // this function process the command line arguments, checks for reset options and colelcts the startup configuration file 82 | int processCommandLine(int argc, unsigned char *argv[]) 83 | { 84 | int iniFlag=0; 85 | 86 | //not enough number of arguments 87 | if(argc<2 || argc > 3) 88 | return usage(); 89 | 90 | for(int i=1;iisBeacon && !shutDown && !inJoinNetwork && !myInfo->noCheck){ 141 | //printf("Inititating CHECK message\n") ; 142 | initiateCheck() ; 143 | } 144 | 145 | } 146 | 147 | // while closing a connection, this function is called to erase the value of neighbor from the list maintained 148 | void eraseValueInMap(int val) 149 | { 150 | for (map::iterator it = nodeConnectionMap.begin(); it != nodeConnectionMap.end(); ++it){ 151 | if((*it).second == val) 152 | { 153 | nodeConnectionMap.erase((*it).first); 154 | break; 155 | } 156 | } 157 | } 158 | 159 | 160 | // Main body of the PEER TO PEER file sharing system 161 | int main(int argc, char *argv[]) 162 | { 163 | 164 | map > bitVectorIndexMap; 165 | map > fileNameIndexMap; 166 | map > sha1IndexMap; 167 | 168 | //Checks if the command arguments are correct or not 169 | if(!processCommandLine(argc, (unsigned char**)argv)) 170 | exit(0); 171 | 172 | 173 | sigset_t new_t ; 174 | sigemptyset(&new_t); 175 | sigaddset(&new_t, SIGINT); 176 | pthread_sigmask(SIG_BLOCK, &new_t, NULL); 177 | 178 | //function populates the node elemenets with default values 179 | populatemyInfo(); 180 | 181 | //parses the INI file, populates the 182 | parseINIfile(fileName); 183 | free(fileName) ; 184 | 185 | myInfo->joinTimeOut_permanent = myInfo->joinTimeOut; 186 | myInfo->autoShutDown_permanent = myInfo->autoShutDown; 187 | myInfo->cacheSize*=1024; 188 | time_t localtime=(time_t)0; 189 | 190 | time(&localtime); 191 | srand48((long)localtime); 192 | /******************************************************/ 193 | /*struct metaData metadata = populateMetaData(33); 194 | metadataList.push_back(metadata); 195 | memset(&metadata, 0, sizeof(metadata)); 196 | metadata = populateMetaData(34); 197 | metadataList.push_back(metadata); 198 | searchResponseDisplay(); 199 | 200 | unsigned char temp_str[20]; 201 | for(map::iterator it = getFileIDMap.begin(); it!=getFileIDMap.end();it++) 202 | { 203 | printf("%d ", (*it).first); 204 | printf("%s ", (((*it).second).c_str())); 205 | for(int i=0;i<20;i++) 206 | { 207 | temp_str[i] = ((*it).second).c_str()[i]; 208 | printf("%02x", temp_str[i]); 209 | } 210 | printf("\n\n"); 211 | } 212 | exit(0);*/ 213 | /*populateBitVectorIndexMap(metadata.bitVector, 33); 214 | populateSha1IndexMap(metadata.sha1, 33); 215 | populateFileNameIndexMap(metadata.fileName, 33);*/ 216 | 217 | /* writeIndexToFile(); 218 | */ 219 | //readIndexFromFile(); 220 | //writeIndexToFile(); 221 | /******************************************************/ 222 | 223 | //creates the directory, homedirectory 224 | 225 | // memset(filesDir, 0, 256); 226 | sprintf((char *)filesDir, "%s/files", myInfo->homeDir); 227 | 228 | 229 | struct stat st; 230 | if(stat((char *)myInfo->homeDir,&st) != 0) 231 | mkdir((char *)myInfo->homeDir, 0777); 232 | 233 | memset(&st, 0, sizeof(st)); 234 | 235 | if(stat((char *)filesDir,&st) != 0) 236 | mkdir((char *)filesDir, 0777); 237 | 238 | unsigned char fileNumber_file[256]; 239 | sprintf((char *)fileNumber_file, "%s/.fileNumber", myInfo->homeDir); 240 | FILE *f_fileNumber = fopen((char *)fileNumber_file, "r"); 241 | if(f_fileNumber == NULL) 242 | { 243 | f_fileNumber = fopen((char *)fileNumber_file, "w"); 244 | fprintf(f_fileNumber, "%d", 0); 245 | } 246 | fclose(f_fileNumber); 247 | 248 | //Log file and init_neighbors_file 249 | memset(&tempLogFile, '\0', 512); 250 | memset(&tempInitFile, '\0', 512); 251 | strncpy((char *)tempLogFile, (char *)myInfo->homeDir, strlen((char*)myInfo->homeDir)); 252 | strncpy((char *)tempInitFile, (char *)myInfo->homeDir, strlen((char*)myInfo->homeDir)); 253 | tempLogFile[strlen((char*)myInfo->homeDir)] = '\0'; 254 | tempInitFile[strlen((char*)myInfo->homeDir)] = '\0'; 255 | strcat((char *)tempLogFile, "/"); 256 | strcat((char *)tempLogFile, (char *)myInfo->logFileName); 257 | strcat((char *)tempInitFile, "/init_neighbor_list"); 258 | 259 | readIndexFromFile(); 260 | readLRUFromFile(); 261 | 262 | //if reset option at the commnad prompt given, delets the log file, init neighbor file 263 | if(resetFlag) 264 | { 265 | //writeLogEntry((unsigned char *)"//Reset Option in command line is given, deleted Log file\n"); 266 | remove((char *)tempLogFile); 267 | // if(!myInfo->isBeacon) 268 | // remove((char *)tempInitFile); 269 | deleteAllFiles(); 270 | } 271 | //Opening the log file 272 | f_log = fopen((char *)tempLogFile, "a"); 273 | 274 | //f_log = fopen((char *)myInfo->logFileName, "a"); 275 | //printf("%s", myInfo->logFileName); 276 | if(strcmp((char *)myInfo->homeDir, "\0")==0 || myInfo->portNo == 0 || myInfo->location == 0) 277 | { 278 | //Program should exit 279 | writeLogEntry((unsigned char *)"//Madatory elements of Nodes were not populated\n"); 280 | exit(0); 281 | } 282 | 283 | // printf("Created a directory %s\n", (char *)myInfo->homeDir); 284 | // exit(0); 285 | //Checks if the node is beacon or not 286 | struct node n; 287 | //strcpy((char *)n.hostname, (char *)myInfo->hostName); 288 | for(int i=0;i<(int)strlen((char *)myInfo->hostName);i++) 289 | n.hostname[i] = myInfo->hostName[i]; 290 | n.hostname[strlen((char *)myInfo->hostName)] = '\0'; 291 | n.portNo=myInfo->portNo; 292 | myInfo->isBeacon = isBeaconNode(n); 293 | 294 | memset(&accept_pid, 0, sizeof(accept_pid)); 295 | node_pid = getpid(); 296 | signal(SIGTERM, my_handler); 297 | 298 | 299 | // Assign a node ID and node instance id to this node 300 | { 301 | unsigned char host1[256] ; 302 | memset(host1, '\0', 256) ; 303 | gethostname((char *)host1, 256) ; 304 | host1[255] = '\0' ; 305 | sprintf((char *)myInfo->node_id, "%s_%d", host1, myInfo->portNo) ; 306 | // printf("My node ID: %s\n", myInfo->node_id) ; 307 | setNodeInstanceId() ; 308 | } 309 | 310 | // Initialize Locks and considiton vairables 311 | int lres = pthread_mutex_init(&logEntryLock, NULL) ; 312 | if (lres != 0){ 313 | //perror("Mutex initialization failed") ; 314 | writeLogEntry((unsigned char *)"//Mutex initialization failed\n"); 315 | } 316 | lres = pthread_mutex_init(&connectionMapLock, NULL) ; 317 | if (lres != 0){ 318 | //perror("Mutex initialization failed") ; 319 | writeLogEntry((unsigned char *)"//Mutex initialization failed\n"); 320 | } 321 | 322 | lres = pthread_mutex_init(&MessageDBLock, NULL) ; 323 | if (lres != 0){ 324 | //perror("Mutex initialization failed") ; 325 | writeLogEntry((unsigned char *)"//Mutex initialization failed\n"); 326 | } 327 | 328 | lres = pthread_mutex_init(&nodeConnectionMapLock, NULL) ; 329 | if (lres != 0){ 330 | //perror("Mutex initialization failed") ; 331 | writeLogEntry((unsigned char *)"//Mutex initialization failed\n"); 332 | } 333 | 334 | lres = pthread_mutex_init(&statusMsgLock, NULL) ; 335 | if (lres != 0){ 336 | //perror("Mutex initialization failed") ; 337 | writeLogEntry((unsigned char *)"//Mutex initialization failed\n"); 338 | } 339 | 340 | int cres = pthread_cond_init(&statusMsgCV, NULL) ; 341 | if (cres != 0){ 342 | //perror("CV initialization failed") ; 343 | writeLogEntry((unsigned char *)"//CV initialization failed\n"); 344 | } 345 | lres = pthread_mutex_init(&searchMsgLock, NULL) ; 346 | if (lres != 0){ 347 | //perror("Mutex initialization failed") ; 348 | writeLogEntry((unsigned char *)"//Mutex initialization failed\n"); 349 | } 350 | 351 | cres = pthread_cond_init(&searchMsgCV, NULL) ; 352 | if (cres != 0){ 353 | //perror("CV initialization failed") ; 354 | writeLogEntry((unsigned char *)"//CV initialization failed\n"); 355 | } 356 | 357 | lres = pthread_mutex_init(&getMsgLock, NULL) ; 358 | if (lres != 0){ 359 | //perror("Mutex initialization failed") ; 360 | writeLogEntry((unsigned char *)"//Mutex initialization failed\n"); 361 | } 362 | 363 | cres = pthread_cond_init(&getMsgCV, NULL) ; 364 | if (cres != 0){ 365 | //perror("CV initialization failed") ; 366 | writeLogEntry((unsigned char *)"//CV initialization failed\n"); 367 | } 368 | 369 | 370 | 371 | 372 | // Call the init function 373 | while(!shutDown || softRestartFlag){ 374 | 375 | 376 | softRestartFlag = 0 ; 377 | signal(SIGTERM, my_handler); 378 | 379 | //Start of the logging 380 | struct timeval tv; 381 | memset(&tv, 0, sizeof(tv)); 382 | gettimeofday(&tv, NULL); 383 | unsigned char startLogging[256]; 384 | memset(startLogging, '\0', 256); 385 | sprintf((char *)startLogging, "// %10ld.%03ld : Logging Started\n", tv.tv_sec, (tv.tv_usec/1000)); 386 | writeLogEntry(startLogging); 387 | 388 | //Initialiing the threads, establishing connections 389 | init() ; 390 | 391 | //Cleaning up, shutting down 392 | cleanup() ; 393 | //printf("The SIze of master list is : %d\n", (int)childThreadList.size()); 394 | //printf("going back again\n") ; 395 | 396 | //checks if the soft restart needs to be performed, and then reset the values 397 | if(softRestartFlag) 398 | resetValues(); 399 | 400 | //Stop logging here 401 | memset(&tv, 0, sizeof(tv)); 402 | gettimeofday(&tv, NULL); 403 | unsigned char stopLogging[256]; 404 | memset(stopLogging, '\0', 256); 405 | sprintf((char *)stopLogging, "// %10ld.%03ld : Logging Stopped\n", tv.tv_sec, (tv.tv_usec/1000)); 406 | writeLogEntry(stopLogging); 407 | 408 | 409 | } 410 | 411 | 412 | writeIndexToFile(); 413 | writeLRUToFile(); 414 | 415 | //printf("Complete Shutdown!!!!\n"); 416 | fclose(f_log); 417 | return 0; 418 | } 419 | 420 | 421 | void resetValues() 422 | { 423 | shutDown = 0; 424 | myInfo->joinTimeOut = myInfo->joinTimeOut_permanent; 425 | myInfo->autoShutDown = myInfo->autoShutDown_permanent; 426 | myInfo->checkResponseTimeout = myInfo->joinTimeOut_permanent; 427 | checkTimerFlag = 0; 428 | nSocket_accept = 0; 429 | //remove((char *)tempInitFile); 430 | } 431 | 432 | void cleanup(){ 433 | 434 | int res ; 435 | void *thread_result ; 436 | 437 | 438 | 439 | //KeepAlive Timer Thread, Sends KeepAlive Messages 440 | pthread_t keepAlive_thread ; 441 | res = pthread_create(&keepAlive_thread, NULL, keepAliveTimer_thread , (void *)NULL); 442 | if (res != 0) { 443 | //perror("Thread creation failed"); 444 | writeLogEntry((unsigned char *)"//In Main: Thread creation failed\n"); 445 | exit(EXIT_FAILURE); 446 | } 447 | childThreadList.push_front(keepAlive_thread); 448 | // Call the Keyboard thread 449 | // Thread creation and join code taken from WROX Publications book 450 | 451 | keepAlive_pid = getpid(); 452 | //pthread_t k_thread ; 453 | res = pthread_create(&k_thread, NULL, keyboard_thread , (void *)NULL); 454 | if (res != 0) { 455 | //perror("Thread creation failed"); 456 | writeLogEntry((unsigned char *)"//In Main: Thread creation failed\n"); 457 | exit(EXIT_FAILURE); 458 | } 459 | childThreadList.push_front(k_thread); 460 | // Call the timer thread 461 | // Thread creation and join code taken from WROX Publications book 462 | pthread_t t_thread ; 463 | res = pthread_create(&t_thread, NULL, timer_thread , (void *)NULL); 464 | if (res != 0) { 465 | //perror("Thread creation failed"); 466 | writeLogEntry((unsigned char *)"//In Main: Thread creation failed\n"); 467 | exit(EXIT_FAILURE); 468 | } 469 | childThreadList.push_front(t_thread); 470 | 471 | 472 | for (list::iterator it = childThreadList.begin(); it != childThreadList.end(); ++it){ 473 | //printf("Value is : %d and SIze: %d\n", (int)(*it), (int)childThreadList.size()); 474 | res = pthread_join((*it), &thread_result); 475 | if (res != 0) { 476 | //perror("Thread join failed"); 477 | writeLogEntry((unsigned char *)"//In Main: Thread joining failed\n"); 478 | exit(EXIT_FAILURE); 479 | //continue; 480 | } 481 | } 482 | 483 | //clearing out the data structres used, if incase needed a restart 484 | nodeConnectionMap.clear(); 485 | childThreadList.clear(); 486 | connectionMap.clear(); 487 | joinResponse.clear(); 488 | } 489 | 490 | 491 | void init(){ 492 | 493 | // If current node is beacon 494 | if (myInfo->isBeacon){ 495 | // Call the Accept thread 496 | // Thread creation and join code taken from WROX Publications book 497 | pthread_t accept_thread ; 498 | int res ; 499 | res = pthread_create(&accept_thread, NULL, accept_connectionsT , (void *)NULL); 500 | if (res != 0) { 501 | perror("Thread creation failed"); 502 | exit(EXIT_FAILURE); 503 | } 504 | childThreadList.push_front(accept_thread); 505 | 506 | // Connect to other beacon nodes 507 | list *tempBeaconList ; 508 | tempBeaconList = new list ; 509 | struct beaconList *b2; 510 | for(list::iterator it = myInfo->myBeaconList->begin(); it != myInfo->myBeaconList->end(); it++){ 511 | if ( (*it)->portNo != myInfo->portNo){ 512 | b2 = (struct beaconList *)malloc(sizeof(struct beaconList)) ; 513 | strncpy((char *)b2->hostName, const_cast((char *)(*it)->hostName), 256) ; 514 | b2->portNo = (*it)->portNo ; 515 | tempBeaconList->push_front(b2) ; 516 | } 517 | } 518 | 519 | //creating the connect threads for the beaocn node, which will retry and retry, untill gets conected to form a complete mesh 520 | for(list::iterator it = tempBeaconList->begin(); it != tempBeaconList->end() && shutDown!=1; ++it){ 521 | //struct node *n = (struct node *)malloc(sizeof(n)); 522 | struct node n; 523 | memset(&n, 0, sizeof(n)); 524 | //n = NULL; 525 | n.portNo = (*it)->portNo ; 526 | //memcpy(&n.portNo, &(*it)->portNo, sizeof((*it)->portNo)); 527 | //strncpy((char *)n->hostname, (const char *)(*it)->hostName, strlen((const char *)(*it)->hostName)) ; 528 | for (unsigned int i=0;ihostName);i++) 529 | n.hostname[i] = (*it)->hostName[i]; 530 | n.hostname[strlen((const char *)(*it)->hostName)] = '\0'; 531 | //memcpy(n.hostname, (*it)->hostName, strlen((char *)(*it)->hostName)) ; 532 | // Create a connect thread for this connection 533 | pthread_t connect_thread ; 534 | //printf("In Main: size of List is: %s %d\n", n->hostname, n->portNo); 535 | int res = pthread_create(&connect_thread, NULL, connectBeacon , (void *)&n); 536 | if (res != 0) { 537 | perror("Thread creation failed"); 538 | exit(EXIT_FAILURE); 539 | } 540 | childThreadList.push_front(connect_thread); 541 | //myConnectThread[connect_thread] = 0; 542 | sleep(1); 543 | } 544 | 545 | } 546 | else{ 547 | 548 | //code for the non-beacon node 549 | FILE *f; 550 | while(!shutDown) 551 | { 552 | 553 | unsigned char nodeName[256]; 554 | memset(&nodeName, '\0', 256); 555 | //printf("A regular node coming up...\n") ; 556 | 557 | //checking if the init_neighbor_list exsits or not 558 | 559 | f=fopen((char *)tempInitFile, "r"); 560 | //f=fopen("init_neighbor_list", "r"); 561 | sigset_t new_t; 562 | sigemptyset(&new_t); 563 | sigaddset(&new_t, SIGUSR1); 564 | 565 | if(f==NULL) 566 | { 567 | //printf("Neighbor List does not exist...Joining the network\n"); 568 | // exit(EXIT_FAILURE); 569 | writeLogEntry((unsigned char *)"//Initiating the Join process, since Init_Neighbor file not present\n"); 570 | 571 | //Adding Signal Handler for USR1 signal 572 | accept_pid=getpid(); 573 | 574 | pthread_sigmask(SIG_UNBLOCK, &new_t, NULL); 575 | 576 | signal(SIGUSR1, my_handler); 577 | 578 | inJoinNetwork = 1; 579 | joinNetwork() ; 580 | inJoinNetwork = 0; 581 | 582 | //printf("Joining success\n"); 583 | writeLogEntry((unsigned char *)"//Terminating the Join process, Init Neighbors identified\n"); 584 | myInfo->joinTimeOut = myInfo->joinTimeOut_permanent; 585 | continue ; 586 | } 587 | 588 | myInfo->joinTimeOut = -1; 589 | pthread_sigmask(SIG_BLOCK, &new_t, NULL); 590 | 591 | 592 | // Call the Accept thread 593 | // Thread creation and join code taken from WROX Publications book 594 | pthread_t accept_thread ; 595 | int res ; 596 | res = pthread_create(&accept_thread, NULL, accept_connectionsT , (void *)NULL); 597 | if (res != 0) { 598 | //perror("Thread creation failed"); 599 | writeLogEntry((unsigned char *)"//Accept Thread creation failed\n"); 600 | exit(EXIT_FAILURE); 601 | } 602 | childThreadList.push_front(accept_thread); 603 | 604 | // Connect to neighbors in the list 605 | // File exist, now say "Hello" 606 | list *tempNeighborsList; 607 | tempNeighborsList = new list; 608 | struct beaconList *b2; 609 | //for(unsigned int i=0;i < myInfo->minNeighbor; i++) 610 | while(fgets((char *)nodeName, 255, f)!=NULL) 611 | { 612 | //fgets(nodeName, 255, f); 613 | unsigned char *hostName = (unsigned char *)strtok((char *)nodeName, ":"); 614 | unsigned char *portNo = (unsigned char *)strtok(NULL, ":"); 615 | 616 | b2 = (struct beaconList *)malloc(sizeof(struct beaconList)) ; 617 | strncpy((char *)b2->hostName, (char *)(hostName), strlen((char *)hostName)) ; 618 | b2->hostName[strlen((char *)hostName)]='\0'; 619 | b2->portNo = atoi((char *)portNo); 620 | tempNeighborsList->push_back(b2) ; 621 | 622 | } 623 | 624 | int nodeConnected = 0; 625 | int resSock; 626 | for(list::iterator it = tempNeighborsList->begin(); it != tempNeighborsList->end() && shutDown!=1; it++){ 627 | struct node n; 628 | n.portNo = (*it)->portNo ; 629 | strncpy((char *)n.hostname, (const char *)(*it)->hostName, 256) ; 630 | pthread_mutex_lock(&nodeConnectionMapLock) ; 631 | //neighbor already exist in the neighbor list 632 | if (nodeConnectionMap.find(n)!=nodeConnectionMap.end()){ 633 | nodeConnected++; 634 | it = tempNeighborsList->erase(it) ; 635 | --it ; 636 | pthread_mutex_unlock(&nodeConnectionMapLock) ; 637 | continue ; 638 | } 639 | pthread_mutex_unlock(&nodeConnectionMapLock) ; 640 | 641 | //printf("Connecting to %s:%d\n", (*it)->hostName, (*it)->portNo) ; 642 | if(shutDown) 643 | { 644 | shutdown(resSock, SHUT_RDWR); 645 | close(resSock); 646 | break; 647 | } 648 | //trying to connect the host name and port no 649 | resSock = connectTo((*it)->hostName, (*it)->portNo) ; 650 | if(shutDown) 651 | { 652 | shutdown(resSock, SHUT_RDWR); 653 | close(resSock); 654 | break; 655 | } 656 | if (resSock == -1 ){ 657 | // Connection could not be established 658 | // now we have to reset the network, call JOIN 659 | continue; 660 | } 661 | else{ 662 | struct connectionNode cn ; 663 | struct node n; 664 | n.portNo = (*it)->portNo ; 665 | strncpy((char *)n.hostname, (const char *)(*it)->hostName, 256) ; 666 | it = tempNeighborsList->erase(it) ; 667 | --it ; 668 | // nodeConnectionMap[n] = resSock ; 669 | 670 | int mres = pthread_mutex_init(&cn.mesQLock, NULL) ; 671 | if (mres != 0){ 672 | //perror("Mutex initialization failed"); 673 | writeLogEntry((unsigned char *)"//Mutex Initializtaion failed\n"); 674 | 675 | } 676 | int cres = pthread_cond_init(&cn.mesQCv, NULL) ; 677 | if (cres != 0){ 678 | //perror("CV initialization failed") ; 679 | writeLogEntry((unsigned char *)"//CV Initializtaion failed\n"); 680 | } 681 | //Shutdown initilazed to zero 682 | cn.shutDown = 0 ; 683 | cn.keepAliveTimer = myInfo->keepAliveTimeOut/2; 684 | cn.keepAliveTimeOut = myInfo->keepAliveTimeOut; 685 | cn.isReady = 0; 686 | cn.n = n; 687 | //signal(SIGUSR2, my_handler); 688 | 689 | pthread_mutex_lock(&connectionMapLock) ; 690 | connectionMap[resSock] = cn ; 691 | pthread_mutex_unlock(&connectionMapLock) ; 692 | // Push a Hello type message in the writing queue 693 | struct Message m ; 694 | m.type = 0xfa ; 695 | m.status = 0 ; 696 | m.fromConnect = 1 ; 697 | pushMessageinQ(resSock, m) ; 698 | // pushMessageinQ(resSock, 0xfa) ; 699 | 700 | // Create a read thread for this connection 701 | pthread_t re_thread ; 702 | res = pthread_create(&re_thread, NULL, read_thread , (void *)resSock); 703 | if (res != 0) { 704 | //perror("Thread creation failed"); 705 | writeLogEntry((unsigned char *)"//Read Thread creation failed\n"); 706 | exit(EXIT_FAILURE); 707 | } 708 | pthread_mutex_lock(&connectionMapLock) ; 709 | connectionMap[resSock].myReadId = re_thread; 710 | childThreadList.push_front(re_thread); 711 | pthread_mutex_unlock(&connectionMapLock) ; 712 | 713 | // Create a write thread 714 | pthread_t wr_thread ; 715 | res = pthread_create(&wr_thread, NULL, write_thread , (void *)resSock); 716 | if (res != 0) { 717 | //perror("Thread creation failed"); 718 | writeLogEntry((unsigned char *)"//Write Thread creation failed\n"); 719 | exit(EXIT_FAILURE); 720 | } 721 | childThreadList.push_front(wr_thread); 722 | pthread_mutex_lock(&connectionMapLock) ; 723 | connectionMap[resSock].myWriteId = wr_thread; 724 | pthread_mutex_unlock(&connectionMapLock) ; 725 | 726 | nodeConnected++; 727 | } 728 | if(nodeConnected == (int)myInfo->minNeighbor) 729 | break; 730 | } 731 | 732 | //succesfully conected to minNeighbors 733 | if(nodeConnected == (int)myInfo->minNeighbor || shutDown) 734 | break; 735 | else 736 | { 737 | //coulndn't connect to the Min Neighbors, need to soft restart 738 | fclose(f); 739 | //remove((char *)tempInitFile); 740 | shutDown = 1; 741 | shutdown(nSocket_accept, SHUT_RDWR); 742 | close(nSocket_accept); 743 | 744 | //Send NOTIFY message beacouse of restart 745 | pthread_mutex_lock(&nodeConnectionMapLock); 746 | for (map::iterator it = nodeConnectionMap.begin(); it != nodeConnectionMap.end(); ++it) 747 | notifyMessageSend((*it).second, 3); 748 | pthread_mutex_unlock(&nodeConnectionMapLock); 749 | 750 | sleep(1); 751 | 752 | pthread_mutex_lock(&nodeConnectionMapLock) ; 753 | for (map::iterator it = nodeConnectionMap.begin(); it != nodeConnectionMap.end(); ++it) 754 | closeConnection((*it).second); 755 | nodeConnectionMap.clear(); 756 | pthread_mutex_unlock(&nodeConnectionMapLock) ; 757 | 758 | void *thread_result; 759 | for (list::iterator it = childThreadList.begin(); it != childThreadList.end(); ++it){ 760 | res = pthread_join((*it), &thread_result); 761 | if (res != 0) { 762 | perror("Thread join failed"); 763 | exit(EXIT_FAILURE); 764 | //continue; 765 | } 766 | } 767 | childThreadList.clear(); 768 | joinResponse.clear(); 769 | //myInfo->joinTimeOut = myInfo->joinTimeOut_permanent; 770 | resetValues(); 771 | continue; 772 | } 773 | 774 | } 775 | fclose(f); 776 | } 777 | 778 | 779 | } 780 | -------------------------------------------------------------------------------- /main.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | 23 | #define HEADER_SIZE 27 24 | #define SHA_DIGEST_LENGTH 20 25 | 26 | using namespace std ; 27 | 28 | //keeps the join responses 29 | extern set joinResponse ; 30 | //keeps the status messgae 31 | extern set< set > statusResponse ; 32 | extern map > statusResponseTypeFiles ; 33 | 34 | struct node{ 35 | unsigned short int portNo; 36 | unsigned char hostname[256]; 37 | 38 | bool operator<(const struct node& node1) const{ 39 | return node1.portNo < portNo ; 40 | } 41 | bool operator==(const struct node& node1) const{ 42 | return ((node1.portNo == portNo) && !strcmp((char *)node1.hostname, (char *)hostname)) ; 43 | } 44 | }; 45 | 46 | struct joinResNode{ 47 | unsigned short int portNo; 48 | unsigned char hostname[256]; 49 | uint32_t location ; 50 | 51 | bool operator<(const struct joinResNode& node1) const{ 52 | return node1.location > location ; 53 | } 54 | bool operator==(const struct joinResNode& node1) const{ 55 | return ((node1.portNo == portNo) && !strcmp((char *)node1.hostname, (char *)hostname) && (node1.location == location)) ; 56 | } 57 | }; 58 | 59 | extern map nodeConnectionMap ; // To store all the neighboring nodes 60 | extern pthread_mutex_t nodeConnectionMapLock ; 61 | 62 | struct metaData 63 | { 64 | unsigned int fileNumber; 65 | unsigned char fileID[20]; 66 | unsigned char fileName[256]; 67 | unsigned long int fileSize; 68 | unsigned char sha1[20]; 69 | unsigned char nonce[20]; 70 | list *keywords; 71 | //map keywords; 72 | unsigned char bitVector[128]; 73 | }; 74 | //message structure that goes into the messgae queues 75 | struct Message{ 76 | uint8_t type; 77 | unsigned char *buffer ; 78 | unsigned char *query ; 79 | unsigned char *metadata; 80 | unsigned char *fileName ; 81 | uint8_t ttl ; 82 | uint32_t location ; 83 | int status ; // 0 - originated from here 84 | unsigned char uoid[SHA_DIGEST_LENGTH] ; 85 | bool fromConnect ; // 1 - The message was created by the node which 86 | // initiated the connection 87 | int buffer_len ; 88 | uint8_t status_type ; 89 | unsigned char query_type ; 90 | uint8_t errorCode; 91 | } ; 92 | 93 | //information for the neighbors stored in this structures 94 | struct connectionNode{ 95 | list MessageQ ; 96 | pthread_mutex_t mesQLock ; 97 | pthread_cond_t mesQCv ; 98 | int shutDown ; 99 | unsigned int keepAliveTimer; 100 | int keepAliveTimeOut; 101 | int myReadId; 102 | int myWriteId; 103 | int isReady; 104 | bool joinFlag; 105 | struct node n; 106 | }; 107 | 108 | 109 | struct parsedDeleteMessage 110 | { 111 | unsigned char fileName[256]; 112 | unsigned char sha1[20]; 113 | unsigned char nonce[20]; 114 | unsigned char password[20]; 115 | }; 116 | 117 | extern unsigned char tempLogFile[512], tempInitFile[512]; 118 | extern bool shutDown ; 119 | extern int accept_pid; 120 | extern int nSocket_accept; 121 | extern int keepAlive_pid; 122 | extern int toBeClosed; 123 | extern int joinTimeOutFlag; 124 | extern int inJoinNetwork; 125 | extern int statusTimerFlag ; 126 | extern int checkTimerFlag ; 127 | extern int searchTimerFlag ; 128 | extern int node_pid; 129 | extern int softRestartFlag ; 130 | //extern int globalFileNumber ; 131 | extern int globalSearchCount ; 132 | extern int currentCacheSize; 133 | extern unsigned char extFile[256]; 134 | extern unsigned char filesDir[256]; 135 | extern FILE *f_log; 136 | extern map connectionMap ; // Stores all the info related to a connection 137 | extern list childThreadList ; 138 | extern map myConnectThread ; 139 | extern map > bitVectorIndexMap; 140 | extern map > fileNameIndexMap; 141 | extern map > sha1IndexMap; 142 | extern map fileIDMap; 143 | extern map getFileIDMap; 144 | extern list cacheLRU; 145 | //extern list metadataList; 146 | extern pthread_mutex_t connectionMapLock ; 147 | extern pthread_mutex_t statusMsgLock ; 148 | extern pthread_mutex_t searchMsgLock ; 149 | extern pthread_mutex_t getMsgLock ; 150 | extern pthread_mutex_t logEntryLock ; 151 | extern pthread_cond_t statusMsgCV; 152 | extern pthread_cond_t searchMsgCV; 153 | extern pthread_cond_t getMsgCV; 154 | extern list tmpFileNameList ; 155 | 156 | //pakcet structre stored in the cache at the nodes 157 | struct Packet{ 158 | 159 | struct node receivedFrom ; 160 | int status; // 0 - originally Sent from here, 161 | // 1 - Forwarded from here, route back, else -1 162 | int sockfd ; 163 | int msgLifeTime; 164 | int status_type ; 165 | }; 166 | 167 | extern map MessageDB ; // Keeps a track of all the messages it sends/forwards 168 | extern pthread_mutex_t MessageDBLock ; 169 | 170 | // Thread function declarations 171 | void *keyboard_thread(void *) ; 172 | void *timer_thread(void *) ; 173 | void *accept_connectionsT(void *); // Waits for other nodes to connect 174 | void *read_thread(void *) ; 175 | void *write_thread(void *) ; 176 | void *connectBeacon(void *); 177 | 178 | // Function declarations 179 | int isBeaconNode(struct node n); 180 | int connectTo(unsigned char *, unsigned int) ; 181 | extern pthread_t k_thread; 182 | void notifyMessageSend(int resSock, uint8_t errorCode); 183 | void pushMessageinQ(int, struct Message ) ; 184 | void closeConnection(int) ; 185 | void joinNetwork() ; 186 | void getStatus() ; 187 | void writeToStatusFile() ; 188 | void getStatusTypeFiles() ; 189 | void writeToStatusFile_TypeFiles() ; 190 | unsigned char *createLogEntry(unsigned char mode, int origin, unsigned char header[HEADER_SIZE], unsigned char *buffer); 191 | void writeLogEntry(unsigned char *logEntry); 192 | void eraseValueInMap(int val); 193 | extern unsigned char *GetUOID(char *, unsigned char *, long unsigned int) ; 194 | void initiateCheck() ; 195 | void init() ; 196 | void cleanup() ; 197 | void writeMetaData(struct metaData metadata, int globalFileNumber); 198 | int updateGlobalFileNumber(); 199 | void writeData(struct metaData, int globalFileNumber); 200 | void populateBitVectorIndexMap(unsigned char*, unsigned int); 201 | void populateSha1IndexMap(unsigned char*, unsigned int); 202 | void populateFileNameIndexMap(unsigned char*, unsigned int); 203 | unsigned char* toHex(unsigned char *str, int len); 204 | struct metaData populateMetaData(int fileNumber); 205 | void initiateSearch(unsigned char, unsigned char *) ; 206 | string MetaDataToStr(struct metaData) ; 207 | struct metaData populateMetaDataFromString(unsigned char *input); 208 | struct metaData populateMetaDataFromCPPString(string); 209 | int searchResponseDisplay(list metadataList, int count); 210 | void writeLRUToFile(); 211 | void readLRUFromFile(); 212 | void updateLRU(int fileNumber); 213 | void removeFromLRU(); 214 | int storeInLRU(struct metaData metadata, unsigned int fileNumber); 215 | list getAllFiles() ; 216 | struct parsedDeleteMessage parseDeleteMessage(unsigned char *message); 217 | void deleteFile(struct parsedDeleteMessage pd); 218 | int getFileNumberFromIndex(unsigned char *fileName, unsigned char *nonce); 219 | void deleteFromIndex(int); 220 | void deleteAllFiles(); 221 | void initiateDelete(unsigned char *) ; 222 | void initiateStore(string, string) ; 223 | void writeFileToCache(unsigned char *metadata_str, unsigned char *fileName); 224 | void writeFileToPermanent(unsigned char *metadata_str, unsigned char *fileName); 225 | void initiateGet(struct metaData) ; 226 | struct metaData populateMetaDataFromString_noFileID(unsigned char *input1); 227 | int doesFileExist(struct metaData ); 228 | void writeToFileFromData(unsigned char fileName[], int fileNumber); 229 | -------------------------------------------------------------------------------- /metaData.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "main.h" 11 | #include "iniParser.h" 12 | #include "signalHandler.h" 13 | #include "keepAliveTimer.h" 14 | #include 15 | #include "indexSearch.h" 16 | #include 17 | #include 18 | 19 | 20 | // Function to update the global file number in 21 | // the filesystem 22 | int updateGlobalFileNumber() 23 | { 24 | int globalFileNumber = 0; 25 | 26 | unsigned char fileNumber_file[256]; 27 | sprintf((char *)fileNumber_file, "%s/.fileNumber", myInfo->homeDir); 28 | 29 | FILE *f = fopen((char *)fileNumber_file, "r"); 30 | if(f==NULL) 31 | { 32 | printf("'.fileNumber'...File Does not exist\n"); 33 | exit(0); 34 | } 35 | fscanf(f, "%d", &globalFileNumber); 36 | fclose(f); 37 | 38 | globalFileNumber++; 39 | 40 | f = fopen((char *)fileNumber_file, "w"); 41 | if(f==NULL) 42 | { 43 | printf("'.fileNumber'...Error!!\n"); 44 | exit(0); 45 | } 46 | fprintf(f, "%d", globalFileNumber); 47 | fclose(f); 48 | 49 | return globalFileNumber; 50 | } 51 | 52 | 53 | // Write metadata in the filesystem 54 | void writeMetaData(struct metaData metadata, int globalFileNumber) 55 | { 56 | //unsigned char dir[10] = "files/"; 57 | 58 | unsigned char fileName[256]; 59 | sprintf((char *)fileName, "%s/%d.meta", filesDir, globalFileNumber); 60 | 61 | FILE *f = fopen((char *)fileName, "w"); 62 | 63 | // printf("IN WRTIE TO FILE\n\n"); 64 | fprintf(f,"%s\n","[metadata]"); 65 | fprintf(f, "%s=%s\n", "FileName", metadata.fileName); 66 | fprintf(f, "%s=%ld\n", "FileSize", metadata.fileSize); 67 | fprintf(f, "%s=", "SHA1"); 68 | for(int i=0;i<20;i++) 69 | { 70 | fprintf(f, "%02x", metadata.sha1[i]); 71 | //printf("%02x", metadata.sha1[i]); 72 | } 73 | 74 | fprintf(f, "\n%s=", "Nonce"); 75 | for(int i=0;i<20;i++) 76 | fprintf(f, "%02x", metadata.nonce[i]); 77 | 78 | fprintf(f, "\n%s=", "Keywords"); 79 | for (list::iterator it = metadata.keywords->begin(); it != metadata.keywords->end(); ++it){ 80 | //for (map::iterator it = metadata.keywords.begin(); it != metadata.keywords.end(); ++it){ 81 | fprintf(f, "%s ", (*it).c_str()); 82 | } 83 | 84 | fprintf(f, "\n%s=", "Bit-vector"); 85 | for(int i=0;i<128;i++) 86 | fprintf(f, "%02x", metadata.bitVector[i]); 87 | 88 | //fprintf(f, "\n%s=%s\n", "Bit-vector", metadata.bitVector); 89 | fclose(f); 90 | } 91 | 92 | 93 | 94 | string MetaDataToStr(struct metaData metadata) 95 | { 96 | string res ; 97 | res.append("[metadata]\nFileName=") ; 98 | res.append((char *)metadata.fileName) ; 99 | res.append("\nFileSize=") ; 100 | int len = res.size() ; 101 | res.resize(res.size()+16) ; 102 | 103 | 104 | sprintf(&res[len], "%ld\n", metadata.fileSize); 105 | res.resize(strlen(res.c_str())) ; 106 | res.append("SHA1=") ; 107 | len = res.size() ; 108 | res.resize(len+40) ; 109 | //printf("\n\n"); 110 | for(int i=0;i<20;i++) 111 | { 112 | sprintf(&res[len+i*2], "%02x", metadata.sha1[i]); 113 | //printf("%02x", metadata.sha1[i]); 114 | } 115 | 116 | //printf("\n\n"); 117 | res.append("\nNonce=") ; 118 | len = res.size() ; 119 | res.resize(len+40) ; 120 | for(int i=0;i<20;i++) 121 | sprintf(&res[len+i*2], "%02x", metadata.nonce[i]); 122 | 123 | res.append("\nKeywords=") ; 124 | len = res.size() ; 125 | for (list::iterator it = metadata.keywords->begin(); it != metadata.keywords->end(); ++it){ 126 | res.append((*it)) ; 127 | res.append(" ") ; 128 | } 129 | res.resize(res.size() -1) ; 130 | 131 | res.append("\nBit-vector=") ; 132 | len = res.size() ; 133 | res.resize(len+256) ; 134 | for(int i=0;i<128;i++) 135 | sprintf(&res[len+i*2], "%02x", metadata.bitVector[i]); 136 | res.resize(res.size()+1) ; 137 | res[len+256] = '\0' ; 138 | // res[len+257] = '\0' ; 139 | len = len +257 ; 140 | 141 | return res ; 142 | // strncpy((char *)str, res.c_str(), len) ; 143 | 144 | } 145 | 146 | 147 | 148 | 149 | // Method to write Data or the file content in the filesystem 150 | void writeData(struct metaData metadata, int globalFileNumber) 151 | { 152 | char ch; 153 | unsigned char fileName[256]; 154 | sprintf((char *)fileName, "%s/%d.data", filesDir, globalFileNumber); 155 | 156 | FILE *f = fopen((char *)metadata.fileName, "rb"); 157 | FILE *f1 = fopen((char *)fileName, "wb"); 158 | while(fread(&ch,1,1,f)!=0) 159 | fwrite(&ch, 1,1, f1); 160 | fclose(f); 161 | fclose(f1); 162 | } 163 | 164 | unsigned char* toHex(unsigned char *str, int len) 165 | { 166 | int l = len; 167 | unsigned char *w = (unsigned char*)malloc(sizeof(unsigned char)*len) ; 168 | 169 | memset(w, '\0', len) ; 170 | for(int i=0 ; i < l ; i++){ 171 | if(str[i*2] >= '0' && str[i*2] <= '9' ) { 172 | w[i] = str[i*2] - 48 ; 173 | } 174 | else if(str[i*2] >= 'a' && str[i*2] <= 'f' ) { 175 | w[i] = str[i*2] - 87 ; 176 | } 177 | else{ 178 | /*fprintf(stderr, "Value not a hexstring\n") ; 179 | exit(0) ;*/ 180 | } 181 | 182 | w[i] = w[i] << 4 ; 183 | 184 | if(str[i*2+1] >= '0' && str[i*2+1] <= '9' ) { 185 | w[i] = w[i] | (str[i*2+1] - 48) ; 186 | } 187 | else if(str[i*2+1] >= 'a' && str[i*2+1] <= 'f' ) { 188 | w[i] = w[i] | (str[i*2+1] - 87) ; 189 | } 190 | else{ 191 | /*fprintf(stderr, "Value not a hexstring\n") ; 192 | exit(0) ;*/ 193 | } 194 | 195 | } 196 | 197 | // puts((char *)w); 198 | return w; 199 | } 200 | 201 | void writeToFileFromData(unsigned char fileName[], int fileNumber) 202 | { 203 | unsigned char ch; 204 | unsigned char fileName_temp[256]; 205 | sprintf((char *)fileName_temp, "%s/%d.data", filesDir, fileNumber); 206 | 207 | FILE *f = fopen((char *)fileName_temp, "rb"); 208 | FILE *f1 = fopen((char *)fileName, "wb"); 209 | while(fread(&ch,1,1,f)!=0) 210 | fwrite(&ch, 1,1, f1); 211 | fclose(f); 212 | fclose(f1); 213 | } 214 | 215 | 216 | // Populate the metadata data structure from the filesystem 217 | struct metaData populateMetaData(int fileNumber) 218 | { 219 | struct metaData metadata; 220 | memset(&metadata, 0, sizeof(metaData)); 221 | unsigned char fileName[256]; 222 | memset(fileName, '\0', sizeof(fileName)); 223 | unsigned char buffer[1024]; 224 | memset(buffer, '\0', sizeof(buffer)); 225 | unsigned char *key; 226 | 227 | sprintf((char *)fileName, "%s/%d.meta", filesDir, fileNumber); 228 | 229 | memset(metadata.fileID, '\0', sizeof(metadata.fileID)); 230 | GetUOID( const_cast ("FileID"), metadata.fileID, sizeof(metadata.fileID)) ; 231 | 232 | FILE *f = fopen((char *)fileName, "r"); 233 | if(f==NULL) 234 | { 235 | // printf("FileName is : %s\n", fileName); 236 | printf("File does not exist\n"); 237 | exit(0) ; 238 | } 239 | 240 | while(fgets((char *)buffer, 1023, f)!=NULL) 241 | { 242 | if(strstr((char *)buffer, "FileName=")!=NULL) 243 | { 244 | key = (unsigned char *)strtok((char *)buffer, "="); 245 | key = (unsigned char *)strtok(NULL, "\n"); 246 | strncpy((char *)metadata.fileName, (char *)key, strlen((char *)key)); 247 | } 248 | else if(strstr((char *)buffer, "FileSize=")!=NULL) 249 | { 250 | key = (unsigned char *)strtok((char *)buffer, "="); 251 | key = (unsigned char *)strtok(NULL, "\n"); 252 | //strncpy(metadata->fileName, key, strlen(key)); 253 | metadata.fileSize = atol((char *)key); 254 | } 255 | else if(strstr((char *)buffer, "SHA1=")!=NULL) 256 | { 257 | key = (unsigned char *)strtok((char *)buffer, "="); 258 | key = (unsigned char *)strtok(NULL, "\n"); 259 | unsigned char *str = toHex(key, 20); 260 | //printf("In populate metadata:\n\n"); 261 | for(int i=0;i<20;i++) 262 | { 263 | metadata.sha1[i] = str[i]; 264 | //printf("%02x", metadata.sha1[i]); 265 | } 266 | //printf("\n\n"); 267 | //strncpy((char *)metadata.sha1, (char *)str, 20); 268 | free(str); 269 | } 270 | else if(strstr((char *)buffer, "Nonce=")!=NULL) 271 | { 272 | key = (unsigned char *)strtok((char *)buffer, "="); 273 | key = (unsigned char *)strtok(NULL, "\n"); 274 | unsigned char *str = toHex(key, 20); 275 | for(int i=0;i<20;i++) 276 | metadata.nonce[i] = str[i]; 277 | //strncpy((char *)metadata.nonce, (char *)str, 20); 278 | free(str); 279 | } 280 | else if(strstr((char *)buffer, "Keywords=")!=NULL) 281 | { 282 | key = (unsigned char *)strtok((char *)buffer, "="); 283 | key = (unsigned char *)strtok(NULL, "\n"); 284 | //strncpy(metadata->fileName, key, strlen(key)); 285 | unsigned char *key1 = NULL; 286 | metadata.keywords = new list(); 287 | while((key1 = (unsigned char*)strtok((char *)key, " "))!=NULL) 288 | { 289 | metadata.keywords->push_back(string((char *)key1)); 290 | key=NULL; 291 | } 292 | } 293 | else if(strstr((char *)buffer, "Bit-vector=")!=NULL) 294 | { 295 | key = (unsigned char *)strtok((char *)buffer, "="); 296 | key = (unsigned char *)strtok(NULL, "="); 297 | 298 | unsigned char *str = toHex(key, 128); 299 | for(int i=0;i<128;i++) 300 | metadata.bitVector[i] = str[i]; 301 | 302 | free(str); 303 | } 304 | } 305 | fclose(f); 306 | /*printf("Some values are: \n\n"); 307 | printf("%s\n%ld\n", metadata.fileName, metadata.fileSize); 308 | for(int i=0;i<20;i++) 309 | printf("%02x", metadata.sha1[i]); 310 | printf("\n"); 311 | for(int i=0;i<20;i++) 312 | printf("%02x", metadata.nonce[i]); 313 | printf("\n"); 314 | for (list::iterator it = metadata.keywords->begin(); it != metadata.keywords->end(); ++it){ 315 | printf("%s ", (*it).c_str()); 316 | } 317 | printf("\n"); 318 | for(int i=0;i<128;i++) 319 | printf("%02x", metadata.bitVector[i]); 320 | printf("\n");*/ 321 | return metadata; 322 | } 323 | 324 | /*void updateLRU(unsigned int fileNumber) 325 | { 326 | list::iterator result = find(cacheLRU.begin(), cacheLRU.end(), (int)fileNumber); 327 | if(result!=cacheLRU.end()) 328 | { 329 | cacheLRU.remove(fileNumber); 330 | cacheLRU.push_back(fileNumber); 331 | } 332 | }*/ 333 | 334 | 335 | // populate the metadata data structure from a string, 336 | // usually used to populate the structure from the string received 337 | // over the socket 338 | struct metaData populateMetaDataFromString(unsigned char *input1) 339 | { 340 | struct metaData metadata; 341 | memset(&metadata, 0, sizeof(metaData)); 342 | unsigned char *buffer; 343 | unsigned char *key, *saveptr1, *saveptr2; 344 | unsigned char input[strlen((char *)input1)]; 345 | strncpy((char *)metadata.fileID, (char *)input1, 20); 346 | // strncpy((char *)input, (char *)input1+20, strlen((char *)input1)-20); 347 | for(int i = 0 ; i < (int)(strlen((char *)input1)-20) ; ++i) 348 | input[i] = input1[i+20] ; 349 | 350 | /*memset(metadata.fileID, '\0', sizeof(metadata.fileID)); 351 | GetUOID( const_cast ("FileID"), metadata.fileID, sizeof(metadata.fileID)) ;*/ 352 | 353 | buffer = (unsigned char *)strtok_r((char *)input, "\n", (char **)&saveptr1); 354 | while((buffer = (unsigned char *)strtok_r(NULL, "\n", (char **)&saveptr1))!=NULL) 355 | { 356 | //printf("value is: %s\n", buffer); 357 | if(strstr((char *)buffer, "FileName=")!=NULL) 358 | { 359 | key = (unsigned char *)strtok_r((char *)buffer, "=", (char **)&saveptr2); 360 | key = (unsigned char *)strtok_r(NULL, "\n", (char **)&saveptr2); 361 | strncpy((char *)metadata.fileName, (char *)key, strlen((char *)key)); 362 | } 363 | else if(strstr((char *)buffer, "FileSize=")!=NULL) 364 | { 365 | key = (unsigned char *)strtok_r((char *)buffer, "=", (char **)&saveptr2); 366 | key = (unsigned char *)strtok_r(NULL, "\n", (char **)&saveptr2); 367 | //strncpy(metadata->fileName, key, strlen(key)); 368 | metadata.fileSize = atol((char *)key); 369 | } 370 | else if(strstr((char *)buffer, "SHA1=")!=NULL) 371 | { 372 | key = (unsigned char *)strtok_r((char *)buffer, "=", (char **)&saveptr2); 373 | key = (unsigned char *)strtok_r(NULL, "\n", (char **)&saveptr2); 374 | unsigned char *str = toHex(key, 20); 375 | strncpy((char *)metadata.sha1, (char *)str, 20); 376 | free(str); 377 | } 378 | else if(strstr((char *)buffer, "Nonce=")!=NULL) 379 | { 380 | key = (unsigned char *)strtok_r((char *)buffer, "=",(char **)&saveptr2); 381 | key = (unsigned char *)strtok_r(NULL, "\n", (char **)&saveptr2); 382 | unsigned char *str = toHex(key, 20); 383 | strncpy((char *)metadata.nonce, (char *)str, 20); 384 | free(str); 385 | } 386 | else if(strstr((char *)buffer, "Keywords=")!=NULL) 387 | { 388 | key = (unsigned char *)strtok_r((char *)buffer, "=", (char **)&saveptr2); 389 | key = (unsigned char *)strtok_r(NULL, "\n", (char **)&saveptr2); 390 | //strncpy(metadata->fileName, key, strlen(key)); 391 | unsigned char *key1 = NULL; 392 | metadata.keywords = new list(); 393 | while((key1 = (unsigned char*)strtok((char *)key, " "))!=NULL) 394 | { 395 | metadata.keywords->push_back(string((char *)key1)); 396 | key=NULL; 397 | } 398 | } 399 | else if(strstr((char *)buffer, "Bit-vector=")!=NULL) 400 | { 401 | key = (unsigned char *)strtok_r((char *)buffer, "=", (char **)&saveptr2); 402 | key = (unsigned char *)strtok_r(NULL, "=", (char **)&saveptr2); 403 | 404 | unsigned char *str = toHex(key, 128); 405 | for(int i=0;i<128;i++) 406 | metadata.bitVector[i] = str[i]; 407 | 408 | free(str); 409 | } 410 | } 411 | /*printf("Some values are: \n\n"); 412 | printf("%s\n%ld\n", metadata.fileName, metadata.fileSize); 413 | for(int i=0;i<20;i++) 414 | printf("%02x", metadata.sha1[i]); 415 | printf("\n"); 416 | for(int i=0;i<20;i++) 417 | printf("%02x", metadata.nonce[i]); 418 | printf("\n"); 419 | for (list::iterator it = metadata.keywords->begin(); it != metadata.keywords->end(); ++it){ 420 | printf("%s ", (*it).c_str()); 421 | } 422 | printf("\n"); 423 | for(int i=0;i<128;i++) 424 | printf("%02x", metadata.bitVector[i]); 425 | printf("\n");*/ 426 | return metadata; 427 | } 428 | 429 | 430 | 431 | // Does the same thing as above, just that the argument in this case 432 | // is C++ string instead of pointer to memory 433 | struct metaData populateMetaDataFromCPPString(string input1) 434 | { 435 | struct metaData metadata; 436 | memset(&metadata, 0, sizeof(metaData)); 437 | unsigned char *buffer; 438 | unsigned char *key, *saveptr1, *saveptr2; 439 | unsigned char input[input1.size()]; 440 | strncpy((char *)metadata.fileID, (char *)input1.c_str(), 20); 441 | // strncpy((char *)input, (char *)input1+20, strlen((char *)input1)-20); 442 | for(int i = 0 ; i < (int)input1.size()-20 ; ++i) 443 | input[i] = input1[i+20] ; 444 | 445 | /*memset(metadata.fileID, '\0', sizeof(metadata.fileID)); 446 | GetUOID( const_cast ("FileID"), metadata.fileID, sizeof(metadata.fileID)) ;*/ 447 | 448 | buffer = (unsigned char *)strtok_r((char *)input, "\n", (char **)&saveptr1); 449 | while((buffer = (unsigned char *)strtok_r(NULL, "\n", (char **)&saveptr1))!=NULL) 450 | { 451 | //printf("value is: %s\n", buffer); 452 | if(strstr((char *)buffer, "FileName=")!=NULL) 453 | { 454 | key = (unsigned char *)strtok_r((char *)buffer, "=", (char **)&saveptr2); 455 | key = (unsigned char *)strtok_r(NULL, "\n", (char **)&saveptr2); 456 | strncpy((char *)metadata.fileName, (char *)key, strlen((char *)key)); 457 | } 458 | else if(strstr((char *)buffer, "FileSize=")!=NULL) 459 | { 460 | key = (unsigned char *)strtok_r((char *)buffer, "=", (char **)&saveptr2); 461 | key = (unsigned char *)strtok_r(NULL, "\n", (char **)&saveptr2); 462 | //strncpy(metadata->fileName, key, strlen(key)); 463 | metadata.fileSize = atol((char *)key); 464 | } 465 | else if(strstr((char *)buffer, "SHA1=")!=NULL) 466 | { 467 | key = (unsigned char *)strtok_r((char *)buffer, "=", (char **)&saveptr2); 468 | key = (unsigned char *)strtok_r(NULL, "\n", (char **)&saveptr2); 469 | unsigned char *str = toHex(key, 20); 470 | strncpy((char *)metadata.sha1, (char *)str, 20); 471 | free(str); 472 | } 473 | else if(strstr((char *)buffer, "Nonce=")!=NULL) 474 | { 475 | key = (unsigned char *)strtok_r((char *)buffer, "=",(char **)&saveptr2); 476 | key = (unsigned char *)strtok_r(NULL, "\n", (char **)&saveptr2); 477 | unsigned char *str = toHex(key, 20); 478 | strncpy((char *)metadata.nonce, (char *)str, 20); 479 | free(str); 480 | } 481 | else if(strstr((char *)buffer, "Keywords=")!=NULL) 482 | { 483 | key = (unsigned char *)strtok_r((char *)buffer, "=", (char **)&saveptr2); 484 | key = (unsigned char *)strtok_r(NULL, "\n", (char **)&saveptr2); 485 | //strncpy(metadata->fileName, key, strlen(key)); 486 | unsigned char *key1 = NULL; 487 | metadata.keywords = new list(); 488 | while((key1 = (unsigned char*)strtok((char *)key, " "))!=NULL) 489 | { 490 | metadata.keywords->push_back(string((char *)key1)); 491 | key=NULL; 492 | } 493 | } 494 | else if(strstr((char *)buffer, "Bit-vector=")!=NULL) 495 | { 496 | key = (unsigned char *)strtok_r((char *)buffer, "=", (char **)&saveptr2); 497 | key = (unsigned char *)strtok_r(NULL, "=", (char **)&saveptr2); 498 | 499 | unsigned char *str = toHex(key, 128); 500 | for(int i=0;i<128;i++) 501 | metadata.bitVector[i] = str[i]; 502 | 503 | free(str); 504 | } 505 | } 506 | return metadata; 507 | } 508 | 509 | 510 | struct metaData populateMetaDataFromString_noFileID(unsigned char *input) 511 | { 512 | struct metaData metadata; 513 | memset(&metadata, 0, sizeof(metaData)); 514 | unsigned char *buffer; 515 | unsigned char *key, *saveptr1, *saveptr2; 516 | 517 | /*memset(metadata.fileID, '\0', sizeof(metadata.fileID)); 518 | GetUOID( const_cast ("FileID"), metadata.fileID, sizeof(metadata.fileID)) ;*/ 519 | 520 | buffer = (unsigned char *)strtok_r((char *)input, "\n", (char **)&saveptr1); 521 | strncpy((char *)input, (char *)buffer, strlen((char *)buffer)); 522 | while((buffer = (unsigned char *)strtok_r(NULL, "\n", (char **)&saveptr1))!=NULL) 523 | { 524 | //printf("value is: %s\n", buffer); 525 | if(strstr((char *)buffer, "FileName=")!=NULL) 526 | { 527 | key = (unsigned char *)strtok_r((char *)buffer, "=", (char **)&saveptr2); 528 | key = (unsigned char *)strtok_r(NULL, "\n", (char **)&saveptr2); 529 | strncpy((char *)metadata.fileName, (char *)key, strlen((char *)key)); 530 | } 531 | else if(strstr((char *)buffer, "FileSize=")!=NULL) 532 | { 533 | key = (unsigned char *)strtok_r((char *)buffer, "=", (char **)&saveptr2); 534 | key = (unsigned char *)strtok_r(NULL, "\n", (char **)&saveptr2); 535 | //strncpy(metadata->fileName, key, strlen(key)); 536 | metadata.fileSize = atol((char *)key); 537 | } 538 | else if(strstr((char *)buffer, "SHA1=")!=NULL) 539 | { 540 | key = (unsigned char *)strtok_r((char *)buffer, "=", (char **)&saveptr2); 541 | key = (unsigned char *)strtok_r(NULL, "\n", (char **)&saveptr2); 542 | unsigned char *str = toHex(key, 20); 543 | //strncpy((char *)metadata.sha1, (char *)str, 20); 544 | 545 | //printf("\n\n%s\n\n",key); 546 | for(int i=0;i<20;i++) 547 | { 548 | //printf("%02x", str[i]); 549 | metadata.sha1[i] = str[i]; 550 | } 551 | //printf("\n\n"); 552 | 553 | free(str); 554 | } 555 | else if(strstr((char *)buffer, "Nonce=")!=NULL) 556 | { 557 | key = (unsigned char *)strtok_r((char *)buffer, "=",(char **)&saveptr2); 558 | key = (unsigned char *)strtok_r(NULL, "\n", (char **)&saveptr2); 559 | unsigned char *str = toHex(key, 20); 560 | strncpy((char *)metadata.nonce, (char *)str, 20); 561 | free(str); 562 | } 563 | else if(strstr((char *)buffer, "Keywords=")!=NULL) 564 | { 565 | key = (unsigned char *)strtok_r((char *)buffer, "=", (char **)&saveptr2); 566 | key = (unsigned char *)strtok_r(NULL, "\n", (char **)&saveptr2); 567 | //strncpy(metadata->fileName, key, strlen(key)); 568 | unsigned char *key1 = NULL; 569 | metadata.keywords = new list(); 570 | while((key1 = (unsigned char*)strtok((char *)key, " "))!=NULL) 571 | { 572 | metadata.keywords->push_back(string((char *)key1)); 573 | key=NULL; 574 | } 575 | } 576 | else if(strstr((char *)buffer, "Bit-vector=")!=NULL) 577 | { 578 | key = (unsigned char *)strtok_r((char *)buffer, "=", (char **)&saveptr2); 579 | key = (unsigned char *)strtok_r(NULL, "=", (char **)&saveptr2); 580 | 581 | unsigned char *str = toHex(key, 128); 582 | for(int i=0;i<128;i++) 583 | metadata.bitVector[i] = str[i]; 584 | 585 | free(str); 586 | } 587 | } 588 | /*printf("Some values are: \n\n"); 589 | printf("%s\n%ld\n", metadata.fileName, metadata.fileSize); 590 | for(int i=0;i<20;i++) 591 | printf("%02x", metadata.sha1[i]); 592 | printf("\n"); 593 | for(int i=0;i<20;i++) 594 | printf("%02x", metadata.nonce[i]); 595 | printf("\n"); 596 | for (list::iterator it = metadata.keywords->begin(); it != metadata.keywords->end(); ++it){ 597 | printf("%s ", (*it).c_str()); 598 | } 599 | printf("\n"); 600 | for(int i=0;i<128;i++) 601 | printf("%02x", metadata.bitVector[i]); 602 | printf("\n");*/ 603 | return metadata; 604 | } 605 | void updateLRU(int fileNumber) 606 | { 607 | list::iterator result = find(cacheLRU.begin(), cacheLRU.end(), (int)fileNumber); 608 | if(result!=cacheLRU.end()) 609 | { 610 | cacheLRU.erase(result); 611 | cacheLRU.push_back(fileNumber); 612 | } 613 | } 614 | 615 | int storeInLRU(struct metaData metadata, unsigned int fileNumber) 616 | { 617 | if(metadata.fileSize > myInfo->cacheSize) 618 | return -1; 619 | while((metadata.fileSize + currentCacheSize) > myInfo->cacheSize) 620 | { 621 | //removeFromLRU(); 622 | deleteFromIndex(cacheLRU.front()); 623 | //printf("I am in here \n"); 624 | } 625 | //printf("Isereted into list: %d\n", fileNumber); 626 | cacheLRU.push_back(fileNumber); 627 | currentCacheSize+=metadata.fileSize; 628 | //printf("currentCacheSize is: %d\n", currentCacheSize); 629 | return 1; 630 | } 631 | 632 | void removeFromLRU() 633 | { 634 | /*int toBeRemoved = cacheLRU.front(); 635 | printf("removed from list: %d\n", toBeRemoved); 636 | struct metaData metadata = populateMetaData(toBeRemoved); 637 | //currentCacheSize -= metadata.fileSize; 638 | //cacheLRU.pop_front(); 639 | 640 | deleteFromIndex(toBeRemoved); 641 | 642 | cacheLRU.remove(toBeRemoved); 643 | unsigned char removeString[256]; 644 | 645 | memset(removeString, '\0', 256); 646 | sprintf((char *)removeString, "%s/%d.data", filesDir, (toBeRemoved)); 647 | remove((char *)removeString); 648 | 649 | memset(removeString, '\0', 256); 650 | sprintf((char *)removeString, "%s/%d.meta", filesDir, toBeRemoved); 651 | remove((char *)removeString); 652 | 653 | memset(removeString, '\0', 256); 654 | sprintf((char *)removeString, "%s/%d.pass", filesDir, toBeRemoved); 655 | remove((char *)removeString);*/ 656 | } 657 | 658 | // Externalising the LRU 659 | void writeLRUToFile() 660 | { 661 | unsigned char cacheLRU_file[256]; 662 | sprintf((char *)cacheLRU_file, "%s/cacheLRU", myInfo->homeDir); 663 | 664 | FILE *f = fopen((char *)cacheLRU_file, "w"); 665 | for(list :: iterator it = cacheLRU.begin(); it!=cacheLRU.end();it++) 666 | { 667 | fprintf(f, "%d ", (*it)); 668 | } 669 | fclose(f); 670 | } 671 | 672 | // Read the LRU from file, usually done at startup 673 | void readLRUFromFile() 674 | { 675 | int temp; 676 | unsigned char cacheLRU_file[256]; 677 | sprintf((char *)cacheLRU_file, "%s/cacheLRU", myInfo->homeDir); 678 | 679 | FILE *f = fopen((char *)cacheLRU_file, "r"); 680 | if(f!=NULL) 681 | { 682 | while(fscanf(f, "%d ", &temp)!=EOF) 683 | { 684 | cacheLRU.push_back(temp); 685 | struct metaData metadata = populateMetaData(temp); 686 | currentCacheSize += metadata.fileSize; 687 | } 688 | fclose(f); 689 | } 690 | } 691 | 692 | // Displays the metadata response in the required format 693 | int searchResponseDisplay(list metadataList, int count) 694 | { 695 | for(list::iterator it = metadataList.begin(); it!=metadataList.end(); ++it, count++) 696 | { 697 | getFileIDMap[count] = (*it); 698 | printf("[%d] FileID=", count); 699 | for(int i=0;i<20;i++) 700 | printf("%02x", (*it).fileID[i]); 701 | printf("\n FileName=%s", (*it).fileName); 702 | printf("\n FileSize=%ld", (*it).fileSize); 703 | printf("\n SHA1="); 704 | for(int i=0;i<20;i++) 705 | printf("%02x", (*it).sha1[i]); 706 | printf("\n Nonce="); 707 | for(int i=0;i<20;i++) 708 | printf("%02x", (*it).nonce[i]); 709 | printf("\n Keywords="); 710 | for(list ::iterator it1 = (*it).keywords->begin(); it1!=(*it).keywords->end();++it1) 711 | { 712 | printf("%s ", (*it1).c_str()); 713 | } 714 | printf("\n"); 715 | } 716 | return count; 717 | } 718 | 719 | struct parsedDeleteMessage parseDeleteMessage(unsigned char *message) 720 | { 721 | struct parsedDeleteMessage pd; 722 | memset(&pd, 0, sizeof(pd)); 723 | unsigned char *value = NULL; 724 | unsigned char *saveptr1, *saveptr2; 725 | while((value = (unsigned char *)strtok_r((char *)message, "\r\n", (char **)&saveptr1))!=NULL) 726 | { 727 | if(strstr((char *)value, "FileName=")!=NULL) 728 | { 729 | unsigned char *key = (unsigned char *)strtok_r((char *)value, "=", (char **)&saveptr2); 730 | key = (unsigned char *)strtok_r(NULL, "=", (char **)&saveptr2); 731 | strncpy((char *)pd.fileName, (char *)key, strlen((char *)key)); 732 | } 733 | else if(strstr((char *)value, "SHA1=")!=NULL) 734 | { 735 | unsigned char *key = (unsigned char *)strtok_r((char *)value, "=", (char **)&saveptr2); 736 | key = (unsigned char *)strtok_r(NULL, "=", (char **)&saveptr2); 737 | strncpy((char *)pd.sha1, (char *)toHex(key, 20), 20); 738 | } 739 | else if(strstr((char *)value, "Nonce=")!=NULL) 740 | { 741 | unsigned char *key = (unsigned char *)strtok_r((char *)value, "=", (char **)&saveptr2); 742 | key = (unsigned char *)strtok_r(NULL, "=", (char **)&saveptr2); 743 | strncpy((char *)pd.nonce, (char *)toHex(key, 20), 20); 744 | } 745 | else if(strstr((char *)value, "Password=")!=NULL) 746 | { 747 | unsigned char *key = (unsigned char *)strtok_r((char *)value, "=", (char **)&saveptr2); 748 | key = (unsigned char *)strtok_r(NULL, "=", (char **)&saveptr2); 749 | strncpy((char *)pd.password, (char *)toHex(key, 20), 20); 750 | } 751 | message = NULL; 752 | saveptr2 = NULL; 753 | } 754 | return pd; 755 | } 756 | 757 | void deleteFile(struct parsedDeleteMessage pd) 758 | { 759 | unsigned char *nonce = (unsigned char *)malloc(sizeof(unsigned char)*20); 760 | SHA1(pd.password, 20, nonce); 761 | 762 | if(strncmp((char *)nonce, (char *)pd.nonce, 20)==0) 763 | { 764 | 765 | int fileNumber = getFileNumberFromIndex(pd.fileName, pd.nonce); 766 | if(fileNumber!=-1){ 767 | deleteFromIndex(fileNumber); 768 | } 769 | } 770 | } 771 | 772 | int getFileNumberFromIndex(unsigned char *fileName, unsigned char *nonce) 773 | { 774 | int ret = -1; 775 | list tempList = fileNameIndexMap[string((char *)fileName)]; 776 | 777 | for(list ::iterator it = tempList.begin();it!=tempList.end();it++) 778 | { 779 | struct metaData metadata = populateMetaData((*it)); 780 | if(strncmp((char *)nonce,(char *)metadata.nonce, 20)==0) 781 | { 782 | return (*it); 783 | } 784 | } 785 | 786 | return ret; 787 | } 788 | -------------------------------------------------------------------------------- /outgoing_connections.cc: -------------------------------------------------------------------------------- 1 | #include "main.h" 2 | #include "iniParser.h" 3 | #include "signalHandler.h" 4 | #include "indexSearch.h" 5 | #include 6 | #include 7 | #include 8 | 9 | #ifndef min 10 | #define min(A,B) (((A)>(B)) ? (B) : (A)) 11 | #endif /* ~min */ 12 | 13 | unsigned char *GetUOID(char *obj_type, unsigned char *uoid_buf, long unsigned int uoid_buf_sz) ; 14 | map MessageDB ; 15 | 16 | //Write thread, picks the message from the queue and then process it and send to the destinations 17 | //if no message, it goes to sleep 18 | void *write_thread(void *args){ 19 | long sockfd = (long)args ; 20 | struct Message mes ; 21 | unsigned char header[HEADER_SIZE] ; 22 | unsigned char *buffer ; 23 | uint32_t len = 0 ; 24 | FILE *fp; 25 | struct stat st ; 26 | //signal(SIGUSR1, my_handler); 27 | //printf("My Id is write: %d\n", (int)pthread_self()); 28 | //connectionMap[sockfd].myWriteId = pthread_self(); 29 | 30 | while(!shutDown && !(connectionMap[sockfd].shutDown)){ 31 | //if no messages in the queue, it goes to sleep, wait 32 | if(connectionMap[sockfd].MessageQ.size() <= 0){ 33 | pthread_mutex_lock(&connectionMap[sockfd].mesQLock) ; 34 | pthread_cond_wait(&connectionMap[sockfd].mesQCv, &connectionMap[sockfd].mesQLock) ; 35 | if (connectionMap[sockfd].shutDown) 36 | { 37 | pthread_mutex_unlock(&connectionMap[sockfd].mesQLock) ; 38 | break ; 39 | } 40 | mes = connectionMap[sockfd].MessageQ.front() ; 41 | connectionMap[sockfd].MessageQ.pop_front() ; 42 | pthread_mutex_unlock(&connectionMap[sockfd].mesQLock) ; 43 | 44 | } 45 | else{ 46 | pthread_mutex_lock(&connectionMap[sockfd].mesQLock) ; 47 | mes = connectionMap[sockfd].MessageQ.front() ; 48 | connectionMap[sockfd].MessageQ.pop_front() ; 49 | pthread_mutex_unlock(&connectionMap[sockfd].mesQLock) ; 50 | } 51 | if (connectionMap[sockfd].shutDown) 52 | { 53 | pthread_mutex_unlock(&connectionMap[sockfd].mesQLock) ; 54 | break ; 55 | } 56 | 57 | memset(header, 0, HEADER_SIZE) ; 58 | 59 | // Message originated from here 60 | if (mes.status == 0){ 61 | unsigned char uoid[SHA_DIGEST_LENGTH] ; 62 | GetUOID( const_cast ("msg"), uoid, sizeof(uoid)) ; 63 | struct Packet pk; 64 | pk.status = 0 ; 65 | pk.msgLifeTime = myInfo->msgLifeTime; 66 | pthread_mutex_lock(&MessageDBLock) ; 67 | MessageDB[string((const char *)uoid, SHA_DIGEST_LENGTH) ] = pk ; 68 | pthread_mutex_unlock(&MessageDBLock) ; 69 | for (int i=0 ; i < SHA_DIGEST_LENGTH ; i++) 70 | header[1+i] = uoid[i] ; 71 | } 72 | // Copy the uoid from the structure into the header 73 | else if (mes.status == 1){ 74 | // memcpy((char *)&header[1], mes.uoid, 20) ; 75 | //pk.status = 1 ; 76 | for (int i=0 ; i < SHA_DIGEST_LENGTH ; i++) 77 | header[1+i] = mes.uoid[i] ; 78 | 79 | 80 | } 81 | // Done for status message 82 | else if (mes.status == 2 || mes.status == 3){ 83 | for (int i=0 ; i < SHA_DIGEST_LENGTH ; i++) 84 | header[1+i] = mes.uoid[i] ; 85 | } 86 | 87 | // Message of type Hello 88 | if (mes.type == 0xfa){ 89 | //printf("Sending Hello Message\n") ; 90 | header[0] = 0xfa; 91 | header[21] = 0x01 ; 92 | unsigned char host[256] ; 93 | gethostname((char *)host, 256) ; 94 | host[255] = '\0' ; 95 | len = strlen((char *)host) + 2 ; 96 | memcpy((char *)&header[23], &(len), 4) ; 97 | 98 | buffer = (unsigned char *)malloc(len) ; 99 | memset(buffer, '\0', len) ; 100 | memcpy((char *)buffer, &(myInfo->portNo), 2) ; 101 | 102 | // sprintf((char *)&buffer[2], "%s", host); 103 | for (int i = 0 ; i < (int)len - 2 ; ++i) 104 | buffer[2+i] = host[i] ; 105 | 106 | //Incrementing Ready STatus 107 | pthread_mutex_lock(&connectionMapLock) ; 108 | connectionMap[sockfd].isReady++; 109 | pthread_mutex_unlock(&connectionMapLock) ; 110 | 111 | 112 | } 113 | // Sending JOIN Request 114 | else if (mes.type == 0xfc){ 115 | // printf("Sending JOIN request\n") ; 116 | 117 | if (mes.status == 1){ 118 | buffer = mes.buffer ; 119 | len = mes.buffer_len ; 120 | } 121 | else{ 122 | unsigned char host[256] ; 123 | gethostname((char *)host, 256) ; 124 | host[255] = '\0' ; 125 | len = strlen((char *)host) + 6 ; 126 | buffer = (unsigned char *)malloc(len) ; 127 | memset(buffer, '\0', len) ; 128 | memcpy((unsigned char *)buffer, &(myInfo->location), 4) ; 129 | memcpy((unsigned char *)&buffer[4], &(myInfo->portNo), 2) ; 130 | sprintf((char *)&buffer[6], "%s", host); 131 | } 132 | 133 | 134 | header[0] = 0xfc; 135 | 136 | 137 | memcpy((char *)&header[21], &(mes.ttl), 1) ; 138 | header[22] = 0x00 ; 139 | memcpy((char *)&header[23], &(len), 4) ; 140 | 141 | } 142 | else if (mes.type == 0xfb){ 143 | // printf("Sending JOIN Response..\n") ; 144 | 145 | //originated from somewhere else, just need to forward the message 146 | if (mes.status == 1){ 147 | buffer = (unsigned char *)malloc(mes.buffer_len) ; 148 | for (int i = 0 ; i < mes.buffer_len ; i++) 149 | buffer[i] = mes.buffer[i] ; 150 | len = mes.buffer_len ; 151 | } 152 | else{ 153 | //originated from here, needs to send to destinations 154 | unsigned char host[256] ; 155 | gethostname((char *)host, 256) ; 156 | host[255] = '\0' ; 157 | len = strlen((char *)host) + 26 ; 158 | buffer = (unsigned char *)malloc(len) ; 159 | memset(buffer, '\0', len) ; 160 | //memcpy(buffer, mes.uoid, 20) ; 161 | for(unsigned int i = 0;i<20;i++){ 162 | buffer[i] = mes.uoid[i]; 163 | //printf("%02x-", mes.uoid[i]) ; 164 | } 165 | //printf("\n") ; 166 | memcpy(&buffer[20], &(mes.location), 4) ; 167 | memcpy(&buffer[24], &(myInfo->portNo), 2) ; 168 | sprintf((char *)&buffer[26], "%s", host); 169 | } 170 | 171 | 172 | header[0] = 0xfb; 173 | memcpy((char *)&header[21], &(mes.ttl), 1) ; 174 | header[22] = 0x00 ; 175 | memcpy((char *)&header[23], &(len), 4) ; 176 | } 177 | else if (mes.type == 0xf8){ 178 | // printf("Sending KeepAlive request from : %d\n", (int)sockfd) ; 179 | 180 | len = 0; 181 | buffer = (unsigned char *)malloc(len) ; 182 | memset(buffer, '\0', len) ; 183 | 184 | header[0] = 0xf8; 185 | header[21]=0x01; 186 | header[22] = 0x00 ; 187 | memcpy((char *)&header[23], &(len), 4) ; 188 | 189 | } 190 | // Status Message request 191 | else if (mes.type == 0xac){ 192 | //originted from somewhere else 193 | if (mes.status == 1){ 194 | buffer = mes.buffer ; 195 | len = mes.buffer_len ; 196 | } 197 | else{ 198 | len = 1 ; 199 | buffer = (unsigned char *)malloc(len) ; 200 | memset(buffer, '\0', len) ; 201 | buffer[0] = mes.status_type ; 202 | } 203 | 204 | 205 | header[0] = 0xac; 206 | 207 | 208 | memcpy((char *)&header[21], &(mes.ttl), 1) ; 209 | header[22] = 0x00 ; 210 | memcpy((char *)&header[23], &(len), 4) ; 211 | 212 | } 213 | // Search Message request 214 | else if (mes.type == 0xec){ 215 | if (mes.status == 1){ 216 | buffer = mes.buffer ; 217 | len = mes.buffer_len ; 218 | } 219 | else{ 220 | len = mes.buffer_len + 1 ; 221 | buffer = (unsigned char *)malloc(len) ; 222 | memset(buffer, '\0', len) ; 223 | buffer[0] = mes.query_type ; 224 | for (unsigned int i = 1 ; i < len ; ++i) 225 | buffer[i] = mes.query[i-1] ; 226 | } 227 | 228 | 229 | header[0] = 0xec; 230 | 231 | 232 | memcpy((char *)&header[21], &(mes.ttl), 1) ; 233 | header[22] = 0x00 ; 234 | memcpy((char *)&header[23], &(len), 4) ; 235 | 236 | } 237 | // Store Message request 238 | else if (mes.type == 0xcc){ 239 | if (mes.status == 1){ 240 | buffer = mes.buffer ; 241 | len = mes.buffer_len ; 242 | fp = fopen((char *)mes.fileName, "rb") ; 243 | if(fp==NULL){ 244 | writeLogEntry((unsigned char *)"//File to be stored could not be opened\n") ; 245 | continue ; 246 | } 247 | stat((char *)mes.fileName, &st) ; 248 | len += st.st_size ; 249 | mes.status = 3 ; 250 | } 251 | else{ 252 | // printf("Sending store request\n") ; 253 | fp = fopen((char *)mes.fileName, "rb") ; 254 | if(fp==NULL){ 255 | writeLogEntry((unsigned char *)"//File to be stored could not be opened\n") ; 256 | continue ; 257 | } 258 | stat((char *)mes.fileName, &st) ; 259 | string metaStr((char *)mes.metadata) ; 260 | uint32_t templen = metaStr.size() ; 261 | len = 4 + templen ; 262 | buffer = (unsigned char *)malloc(len ) ; 263 | memset(buffer, '\0', len) ; 264 | memcpy(&buffer[0], &templen, 4) ; 265 | for (unsigned int i = 0 ; i < templen ; ++i) 266 | buffer[i+4] = metaStr[i] ; 267 | len += st.st_size ; 268 | } 269 | 270 | 271 | header[0] = 0xcc; 272 | 273 | 274 | memcpy((char *)&header[21], &(mes.ttl), 1) ; 275 | header[22] = 0x00 ; 276 | memcpy((char *)&header[23], &(len), 4) ; 277 | 278 | } 279 | // Get Message response 280 | else if (mes.type == 0xdb){ 281 | if (mes.status == 1){ 282 | buffer = mes.buffer ; 283 | len = mes.buffer_len ; 284 | fp = fopen((char *)mes.fileName, "rb") ; 285 | if(fp==NULL){ 286 | writeLogEntry((unsigned char *)"//File to be stored could not be opened\n") ; 287 | continue ; 288 | } 289 | stat((char *)mes.fileName, &st) ; 290 | len += st.st_size ; 291 | mes.status = 3 ; 292 | } 293 | else{ 294 | // printf("Sending get response\n") ; 295 | fp = fopen((char *)mes.fileName, "rb") ; 296 | if(fp==NULL){ 297 | // printf("Filename: %s\n", mes.fileName) ; 298 | writeLogEntry((unsigned char *)"//File to be stored could not be opened\n") ; 299 | continue ; 300 | } 301 | stat((char *)mes.fileName, &st) ; 302 | string metaStr((char *)mes.metadata) ; 303 | uint32_t templen = metaStr.size() ; 304 | len = 24 + templen ; 305 | buffer = (unsigned char *)malloc(len ) ; 306 | memset(buffer, '\0', len) ; 307 | for(int i = 0 ; i < 20 ; ++i) 308 | buffer[i] = mes.uoid[i] ; 309 | memcpy(&buffer[20], &templen, 4) ; 310 | for (unsigned int i = 0 ; i < templen ; ++i) 311 | buffer[i+24] = metaStr[i] ; 312 | len += st.st_size ; 313 | } 314 | 315 | 316 | header[0] = 0xdb; 317 | 318 | 319 | memcpy((char *)&header[21], &(mes.ttl), 1) ; 320 | header[22] = 0x00 ; 321 | memcpy((char *)&header[23], &(len), 4) ; 322 | 323 | } 324 | // get Message request 325 | else if (mes.type == 0xdc){ 326 | // printf("Sending get request\n") ; 327 | if (mes.status == 1){ 328 | buffer = mes.buffer ; 329 | len = mes.buffer_len ; 330 | } 331 | else{ 332 | len = 40 ; 333 | buffer = (unsigned char *)malloc(len) ; 334 | memset(buffer, '\0', len) ; 335 | for (unsigned int i = 0 ; i < 20 ; ++i){ 336 | buffer[i] = mes.query[i] ; 337 | buffer[i+20] = mes.metadata[i] ; 338 | } 339 | } 340 | 341 | 342 | header[0] = 0xdc; 343 | 344 | 345 | memcpy((char *)&header[21], &(mes.ttl), 1) ; 346 | header[22] = 0x00 ; 347 | memcpy((char *)&header[23], &(len), 4) ; 348 | 349 | } 350 | // Delete Message request 351 | else if (mes.type == 0xbc){ 352 | // printf("Sending delete message\n") ; 353 | if (mes.status == 1){ 354 | buffer = mes.buffer ; 355 | len = mes.buffer_len ; 356 | } 357 | else{ 358 | len = mes.buffer_len ; 359 | buffer = (unsigned char *)malloc(len) ; 360 | memset(buffer, '\0', len) ; 361 | for (unsigned int i = 0 ; i < len ; ++i){ 362 | buffer[i] = mes.query[i] ; 363 | // printf("%c", buffer[i]) ; 364 | } 365 | } 366 | 367 | 368 | header[0] = 0xbc; 369 | 370 | 371 | memcpy((char *)&header[21], &(mes.ttl), 1) ; 372 | header[22] = 0x00 ; 373 | memcpy((char *)&header[23], &(len), 4) ; 374 | 375 | } 376 | // CHECK Message request 377 | else if (mes.type == 0xf6){ 378 | if (mes.status == 1){ 379 | buffer = mes.buffer ; 380 | len = mes.buffer_len ; 381 | } 382 | else{ 383 | len = 0 ; 384 | } 385 | 386 | header[0] = 0xf6; 387 | 388 | memcpy((char *)&header[21], &(mes.ttl), 1) ; 389 | header[22] = 0x00 ; 390 | memcpy((char *)&header[23], &(len), 4) ; 391 | 392 | } 393 | else if (mes.type == 0xab){ 394 | // printf("Sending Status Response..\n") ; 395 | 396 | if (mes.status == 1){ 397 | buffer = (unsigned char *)malloc(mes.buffer_len) ; 398 | for (int i = 0 ; i < mes.buffer_len ; i++) 399 | buffer[i] = mes.buffer[i] ; 400 | len = mes.buffer_len ; 401 | } 402 | else{ 403 | unsigned char host[256] ; 404 | gethostname((char *)host, 256) ; 405 | host[255] = '\0' ; 406 | unsigned int len1 = strlen((char *)host) + 24 ; 407 | buffer = (unsigned char *)malloc(len1) ; 408 | memset(buffer, 0, len1) ; 409 | //memcpy(buffer, mes.uoid, 20) ; 410 | for(unsigned int i=0;i<20;i++) 411 | buffer[i] = mes.uoid[i]; 412 | uint16_t templen = len1 - 22 ; 413 | memcpy(&buffer[20], &(templen), 2) ; 414 | memcpy(&buffer[22], &(myInfo->portNo), 2) ; 415 | for (int i = 24 ; i < (int)len1 ; ++i) 416 | buffer[i] = host[i-24] ; 417 | // sprintf((char *)&buffer[24], "%s", host); 418 | len = len1 ; 419 | 420 | if(mes.status_type == 0x01){ 421 | for(map::iterator it = nodeConnectionMap.begin(); it != nodeConnectionMap.end() ; ++it){ 422 | unsigned int len2 = strlen((char *)((*it).first.hostname)) + 2 ; 423 | len += len2+4 ; 424 | buffer = (unsigned char *)realloc(buffer, len) ; 425 | ++it ; 426 | if ( it == nodeConnectionMap.end() ){ 427 | unsigned int temlen2 = 0 ; 428 | memcpy(&buffer[len-len2-4], &(temlen2), 4); 429 | } 430 | else{ 431 | memcpy(&buffer[len-len2-4], &(len2), 4); 432 | } 433 | --it ; 434 | memcpy(&buffer[len-len2], &((*it).first.portNo ), 2) ; 435 | for (int i = len - len2 + 2 ; i < (int)len ; ++i) 436 | buffer[i] = host[i -(len-len2+2)] ; 437 | // sprintf((char *)&buffer[len-len2+2], "%s", host); 438 | } 439 | } 440 | else if(mes.status_type == 0x02){ 441 | // printf("Sending Status Files response\n") ; 442 | list tempList ; 443 | tempList = getAllFiles() ; 444 | 445 | struct metaData metadata ; 446 | string metaStr("") ; 447 | for(list::iterator it = tempList.begin(); it != tempList.end(); it++){ 448 | metadata = populateMetaData(*it) ; 449 | fileIDMap[string((char *)metadata.fileID, 20)] = (*it) ; 450 | metaStr = MetaDataToStr(metadata) ; 451 | // printf("%s\n", metaStr) ; 452 | unsigned int len2 = metaStr.size() ; 453 | len += len2+4 ; 454 | buffer = (unsigned char *)realloc(buffer, len) ; 455 | ++it ; 456 | if ( it == tempList.end() ){ 457 | unsigned int temlen2 = 0 ; 458 | memcpy(&buffer[len-len2-4], &(temlen2), 4); 459 | } 460 | else{ 461 | memcpy(&buffer[len-len2-4], &(len2), 4); 462 | } 463 | --it ; 464 | for (int i = len - len2 ; i < (int)len ; ++i) 465 | buffer[i] = metaStr[i -(len-len2)] ; 466 | } 467 | 468 | } 469 | 470 | } 471 | 472 | 473 | header[0] = 0xab; 474 | memcpy((char *)&header[21], &(mes.ttl), 1) ; 475 | header[22] = 0x00 ; 476 | memcpy((char *)&header[23], &(len), 4) ; 477 | } 478 | else if (mes.type == 0xeb){ 479 | // printf("Sending Search Response..\n") ; 480 | 481 | if (mes.status == 1){ 482 | buffer = (unsigned char *)malloc(mes.buffer_len) ; 483 | for (int i = 0 ; i < mes.buffer_len ; i++) 484 | buffer[i] = mes.buffer[i] ; 485 | len = mes.buffer_len ; 486 | } 487 | else{ 488 | // Construct the response 489 | len = 20 ; 490 | buffer = (unsigned char *)malloc(len) ; 491 | for(unsigned int i=0;i<20;i++) 492 | buffer[i] = mes.uoid[i]; 493 | list tempList ; 494 | switch(mes.query_type){ 495 | case 0x01: 496 | tempList = fileNameSearch(mes.query) ; 497 | break; 498 | case 0x02: 499 | tempList = sha1Search(mes.query) ; 500 | break ; 501 | case 0x03: 502 | tempList = keywordSearch(mes.query) ; 503 | break ; 504 | } 505 | if (tempList.size() == 0){ 506 | // printf("No records found\n") ; 507 | // free(buffer) ; 508 | continue; 509 | } 510 | struct metaData metadata ; 511 | string metaStr("") ; 512 | for(list::iterator it = tempList.begin(); it != tempList.end(); it++){ 513 | metadata = populateMetaData(*it) ; 514 | fileIDMap[string((char *)metadata.fileID, 20)] = (*it) ; 515 | metaStr = MetaDataToStr(metadata) ; 516 | uint32_t len1 = metaStr.size() ; 517 | len = len + len1 + 24 ; 518 | buffer = (unsigned char *)realloc(buffer, len) ; 519 | 520 | ++it ; 521 | if( it == tempList.end()){ 522 | uint32_t zeroLen = 0 ; 523 | memcpy(&buffer[len - len1 - 24], &zeroLen, 4) ; 524 | } 525 | else{ 526 | memcpy(&buffer[len - len1 - 24], &len1, 4) ; 527 | } 528 | --it ; 529 | // memcpy(&buffer[len - len1 - 24], &len1, 4) ; 530 | for(unsigned int h = (len-len1-20) ; h < (len - len1) ; ++h) 531 | buffer[h] = metadata.fileID[h - (len-len1-20)] ; 532 | for(unsigned int h = (len-len1) ; h < len ; ++h){ 533 | buffer[h] = metaStr[h-len+len1] ; 534 | // printf("%c", buffer[h]) ; 535 | } 536 | // memcpy(&buffer[len-24], metaStr.c_str(), len1) ; 537 | } 538 | 539 | 540 | } 541 | 542 | 543 | header[0] = 0xeb; 544 | memcpy((char *)&header[21], &(mes.ttl), 1) ; 545 | header[22] = 0x00 ; 546 | memcpy((char *)&header[23], &(len), 4) ; 547 | } 548 | else if (mes.type == 0xf5){ 549 | // printf("Sending CHECK Response..\n") ; 550 | 551 | if (mes.status == 1){ 552 | buffer = (unsigned char *)malloc(mes.buffer_len) ; 553 | for (int i = 0 ; i < mes.buffer_len ; i++) 554 | buffer[i] = mes.buffer[i] ; 555 | len = mes.buffer_len ; 556 | } 557 | else{ 558 | unsigned int len1 = 20 ; 559 | 560 | buffer = (unsigned char *)malloc(len1) ; 561 | memset(buffer, 0, len1) ; 562 | 563 | for (int i = 0 ; i < SHA_DIGEST_LENGTH ; ++i) 564 | buffer[i] = mes.uoid[i] ; 565 | // memcpy(buffer, mes.uoid, 20) ; 566 | 567 | len = len1 ; 568 | 569 | } 570 | 571 | header[0] = 0xf5; 572 | memcpy((char *)&header[21], &(mes.ttl), 1) ; 573 | header[22] = 0x00 ; 574 | memcpy((char *)&header[23], &(len), 4) ; 575 | } 576 | else if (mes.type == 0xf7) 577 | { 578 | // printf("Sending Notify message\n"); 579 | len = 1; 580 | buffer = (unsigned char *)malloc(len) ; 581 | memset(buffer, '\0', len) ; 582 | //memcpy(buffer, &mes.errorCode, sizeof(mes.errorCode)); 583 | buffer[0]=mes.errorCode; 584 | 585 | header[0] = 0xf7; 586 | 587 | header[21] = 0x01 ; 588 | memcpy((char *)&header[23], &(len), 4) ; 589 | } 590 | 591 | //KeepAlive message sending 592 | //Resst the keepAliveTimer for this connection 593 | if(connectionMap.find(sockfd)!=connectionMap.end()) 594 | { 595 | pthread_mutex_lock(&connectionMapLock) ; 596 | connectionMap[sockfd].keepAliveTimer = myInfo->keepAliveTimeOut/2; 597 | pthread_mutex_unlock(&connectionMapLock) ; 598 | } 599 | 600 | int return_code = 0 ; 601 | return_code = (int)write(sockfd, header, HEADER_SIZE) ; 602 | if (return_code != HEADER_SIZE){ 603 | //fprintf(stderr, "Socket Write Error") ; 604 | } 605 | 606 | if(mes.status == 3){ 607 | write(sockfd, buffer, len - st.st_size) ; 608 | unsigned char chunk[8192] ; 609 | // read the content of the file and write on the socket 610 | //while(!feof(fp)){ 611 | while(1){ 612 | memset(chunk, '\0' , 8192) ; 613 | int numBytes = fread(chunk, 1, 8192, fp) ; 614 | if(numBytes == 0) 615 | break; 616 | write(sockfd, chunk, numBytes) ; 617 | } 618 | } 619 | else{ 620 | return_code = (int)write(sockfd, buffer, len) ; 621 | if (return_code != (int)len){ 622 | // fprintf(stderr, "Socket Write Error") ; 623 | } 624 | } 625 | 626 | 627 | 628 | //logging the message sent from this node or forwarded from this node 629 | unsigned char *logEntry = NULL; 630 | if(!(mes.type == 0xfa && (inJoinNetwork || connectionMap[sockfd].joinFlag == 1))) 631 | { 632 | pthread_mutex_lock(&logEntryLock) ; 633 | if(mes.status== 0 || mes.status == 2 ) 634 | logEntry = createLogEntry('s', sockfd, header, buffer); 635 | else 636 | logEntry = createLogEntry('f', sockfd, header, buffer); 637 | 638 | if(logEntry!=NULL) 639 | writeLogEntry(logEntry); 640 | pthread_mutex_unlock(&logEntryLock) ; 641 | } 642 | 643 | free(buffer) ; 644 | 645 | } 646 | 647 | // printf("Write Thread exiting...\n") ; 648 | 649 | pthread_exit(0); 650 | return 0; 651 | } 652 | 653 | 654 | int connectTo(unsigned char *hostName, unsigned int portN ) { 655 | 656 | struct sockaddr_in serv_addr ; 657 | struct hostent *host ; 658 | int nSocket = 0, status; 659 | 660 | host = gethostbyname(const_cast ((char *)hostName)) ; 661 | if (host == NULL){ 662 | //fprintf(stderr, "Unknown host\n") ; 663 | return -1 ; 664 | } 665 | 666 | 667 | // Creating the new server 668 | nSocket = socket(AF_INET, SOCK_STREAM,0) ; 669 | 670 | // Initialising the structure with 0 671 | memset(&serv_addr,0, sizeof(struct sockaddr_in)) ; 672 | 673 | // Filling up the structure with specifics 674 | serv_addr.sin_family = AF_INET ; 675 | serv_addr.sin_addr = *((struct in_addr *)host->h_addr); 676 | serv_addr.sin_port = htons(portN) ; 677 | 678 | // Connect to the server 679 | status = connect(nSocket, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) ; 680 | if (status < 0){ 681 | //perror("Connect") ; 682 | return -1 ; 683 | } 684 | else { 685 | return nSocket ; 686 | 687 | } 688 | 689 | } 690 | 691 | 692 | //get the UOID of the messages 693 | unsigned char *GetUOID(char *obj_type, unsigned char *uoid_buf, long unsigned int uoid_buf_sz){ 694 | static unsigned long seq_no=(unsigned long)1; 695 | unsigned char sha1_buf[SHA_DIGEST_LENGTH], str_buf[104]; 696 | 697 | snprintf((char *)str_buf, sizeof(str_buf), "%s_%s_%1ld", myInfo->node_instance_id, obj_type, (long)seq_no++); 698 | SHA1(str_buf, strlen((const char *)str_buf), sha1_buf); 699 | memset(uoid_buf, 0, uoid_buf_sz); 700 | memcpy(uoid_buf, sha1_buf,min(uoid_buf_sz,sizeof(sha1_buf))); 701 | return uoid_buf; 702 | } 703 | 704 | 705 | 706 | // Method to join the network 707 | // Case when then init_neighbor file is not present 708 | void joinNetwork(){ 709 | // printf("In join network method\n") ; 710 | int resSock = -1 ; 711 | pthread_t re_thread ; 712 | void *thread_result ; 713 | 714 | for(list::iterator it = myInfo->myBeaconList->begin(); it != myInfo->myBeaconList->end(); it++){ 715 | // printf("Trying to connect to %s:%d\n", (*it)->hostName, (*it)->portNo) ; 716 | resSock = connectTo((*it)->hostName, (*it)->portNo) ; 717 | if (resSock == -1 ){ 718 | // Connection could not be established 719 | } 720 | else{ 721 | struct connectionNode cn ; 722 | struct node n; 723 | n.portNo = (*it)->portNo ; 724 | //strcpy(n.hostname, (const char *)(*it)->hostName) ; 725 | for(unsigned int i =0 ;ihostName);i++) 726 | n.hostname[i] = (*it)->hostName[i]; 727 | n.hostname[strlen((const char *)(*it)->hostName)] = '\0'; 728 | // nodeConnectionMap[n] = resSock ; 729 | 730 | int mres = pthread_mutex_init(&cn.mesQLock, NULL) ; 731 | if (mres != 0){ 732 | //perror("Mutex initialization failed"); 733 | writeLogEntry((unsigned char *)"//Mutex initialization failed\n"); 734 | 735 | } 736 | int cres = pthread_cond_init(&cn.mesQCv, NULL) ; 737 | if (cres != 0){ 738 | //perror("CV initialization failed") ; 739 | writeLogEntry((unsigned char *)"//CV initialization failed\n"); 740 | } 741 | 742 | cn.shutDown = 0 ; 743 | cn.n = n; 744 | pthread_mutex_lock(&connectionMapLock) ; 745 | connectionMap[resSock] = cn ; 746 | pthread_mutex_unlock(&connectionMapLock) ; 747 | // Push a Join Req type message in the writing queue 748 | struct Message m ; 749 | m.type = 0xfc ; 750 | m.status = 0 ; 751 | m.ttl = myInfo->ttl ; 752 | pushMessageinQ(resSock, m) ; 753 | 754 | // Create a read thread for this connection 755 | int res = pthread_create(&re_thread, NULL, read_thread , (void *)resSock); 756 | if (res != 0) { 757 | //perror("Thread creation failed"); 758 | writeLogEntry((unsigned char *)"//In Join Network: Read Thread Creation Failed\n"); 759 | exit(EXIT_FAILURE); 760 | } 761 | childThreadList.push_front(re_thread); 762 | // Create a write thread 763 | pthread_t wr_thread ; 764 | res = pthread_create(&wr_thread, NULL, write_thread , (void *)resSock); 765 | if (res != 0) { 766 | //perror("Thread creation failed"); 767 | writeLogEntry((unsigned char *)"//In Join Network: Write Thread Creation Failed\n"); 768 | exit(EXIT_FAILURE); 769 | } 770 | childThreadList.push_front(wr_thread); 771 | break ; 772 | } 773 | } 774 | 775 | if (resSock == -1){ 776 | //fprintf(stderr,"No Beacon node up\n") ; 777 | writeLogEntry((unsigned char *)"//NO Beacon Node is up, shuting down\n"); 778 | exit(0) ; 779 | } 780 | int res; 781 | // Call the timer thread 782 | // Thread creation and join code taken from WROX Publications book 783 | pthread_t t_thread ; 784 | res = pthread_create(&t_thread, NULL, timer_thread , (void *)NULL); 785 | if (res != 0) { 786 | //perror("Thread creation failed"); 787 | writeLogEntry((unsigned char *)"//In Join Network: Timer Thread Creation Failed\n"); 788 | exit(EXIT_FAILURE); 789 | } 790 | childThreadList.push_front(t_thread); 791 | 792 | // Join the read thread here 793 | // Thread Join code taken from WROX Publications 794 | for (list::iterator it = childThreadList.begin(); it != childThreadList.end(); ++it){ 795 | //printf("Value is : %d\n", (pthread_t)(*it).second.myReadId); 796 | int res = pthread_join((*it), &thread_result); 797 | if (res != 0) { 798 | //perror("Thread join failed"); 799 | writeLogEntry((unsigned char *)"//In Join Network: Thread Joining Failed\n"); 800 | exit(EXIT_FAILURE); 801 | } 802 | } 803 | 804 | 805 | joinTimeOutFlag = 0; 806 | // printf("Join process exiting..\n") ; 807 | 808 | // Sort the output and write them in the file 809 | //FILE *fp = fopen("init_neighbor_list", "w") ; 810 | FILE *fp = fopen((char *)tempInitFile, "w"); 811 | //FILE *fp = fopen("init_neighbor_list", "w"); 812 | if (fp==NULL){ 813 | //fprintf(stderr, "Error in file open") ; 814 | writeLogEntry((unsigned char *)"//In Join Network: Failed to open Init_Neighbor_list file\n"); 815 | exit(EXIT_FAILURE); 816 | } 817 | unsigned char tempPort[10] ; 818 | if (joinResponse.size() < myInfo->initNeighbor){ 819 | //if (joinResponse.size() < 1){ 820 | //fprintf(stderr, "Failed to locate minimum number of nodes\n") ; 821 | writeLogEntry((unsigned char *)"//Failed to locate Init Neighbor number of nodes\n"); 822 | fclose(f_log); 823 | exit(0) ; 824 | } 825 | unsigned int counter = 0; 826 | for (set::iterator it = joinResponse.begin(); it != joinResponse.end() ; it++, counter++){ 827 | 828 | if(counter==myInfo->minNeighbor) 829 | break; 830 | 831 | //printf("Hostname: %s, Port: %d, location: %d\n", (*it).hostname, (*it).portNo, (*it).location) ; 832 | fputs((char *)(*it).hostname , fp) ; 833 | fputs(":", fp) ; 834 | sprintf((char *)tempPort, "%d", (*it).portNo) ; 835 | fputs((char *)tempPort, fp) ; 836 | fputs("\n", fp) ; 837 | 838 | } 839 | fflush(fp) ; 840 | fclose(fp) ; 841 | pthread_mutex_lock(&nodeConnectionMapLock) ; 842 | nodeConnectionMap.erase(nodeConnectionMap.begin(), nodeConnectionMap.end()) ; 843 | pthread_mutex_unlock(&nodeConnectionMapLock) ; 844 | childThreadList.clear(); 845 | } 846 | 847 | 848 | // Method to flood the status requests 849 | void getStatus(){ 850 | 851 | unsigned char uoid[SHA_DIGEST_LENGTH] ; 852 | GetUOID( const_cast ("msg"), uoid, sizeof(uoid)) ; 853 | // memcpy((char *)&header[1], uoid, 20) ; 854 | 855 | 856 | struct Packet pk; 857 | pk.status = 0 ; 858 | pk.msgLifeTime = myInfo->msgLifeTime; 859 | pk.status_type = 0x01 ; 860 | 861 | 862 | pthread_mutex_lock(&MessageDBLock) ; 863 | MessageDB[string((const char *)uoid, SHA_DIGEST_LENGTH) ] = pk ; 864 | pthread_mutex_unlock(&MessageDBLock) ; 865 | 866 | //sending the status request message to all of it's neighbor 867 | pthread_mutex_lock(&nodeConnectionMapLock) ; 868 | for(map::iterator it = nodeConnectionMap.begin(); it != nodeConnectionMap.end() ; ++it){ 869 | struct Message m ; 870 | m.type = 0xac ; 871 | m.status = 2 ; 872 | m.ttl = myInfo->ttl ; 873 | m.status_type = 0x01 ; 874 | for (int i=0 ; i < SHA_DIGEST_LENGTH ; i++) 875 | m.uoid[i] = uoid[i] ; 876 | pushMessageinQ( (*it).second, m) ; 877 | } 878 | pthread_mutex_unlock(&nodeConnectionMapLock) ; 879 | 880 | } 881 | 882 | 883 | // Method to initiate the CHECK message 884 | // The methid is invoked when one of the node's 885 | // neighbor dies 886 | void initiateCheck(){ 887 | 888 | unsigned char uoid[SHA_DIGEST_LENGTH] ; 889 | GetUOID( const_cast ("msg"), uoid, sizeof(uoid)) ; 890 | 891 | struct Packet pk; 892 | pk.status = 0 ; 893 | pk.msgLifeTime = myInfo->msgLifeTime; 894 | 895 | 896 | pthread_mutex_lock(&MessageDBLock) ; 897 | MessageDB[string((const char *)uoid, SHA_DIGEST_LENGTH) ] = pk ; 898 | pthread_mutex_unlock(&MessageDBLock) ; 899 | 900 | // myInfo->checkResponseTimeout = myInfo->joinTimeOut ; 901 | 902 | 903 | //printf("here1\n") ; 904 | // pthread_mutex_lock(&nodeConnectionMapLock) ; 905 | //printf("here2\n") ; 906 | for(map::iterator it = nodeConnectionMap.begin(); it != nodeConnectionMap.end() ; ++it){ 907 | //printf("here3\n") ; 908 | struct Message m ; 909 | m.type = 0xf6 ; 910 | m.status = 2 ; 911 | m.ttl = myInfo->ttl ; 912 | for (int i=0 ; i < SHA_DIGEST_LENGTH ; i++) 913 | m.uoid[i] = uoid[i] ; 914 | pushMessageinQ( (*it).second, m) ; 915 | } 916 | // pthread_mutex_unlock(&nodeConnectionMapLock) ; 917 | checkTimerFlag = 1 ; 918 | 919 | } 920 | 921 | 922 | void initiateSearch(unsigned char type, unsigned char *value){ 923 | unsigned char uoid[SHA_DIGEST_LENGTH] ; 924 | GetUOID( const_cast ("msg"), uoid, sizeof(uoid)) ; 925 | 926 | searchTimerFlag = 1 ; 927 | 928 | // Clear the search response MAP 929 | getFileIDMap.clear() ; 930 | 931 | // Reset the counter 932 | globalSearchCount = 1 ; 933 | 934 | 935 | struct Packet pk; 936 | pk.status = 0 ; 937 | pk.msgLifeTime = myInfo->msgLifeTime; 938 | 939 | // Insert the search response of this node(own) 940 | list tempList ; 941 | switch(type){ 942 | case 0x01: 943 | tempList = fileNameSearch(value) ; 944 | break; 945 | case 0x02: 946 | tempList = sha1Search(value) ; 947 | break ; 948 | case 0x03: 949 | tempList = keywordSearch(value) ; 950 | break ; 951 | } 952 | list searchRes ; 953 | for(list::iterator it = tempList.begin(); it != tempList.end(); it++){ 954 | struct metaData metadata = populateMetaData(*it) ; 955 | fileIDMap[string((char *)metadata.fileID, 20)] = (*it) ; 956 | searchRes.push_front(metadata) ; 957 | } 958 | globalSearchCount = searchResponseDisplay(searchRes, globalSearchCount) ; 959 | 960 | 961 | pthread_mutex_lock(&MessageDBLock) ; 962 | MessageDB[string((const char *)uoid, SHA_DIGEST_LENGTH) ] = pk ; 963 | pthread_mutex_unlock(&MessageDBLock) ; 964 | 965 | //sending the status request message to all of it's neighbors 966 | pthread_mutex_lock(&nodeConnectionMapLock) ; 967 | for(map::iterator it = nodeConnectionMap.begin(); it != nodeConnectionMap.end() ; ++it){ 968 | struct Message m ; 969 | m.type = 0xec ; 970 | m.status = 2 ; 971 | m.ttl = myInfo->ttl ; 972 | m.query_type = type ; 973 | m.buffer_len = strlen((char *)value) ; 974 | m.query = (unsigned char *)malloc(m.buffer_len) ; 975 | for(int l = 0 ; l < m.buffer_len; ++l) 976 | m.query[l] = value[l] ; 977 | for (int i=0 ; i < SHA_DIGEST_LENGTH ; i++) 978 | m.uoid[i] = uoid[i] ; 979 | pushMessageinQ( (*it).second, m) ; 980 | } 981 | pthread_mutex_unlock(&nodeConnectionMapLock) ; 982 | 983 | 984 | } 985 | 986 | 987 | 988 | 989 | //Writing the status response to the file, creating the nam file 990 | void writeToStatusFile(){ 991 | // printf("Writing to the file\n") ; 992 | pthread_mutex_lock(&statusMsgLock) ; 993 | FILE *fp = fopen((char *)myInfo->status_file, "a") ; 994 | if (fp == NULL){ 995 | //fprintf(stderr, "File open failed\n") ; 996 | writeLogEntry((unsigned char *)"//Failed to open STATUS FILE\n"); 997 | exit(0) ; 998 | } 999 | 1000 | set distinctNodes ; 1001 | set::iterator it1 ; 1002 | 1003 | for (set< set >::iterator it = statusResponse.begin(); it != statusResponse.end() ; ++it){ 1004 | it1 = (*it).begin() ; 1005 | distinctNodes.insert( *it1 ) ; 1006 | ++it1 ; 1007 | distinctNodes.insert( *it1 ) ; 1008 | } 1009 | 1010 | if(distinctNodes.size() == 0) 1011 | { 1012 | fputs("n -t * -s ", fp) ; 1013 | 1014 | unsigned char portS[20] ; 1015 | sprintf((char *)portS, "%d", myInfo->portNo) ; 1016 | fputs((char *)portS, fp) ; 1017 | //Beacon node is represnted by BLUE NODES 1018 | if (myInfo->isBeacon){ 1019 | fputs(" -c blue -i blue\n", fp) ; 1020 | } 1021 | //NON-Beacon ndoe is represented by BLACK nodes 1022 | else{ 1023 | fputs(" -c black -i black\n", fp) ; 1024 | } 1025 | } 1026 | 1027 | for (set< struct node >::iterator it = distinctNodes.begin(); it != distinctNodes.end() ; ++it){ 1028 | fputs("n -t * -s ", fp) ; 1029 | unsigned char portS[20] ; 1030 | sprintf((char *)portS, "%d", (*it).portNo) ; 1031 | fputs((char *)portS, fp) ; 1032 | //Beacon node is represnted by BLUE NODES 1033 | if (isBeaconNode(*it) ){ 1034 | fputs(" -c blue -i blue\n", fp) ; 1035 | } 1036 | else{ 1037 | //NON-Beacon node is represnted by BLACK NODES 1038 | fputs(" -c black -i black\n", fp) ; 1039 | } 1040 | } 1041 | 1042 | for (set< set >::iterator it = statusResponse.begin(); it != statusResponse.end() ; ++it){ 1043 | fputs("l -t * -s ", fp) ; 1044 | struct node n1; 1045 | struct node n2; 1046 | it1 = (*it).begin() ; 1047 | n1 = *it1 ; 1048 | ++it1 ; 1049 | n2 = *it1 ; 1050 | 1051 | unsigned char portS[20] ; 1052 | sprintf((char *) portS, "%d", n1.portNo) ; 1053 | fputs((char *)portS, fp) ; 1054 | fputs(" -d ", fp) ; 1055 | 1056 | memset(portS, '\0', 20) ; 1057 | sprintf((char *)portS, "%d", n2.portNo) ; 1058 | fputs((char *)portS, fp) ; 1059 | 1060 | 1061 | if (isBeaconNode(n1) && isBeaconNode(n2) ){ 1062 | fputs(" -c blue\n", fp) ; 1063 | } 1064 | else{ 1065 | fputs(" -c black\n", fp) ; 1066 | } 1067 | } 1068 | 1069 | 1070 | 1071 | fflush(fp) ; 1072 | fclose(fp) ; 1073 | statusResponse.erase( statusResponse.begin(), statusResponse.end()) ; 1074 | pthread_mutex_unlock(&statusMsgLock) ; 1075 | // printf("status file written\n") ; 1076 | } 1077 | 1078 | 1079 | void getStatusTypeFiles(){ 1080 | 1081 | unsigned char uoid[SHA_DIGEST_LENGTH] ; 1082 | GetUOID( const_cast ("msg"), uoid, sizeof(uoid)) ; 1083 | 1084 | 1085 | struct Packet pk; 1086 | pk.status = 0 ; 1087 | pk.msgLifeTime = myInfo->msgLifeTime; 1088 | pk.status_type = 0x02 ; 1089 | 1090 | 1091 | pthread_mutex_lock(&MessageDBLock) ; 1092 | MessageDB[string((const char *)uoid, SHA_DIGEST_LENGTH) ] = pk ; 1093 | pthread_mutex_unlock(&MessageDBLock) ; 1094 | 1095 | //sending the status request message to all of it's neighbor 1096 | pthread_mutex_lock(&nodeConnectionMapLock) ; 1097 | for(map::iterator it = nodeConnectionMap.begin(); it != nodeConnectionMap.end() ; ++it){ 1098 | struct Message m ; 1099 | m.type = 0xac ; 1100 | m.status = 2 ; 1101 | m.ttl = myInfo->status_ttl ; 1102 | m.status_type = 0x02 ; 1103 | for (int i=0 ; i < SHA_DIGEST_LENGTH ; i++) 1104 | m.uoid[i] = uoid[i] ; 1105 | pushMessageinQ( (*it).second, m) ; 1106 | } 1107 | pthread_mutex_unlock(&nodeConnectionMapLock) ; 1108 | 1109 | } 1110 | 1111 | //Writing the status response to the file, creating the nam file 1112 | void writeToStatusFile_TypeFiles(){ 1113 | // printf("Writing to the file\n") ; 1114 | pthread_mutex_lock(&statusMsgLock) ; 1115 | FILE *fp = fopen((char *)myInfo->status_file, "a") ; 1116 | if (fp == NULL){ 1117 | //fprintf(stderr, "File open failed\n") ; 1118 | writeLogEntry((unsigned char *)"//Failed to open STATUS FILE\n"); 1119 | exit(0) ; 1120 | } 1121 | 1122 | // Insert its own record in the map 1123 | struct node own ; 1124 | own.portNo = myInfo->portNo ; 1125 | for (int h = 0 ; h < 256 ; ++h) 1126 | own.hostname[h] = myInfo->hostName[h] ; 1127 | list tempList ; 1128 | tempList = getAllFiles() ; 1129 | 1130 | struct metaData metadata ; 1131 | string metaStr("") ; 1132 | statusResponseTypeFiles[own] ; 1133 | for(list::iterator it = tempList.begin(); it != tempList.end(); it++){ 1134 | metadata = populateMetaData(*it) ; 1135 | fileIDMap[string((char *)metadata.fileID, 20)] = (*it) ; 1136 | 1137 | /*printf("Before metadatatostr:\n\n"); 1138 | for(int i=0;i<20;i++) 1139 | { 1140 | printf("%02x", metadata.sha1[i]); 1141 | } 1142 | printf("After metadatatostr:\n\n");*/ 1143 | metaStr = MetaDataToStr(metadata) ; 1144 | statusResponseTypeFiles[own].push_front(metaStr) ; 1145 | //cout<<"String came from is: "< >::iterator it = statusResponseTypeFiles.begin(); it != statusResponseTypeFiles.end() ; ++it){ 1151 | if( (*it).second.size() == 0) 1152 | fprintf(fp, "%s:%d has no file\n", (*it).first.hostname, (*it).first.portNo) ; 1153 | else if( (*it).second.size() == 1) 1154 | fprintf(fp, "%s:%d has 1 file\n", (*it).first.hostname, (*it).first.portNo) ; 1155 | else 1156 | fprintf(fp, "%s:%d has %d files\n", (*it).first.hostname, (*it).first.portNo, (int)(*it).second.size()) ; 1157 | 1158 | for(list::iterator it1 = (*it).second.begin(); it1 != (*it).second.end() ; ++it1){ 1159 | fputs((*it1).c_str(), fp) ; 1160 | fputs("\n", fp) ; 1161 | } 1162 | 1163 | 1164 | } 1165 | 1166 | 1167 | 1168 | 1169 | 1170 | fflush(fp) ; 1171 | fclose(fp) ; 1172 | statusResponseTypeFiles.clear() ; 1173 | pthread_mutex_unlock(&statusMsgLock) ; 1174 | // printf("status file written\n") ; 1175 | } 1176 | 1177 | 1178 | void initiateDelete(unsigned char *message){ 1179 | unsigned char uoid[SHA_DIGEST_LENGTH] ; 1180 | GetUOID( const_cast ("msg"), uoid, sizeof(uoid)) ; 1181 | 1182 | 1183 | struct Packet pk; 1184 | pk.status = 0 ; 1185 | pk.msgLifeTime = myInfo->msgLifeTime; 1186 | 1187 | 1188 | pthread_mutex_lock(&MessageDBLock) ; 1189 | MessageDB[string((const char *)uoid, SHA_DIGEST_LENGTH) ] = pk ; 1190 | pthread_mutex_unlock(&MessageDBLock) ; 1191 | 1192 | //sending the status request message to all of it's neighbor 1193 | pthread_mutex_lock(&nodeConnectionMapLock) ; 1194 | for(map::iterator it = nodeConnectionMap.begin(); it != nodeConnectionMap.end() ; ++it){ 1195 | struct Message m ; 1196 | m.type = 0xbc ; 1197 | m.status = 2 ; 1198 | m.ttl = myInfo->ttl ; 1199 | m.buffer_len = strlen((char *)message) ; 1200 | m.query = (unsigned char *)malloc(m.buffer_len); 1201 | for (int i = 0 ; i < m.buffer_len ; ++i){ 1202 | m.query[i] = message[i] ; 1203 | } 1204 | 1205 | for (int i=0 ; i < SHA_DIGEST_LENGTH ; i++) 1206 | m.uoid[i] = uoid[i] ; 1207 | pushMessageinQ( (*it).second, m) ; 1208 | } 1209 | pthread_mutex_unlock(&nodeConnectionMapLock) ; 1210 | 1211 | } 1212 | 1213 | void initiateStore(string metadata, string fileName){ 1214 | // printf("Initiating store method\n") ; 1215 | unsigned char uoid[SHA_DIGEST_LENGTH] ; 1216 | GetUOID( const_cast ("msg"), uoid, sizeof(uoid)) ; 1217 | 1218 | struct Packet pk; 1219 | pk.status = 0 ; 1220 | pk.msgLifeTime = myInfo->msgLifeTime; 1221 | 1222 | 1223 | pthread_mutex_lock(&MessageDBLock) ; 1224 | MessageDB[string((const char *)uoid, SHA_DIGEST_LENGTH) ] = pk ; 1225 | pthread_mutex_unlock(&MessageDBLock) ; 1226 | 1227 | //sending the store message to all of it's neighbor 1228 | pthread_mutex_lock(&nodeConnectionMapLock) ; 1229 | for(map::iterator it = nodeConnectionMap.begin(); it != nodeConnectionMap.end() ; ++it){ 1230 | if((double)drand48() <= myInfo->neighborStoreProb){ 1231 | struct Message m ; 1232 | m.type = 0xcc ; 1233 | m.status = 3 ; 1234 | m.ttl = myInfo->status_ttl ; 1235 | m.metadata = (unsigned char *)malloc(metadata.size()+1) ; 1236 | strncpy((char *)m.metadata, metadata.c_str(), metadata.size()) ; 1237 | m.metadata[metadata.size()] = '\0' ; 1238 | 1239 | m.fileName = (unsigned char *)malloc(fileName.size()+1) ; 1240 | strncpy((char *)m.fileName, fileName.c_str(), fileName.size()) ; 1241 | m.fileName[fileName.size()] = '\0' ; 1242 | 1243 | 1244 | for (int i=0 ; i < SHA_DIGEST_LENGTH ; i++) 1245 | m.uoid[i] = uoid[i] ; 1246 | pushMessageinQ( (*it).second, m) ; 1247 | 1248 | } 1249 | } 1250 | pthread_mutex_unlock(&nodeConnectionMapLock) ; 1251 | 1252 | } 1253 | 1254 | void initiateGet(struct metaData metadata){ 1255 | // printf("Initiating get method\n") ; 1256 | unsigned char uoid[SHA_DIGEST_LENGTH] ; 1257 | GetUOID( const_cast ("msg"), uoid, sizeof(uoid)) ; 1258 | 1259 | 1260 | struct Packet pk; 1261 | pk.status = 0 ; 1262 | pk.msgLifeTime = myInfo->getMsgLifeTime; 1263 | 1264 | 1265 | pthread_mutex_lock(&MessageDBLock) ; 1266 | MessageDB[string((const char *)uoid, SHA_DIGEST_LENGTH) ] = pk ; 1267 | pthread_mutex_unlock(&MessageDBLock) ; 1268 | 1269 | //sending the store message to all of it's neighbor 1270 | pthread_mutex_lock(&nodeConnectionMapLock) ; 1271 | for(map::iterator it = nodeConnectionMap.begin(); it != nodeConnectionMap.end() ; ++it){ 1272 | struct Message m ; 1273 | m.type = 0xdc ; 1274 | m.status = 2 ; 1275 | m.ttl = myInfo->status_ttl ; 1276 | m.metadata = (unsigned char *)malloc(20) ; 1277 | m.query = (unsigned char *)malloc(20) ; 1278 | for(int i = 0 ; i < 20 ; ++i){ 1279 | m.metadata[i] = metadata.sha1[i] ; 1280 | m.query[i] = metadata.fileID[i] ; 1281 | } 1282 | 1283 | 1284 | 1285 | for (int i=0 ; i < SHA_DIGEST_LENGTH ; i++) 1286 | m.uoid[i] = uoid[i] ; 1287 | pushMessageinQ( (*it).second, m) ; 1288 | } 1289 | pthread_mutex_unlock(&nodeConnectionMapLock) ; 1290 | 1291 | 1292 | } 1293 | -------------------------------------------------------------------------------- /signalHandler.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | #include "main.h" 7 | #include "iniParser.h" 8 | #include "signalHandler.h" 9 | /* Signal Handler */ 10 | void my_handler(int nSig) 11 | { 12 | //Checks the signal 13 | if (nSig == SIGUSR1) { 14 | //printf("Signal Handling Success!!!!!\n"); 15 | //Indicates the Join timeout 16 | if(myInfo->joinTimeOut == 0) 17 | { 18 | joinTimeOutFlag = 1; 19 | 20 | closeConnection( (*nodeConnectionMap.begin()).second ) ; 21 | myInfo->joinTimeOut--; 22 | } 23 | // if(shutDown) 24 | 25 | //pthread_exit(0); 26 | } 27 | 28 | if (nSig == SIGUSR2) { 29 | //closeConnection(toBeClosed); 30 | //pthread_exit(0); 31 | } 32 | //signal for shutdown 33 | if(nSig == SIGTERM) 34 | { 35 | shutDown = 1; 36 | pthread_mutex_lock(&nodeConnectionMapLock) ; 37 | for (map::iterator it = nodeConnectionMap.begin(); it != nodeConnectionMap.end(); ++it) 38 | closeConnection((*it).second); 39 | //nodeConnectionMap.clear(); 40 | pthread_mutex_unlock(&nodeConnectionMapLock) ; 41 | 42 | shutdown(nSocket_accept, SHUT_RDWR); 43 | close(nSocket_accept); 44 | pthread_kill(k_thread, SIGUSR2); 45 | for(list::iterator it = tmpFileNameList.begin(); it != tmpFileNameList.end() ; ++it){ 46 | remove((*it).c_str()) ; 47 | // printf("%s\n", (*it).c_str()) ; 48 | } 49 | 50 | /*if(myInfo->isBeacon) 51 | { 52 | for (map::iterator it = myConnectThread.begin(); it != myConnectThread.end(); ++it) 53 | { 54 | if((*it).second) 55 | pthread_kill((*it).first, SIGUSR2); 56 | } 57 | }*/ 58 | 59 | } 60 | if(nSig == SIGALRM) 61 | { 62 | pthread_exit(0); 63 | } 64 | //signal handling of ctrl+c 65 | if(nSig == SIGINT) 66 | { 67 | pthread_mutex_lock(&statusMsgLock) ; 68 | if(statusTimerFlag) 69 | myInfo->statusResponseTimeout = 0; 70 | pthread_mutex_unlock(&statusMsgLock) ; 71 | pthread_mutex_lock(&searchMsgLock) ; 72 | searchTimerFlag = 0 ; 73 | pthread_cond_signal(&searchMsgCV) ; 74 | pthread_mutex_unlock(&searchMsgLock) ; 75 | } 76 | 77 | } 78 | 79 | -------------------------------------------------------------------------------- /signalHandler.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | extern void my_handler(int nSig); 7 | -------------------------------------------------------------------------------- /startnode.ini: -------------------------------------------------------------------------------- 1 | [init] 2 | Port=12312 3 | Location=3134382376 4 | HomeDir=" /yourhome/servant/12312 k" 5 | LogFilename=servant.log 6 | AutoShutdown = 60 7 | TTL=255 8 | MsgLifetime=60 9 | GetMsgLifetime=600 10 | InitNeighbors=3 11 | JoinTimeout=5 12 | KeepAliveTimeout=7 13 | MinNeighbors=2 14 | CacheProb=0.5 15 | StoreProb=0.5 16 | NeighborStoreProb=0.5 17 | 18 | [init] 19 | Port=8182 20 | Location=123456789 21 | HomeDir="/1075/exposition/12312 k" 22 | CacheSize=1000 23 | 24 | [beacons] 25 | Retry=3 26 | foo.usc.edu:12311= 27 | foo.usc.edu:12312= 28 | foo.usc.edu:12313= 29 | foo.usc.edu:12314= 30 | -------------------------------------------------------------------------------- /statusResponseTimeout: -------------------------------------------------------------------------------- 1 | connectBeacon.cc:58: cn.keepAliveTimer = myInfo->keepAliveTimeOut/2; 2 | connectBeacon.cc:59: cn.keepAliveTimeOut = myInfo->keepAliveTimeOut; 3 | connectBeacon.cc:121: sleep(myInfo->retry) ; 4 | incoming_connections.cc:13: sprintf(sfn, "%s/.tmp.XXXXXXX", myInfo->homeDir) ; 5 | incoming_connections.cc:43: sprintf((char *)portBuf, "%d", myInfo->portNo) ; 6 | incoming_connections.cc:145: cn.keepAliveTimer = myInfo->keepAliveTimeOut/2; 7 | incoming_connections.cc:146: cn.keepAliveTimeOut = myInfo->keepAliveTimeOut; 8 | incoming_connections.cc:249: if (myInfo->portNo < n.portNo){ 9 | incoming_connections.cc:255: else if(myInfo->portNo > n.portNo){ 10 | incoming_connections.cc:319: pk.msgLifeTime = myInfo->msgLifeTime; 11 | incoming_connections.cc:334: m.location = myInfo->location > location ? myInfo->location - location : location - myInfo->location ; 12 | incoming_connections.cc:340: if (ttl >= 1 && myInfo->ttl > 0){ 13 | incoming_connections.cc:348: m.ttl = (unsigned int)(ttl) < (unsigned int)myInfo->ttl ? (ttl) : myInfo->ttl ; 14 | incoming_connections.cc:451: pk.msgLifeTime = myInfo->msgLifeTime; 15 | incoming_connections.cc:470: if (ttl >= 1 && myInfo->ttl > 0){ 16 | incoming_connections.cc:478: m.ttl = (unsigned int)(ttl) < (unsigned int)myInfo->ttl ? (ttl) : myInfo->ttl ; 17 | incoming_connections.cc:515: pk.msgLifeTime = myInfo->msgLifeTime; 18 | incoming_connections.cc:539: if (ttl >= 1 && myInfo->ttl > 0){ 19 | incoming_connections.cc:546: m.ttl = (unsigned int)(ttl) < (unsigned int)myInfo->ttl ? (ttl) : myInfo->ttl ; 20 | incoming_connections.cc:581: pk.msgLifeTime = myInfo->getMsgLifeTime; 21 | incoming_connections.cc:623: if (ttl >= 1 && myInfo->ttl > 0){ 22 | incoming_connections.cc:630: m.ttl = (unsigned int)(ttl) < (unsigned int)myInfo->ttl ? (ttl) : myInfo->ttl ; 23 | incoming_connections.cc:665: pk.msgLifeTime = myInfo->msgLifeTime; 24 | incoming_connections.cc:679: if((double)drand48() < (double)myInfo->storeProb){ 25 | incoming_connections.cc:682: if (ttl >= 1 && myInfo->ttl > 0){ 26 | incoming_connections.cc:685: if( !((*it).second == sockfd) && ((double)drand48() <= myInfo->neighborStoreProb ) ){ 27 | incoming_connections.cc:689: m.ttl = (unsigned int)(ttl) < (unsigned int)myInfo->ttl ? (ttl) : myInfo->ttl ; 28 | incoming_connections.cc:728: pk.msgLifeTime = myInfo->msgLifeTime; 29 | incoming_connections.cc:744: if (ttl >= 1 && myInfo->ttl > 0){ 30 | incoming_connections.cc:751: m.ttl = (unsigned int)(ttl) < (unsigned int)myInfo->ttl ? (ttl) : myInfo->ttl ; 31 | incoming_connections.cc:983: if((double)drand48() <= myInfo->cacheProb ) 32 | incoming_connections.cc:1026: pk.msgLifeTime = myInfo->msgLifeTime; 33 | incoming_connections.cc:1032: if (myInfo->isBeacon){ 34 | incoming_connections.cc:1046: if (ttl >= 1 && myInfo->ttl > 0){ 35 | incoming_connections.cc:1054: m.ttl = (unsigned int)(ttl) < (unsigned int)myInfo->ttl ? (ttl) : myInfo->ttl ; 36 | incoming_connections.cc:1126: connectionMap[sockfd].keepAliveTimeOut = myInfo->keepAliveTimeOut; 37 | incoming_connections.cc:1394: for(list::iterator it = myInfo->myBeaconList->begin(); it != myInfo->myBeaconList->end(); it++){ 38 | indexSearch.cc:284:sprintf((char *)kwrd_index, "%s/%s" ,myInfo->homeDir, "kwrd_index"); 39 | indexSearch.cc:287:sprintf((char *)kwrd_index_file, "%s/kwrd_index", myInfo->homeDir); 40 | indexSearch.cc:318:sprintf((char *)name_index, "%s/%s" ,myInfo->homeDir, "name_index"); 41 | indexSearch.cc:321:sprintf((char *)name_index_file, "%s/name_index", myInfo->homeDir); 42 | indexSearch.cc:338:sprintf((char *)sha1_index, "%s/%s" ,myInfo->homeDir, "sha1_index"); 43 | indexSearch.cc:343:sprintf((char *)sha1_index_file, "%s/sha1_index", myInfo->homeDir); 44 | indexSearch.cc:371:sprintf((char *)kwrd_index, "%s/%s" ,myInfo->homeDir, "kwrd_index"); 45 | indexSearch.cc:390:sprintf((char *)kwrd_index_file, "%s/kwrd_index", myInfo->homeDir); 46 | indexSearch.cc:437:sprintf((char *)name_index, "%s/%s" ,myInfo->homeDir, "name_index"); 47 | indexSearch.cc:445:sprintf((char *)name_index_file, "%s/name_index", myInfo->homeDir); 48 | indexSearch.cc:466:sprintf((char *)sha1_index, "%s/%s" ,myInfo->homeDir, "sha1_index"); 49 | indexSearch.cc:476:sprintf((char *)sha1_index_file, "%s/sha1_index", myInfo->homeDir); 50 | indexSearch.cc:618: sprintf((char *)kwrd_index_file, "%s/kwrd_index", myInfo->homeDir); 51 | indexSearch.cc:620: sprintf((char *)name_index_file, "%s/name_index", myInfo->homeDir); 52 | indexSearch.cc:622: sprintf((char *)sha1_index_file, "%s/sha1_index", myInfo->homeDir); 53 | indexSearch.cc:624: sprintf((char *)cacheLRU, "%s/cacheLRU", myInfo->homeDir); 54 | iniParser.cc:20: sprintf((char *)myInfo->node_instance_id, "%s_%ld", myInfo->node_id, (long)sec) ; 55 | iniParser.cc:21:// printf("%s\n", myInfo->node_instance_id) ; 56 | iniParser.cc:30: myInfo->myBeaconList = new list ; 57 | iniParser.cc:31: myInfo->portNo = 0; 58 | iniParser.cc:32: gethostname((char *)myInfo->hostName, 256); 59 | iniParser.cc:33: myInfo->location = 0; 60 | iniParser.cc:34: memset(myInfo->homeDir, '\0', 512); 61 | iniParser.cc:35: strncpy((char *)myInfo->logFileName, "servant.log", strlen("servant.log")); 62 | iniParser.cc:36: myInfo->logFileName[strlen("servant.log")]='\0'; 63 | iniParser.cc:37: myInfo->autoShutDown = 900; 64 | iniParser.cc:38: myInfo->autoShutDown_permanent = 900; 65 | iniParser.cc:39: myInfo->ttl = 30; 66 | iniParser.cc:40: myInfo->msgLifeTime = 30; 67 | iniParser.cc:41: myInfo->getMsgLifeTime = 300; 68 | iniParser.cc:42: myInfo->initNeighbor = 3; 69 | iniParser.cc:43: myInfo->joinTimeOut = 15; 70 | iniParser.cc:44: myInfo->joinTimeOut_permanent = myInfo->joinTimeOut; 71 | iniParser.cc:45: myInfo->checkResponseTimeout = 15; 72 | iniParser.cc:46: myInfo->keepAliveTimeOut = 60; 73 | iniParser.cc:47: myInfo->minNeighbor = 2; 74 | iniParser.cc:48: myInfo->noCheck = 0; 75 | iniParser.cc:49: myInfo->cacheProb = 0.1; 76 | iniParser.cc:50: myInfo->storeProb = 0.1; 77 | iniParser.cc:51: myInfo->neighborStoreProb = 0.2; 78 | iniParser.cc:52: myInfo->cacheSize = 500; 79 | iniParser.cc:53: myInfo->isBeacon = false; 80 | iniParser.cc:54: //myInfo->retry = 30; 81 | iniParser.cc:55: myInfo->retry = 7; 82 | iniParser.cc:56: memset(myInfo->node_id, '\0', 265) ; 83 | iniParser.cc:57: memset(myInfo->node_instance_id, '\0', 300) ; 84 | iniParser.cc:66: printf("Port No: %d\n",myInfo->portNo); 85 | iniParser.cc:67: printf("hostName: %s\n",myInfo->hostName); 86 | iniParser.cc:68: printf("Location: %d\n",myInfo->location); 87 | iniParser.cc:69: printf("HomeDir: %s\n",myInfo->homeDir); 88 | iniParser.cc:70: printf("logFileName: %s\n",myInfo->logFileName); 89 | iniParser.cc:71: printf("autoShutDown: %d\n",myInfo->autoShutDown); 90 | iniParser.cc:72: printf("TTL: %d\n",myInfo->ttl); 91 | iniParser.cc:73: printf("msgLifeTime: %d\n",myInfo->msgLifeTime); 92 | iniParser.cc:74: printf("getMsgLifeTime: %d\n",myInfo->getMsgLifeTime); 93 | iniParser.cc:75: printf("initNeighbor: %d\n",myInfo->initNeighbor); 94 | iniParser.cc:76: printf("joinTimeOut: %d\n",myInfo->joinTimeOut); 95 | iniParser.cc:77: printf("keepAliveTimeOut: %d\n",myInfo->keepAliveTimeOut); 96 | iniParser.cc:78: printf("minNeighbor: %d\n",myInfo->minNeighbor); 97 | iniParser.cc:79: printf("noCheck: %d\n",myInfo->noCheck); 98 | iniParser.cc:80: printf("cacheProb: %lf\n",myInfo->cacheProb); 99 | iniParser.cc:81: printf("storeProb: %lf\n",myInfo->storeProb); 100 | iniParser.cc:82: printf("neighborStoreProb: %lf\n",myInfo->neighborStoreProb); 101 | iniParser.cc:83: printf("cacheSize: %d\n",myInfo->cacheSize); 102 | iniParser.cc:84: printf("retry: %d\n",myInfo->retry); 103 | iniParser.cc:85: printf("isBeacon: %d\n",myInfo->isBeacon); 104 | iniParser.cc:205: myInfo->portNo=atoi((char *)value); 105 | iniParser.cc:219: myInfo->location=atol((char *)value); 106 | iniParser.cc:232: strncpy((char *)myInfo->homeDir,(char *)value, strlen((char *)value)); 107 | iniParser.cc:233: myInfo->homeDir[strlen((char *)value)]='\0'; 108 | iniParser.cc:246: strncpy((char *)myInfo->logFileName,(char *)value, strlen((char *)value)); 109 | iniParser.cc:247: myInfo->logFileName[strlen((char *)value)]='\0'; 110 | iniParser.cc:261: myInfo->autoShutDown=atoi((char *)value); 111 | iniParser.cc:274: myInfo->ttl=atoi((char *)value); 112 | iniParser.cc:287: myInfo->msgLifeTime=atoi((char *)value); 113 | iniParser.cc:300: myInfo->getMsgLifeTime=atoi((char *)value); 114 | iniParser.cc:313: myInfo->initNeighbor=atoi((char *)value); 115 | iniParser.cc:326: myInfo->joinTimeOut=atoi((char *)value); 116 | iniParser.cc:327: myInfo->checkResponseTimeout=atoi((char *)value); 117 | iniParser.cc:340: myInfo->keepAliveTimeOut=atoi((char *)value); 118 | iniParser.cc:353: myInfo->minNeighbor=atoi((char *)value); 119 | iniParser.cc:366: myInfo->noCheck=atoi((char *)value); 120 | iniParser.cc:379: myInfo->cacheProb=atof((char *)value); 121 | iniParser.cc:392: myInfo->storeProb=atof((char *)value); 122 | iniParser.cc:405: myInfo->neighborStoreProb=atof((char *)value); 123 | iniParser.cc:418: myInfo->cacheSize=atoi((char *)value); 124 | iniParser.cc:436: myInfo->retry=atoi((char *)value); 125 | iniParser.cc:448: myInfo->myBeaconList->push_back(beaconNode); 126 | keyboard.cc:42: //alarm(myInfo->autoShutDown); 127 | keyboard.cc:47: printf("\nservant:%d> ", myInfo->portNo) ; 128 | keyboard.cc:102: myInfo->status_ttl = (uint8_t)atoi((char *)value); 129 | keyboard.cc:108: strncpy((char *)myInfo->status_file, (char *)value, strlen((char *)value)) ; 130 | keyboard.cc:109: myInfo->status_file[strlen((char *)myInfo->status_file)] = '\0'; 131 | keyboard.cc:111: myInfo->statusResponseTimeout = myInfo->msgLifeTime + 10 ; 132 | keyboard.cc:112: FILE *fp = fopen((char *)myInfo->status_file, "w") ; 133 | keyboard.cc:127: //printf("WOW!!!! %d\n", myInfo->statusResponseTimeout); 134 | keyboard.cc:166: myInfo->status_ttl = (uint8_t)atoi((char *)value); 135 | keyboard.cc:172: strncpy((char *)myInfo->status_file, (char *)value, strlen((char *)value)) ; 136 | keyboard.cc:173: myInfo->status_file[strlen((char *)myInfo->status_file)] = '\0'; 137 | keyboard.cc:175: myInfo->statusResponseTimeout = myInfo->msgLifeTime + 10 ; 138 | keyboard.cc:176: FILE *fp = fopen((char *)myInfo->status_file, "w") ; 139 | keyboard.cc:183: if(myInfo->status_ttl > 0) 140 | keyboard.cc:191: //printf("WOW!!!! %d\n", myInfo->statusResponseTimeout); 141 | keyboard.cc:264: myInfo->status_ttl = atoi((char *)value) ; 142 | keyboard.cc:404: if(myInfo->status_ttl > 0) 143 | keyboard.cc:667: //sprintf((char *)extFile, "%s/%s", myInfo->homeDir, metadata.fileName); 144 | keyboard.cc:670: //sprintf((char *)extFile, "%s/%s", myInfo->homeDir, value); 145 | main.cc:137: if (!myInfo->isBeacon && !shutDown && !inJoinNetwork && !myInfo->noCheck){ 146 | main.cc:182: myInfo->joinTimeOut_permanent = myInfo->joinTimeOut; 147 | main.cc:183: myInfo->autoShutDown_permanent = myInfo->autoShutDown; 148 | main.cc:184: myInfo->cacheSize*=1024; 149 | main.cc:223: sprintf((char *)filesDir, "%s/files", myInfo->homeDir); 150 | main.cc:225: mkdir((char *)myInfo->homeDir, 0777); 151 | main.cc:228: sprintf((char *)fileNumber_file, "%s/.fileNumber", myInfo->homeDir); 152 | main.cc:240: strncpy((char *)tempLogFile, (char *)myInfo->homeDir, strlen((char*)myInfo->homeDir)); 153 | main.cc:241: strncpy((char *)tempInitFile, (char *)myInfo->homeDir, strlen((char*)myInfo->homeDir)); 154 | main.cc:242: tempLogFile[strlen((char*)myInfo->homeDir)] = '\0'; 155 | main.cc:243: tempInitFile[strlen((char*)myInfo->homeDir)] = '\0'; 156 | main.cc:245: strcat((char *)tempLogFile, (char *)myInfo->logFileName); 157 | main.cc:256: if(!myInfo->isBeacon) 158 | main.cc:263: //f_log = fopen((char *)myInfo->logFileName, "a"); 159 | main.cc:264: //printf("%s", myInfo->logFileName); 160 | main.cc:265: if(strcmp((char *)myInfo->homeDir, "\0")==0 || myInfo->portNo == 0 || myInfo->location == 0) 161 | main.cc:272:// printf("Created a directory %s\n", (char *)myInfo->homeDir); 162 | main.cc:276: //strcpy((char *)n.hostname, (char *)myInfo->hostName); 163 | main.cc:277: for(int i=0;i<(int)strlen((char *)myInfo->hostName);i++) 164 | main.cc:278: n.hostname[i] = myInfo->hostName[i]; 165 | main.cc:279: n.hostname[strlen((char *)myInfo->hostName)] = '\0'; 166 | main.cc:280: n.portNo=myInfo->portNo; 167 | main.cc:281: myInfo->isBeacon = isBeaconNode(n); 168 | main.cc:294: sprintf((char *)myInfo->node_id, "%s_%d", host1, myInfo->portNo) ; 169 | main.cc:295: // printf("My node ID: %s\n", myInfo->node_id) ; 170 | main.cc:400: myInfo->joinTimeOut = myInfo->joinTimeOut_permanent; 171 | main.cc:401: myInfo->autoShutDown = myInfo->autoShutDown_permanent; 172 | main.cc:402: myInfo->checkResponseTimeout = myInfo->joinTimeOut_permanent; 173 | main.cc:470: if (myInfo->isBeacon){ 174 | main.cc:486: for(list::iterator it = myInfo->myBeaconList->begin(); it != myInfo->myBeaconList->end(); it++){ 175 | main.cc:487: if ( (*it)->portNo != myInfo->portNo){ 176 | main.cc:560: myInfo->joinTimeOut = myInfo->joinTimeOut_permanent; 177 | main.cc:564: myInfo->joinTimeOut = -1; 178 | main.cc:585: //for(unsigned int i=0;i < myInfo->minNeighbor; i++) 179 | main.cc:659: cn.keepAliveTimer = myInfo->keepAliveTimeOut/2; 180 | main.cc:660: cn.keepAliveTimeOut = myInfo->keepAliveTimeOut; 181 | main.cc:704: if(nodeConnected == (int)myInfo->minNeighbor) 182 | main.cc:709: if(nodeConnected == (int)myInfo->minNeighbor || shutDown) 183 | main.cc:745: //myInfo->joinTimeOut = myInfo->joinTimeOut_permanent; 184 | metaData.cc:24: sprintf((char *)fileNumber_file, "%s/.fileNumber", myInfo->homeDir); 185 | metaData.cc:580: if(metadata.fileSize > myInfo->cacheSize) 186 | metaData.cc:582: while((metadata.fileSize + currentCacheSize) > myInfo->cacheSize) 187 | metaData.cc:614: sprintf((char *)cacheLRU_file, "%s/cacheLRU", myInfo->homeDir); 188 | metaData.cc:628: sprintf((char *)cacheLRU_file, "%s/cacheLRU", myInfo->homeDir); 189 | outgoing_connections.cc:65: pk.msgLifeTime = myInfo->msgLifeTime; 190 | outgoing_connections.cc:100: memcpy((char *)buffer, &(myInfo->portNo), 2) ; 191 | outgoing_connections.cc:128: memcpy((unsigned char *)buffer, &(myInfo->location), 4) ; 192 | outgoing_connections.cc:129: memcpy((unsigned char *)&buffer[4], &(myInfo->portNo), 2) ; 193 | outgoing_connections.cc:167: memcpy(&buffer[24], &(myInfo->portNo), 2) ; 194 | outgoing_connections.cc:414: memcpy(&buffer[22], &(myInfo->portNo), 2) ; 195 | outgoing_connections.cc:596: connectionMap[sockfd].keepAliveTimer = myInfo->keepAliveTimeOut/2; 196 | outgoing_connections.cc:694: snprintf((char *)str_buf, sizeof(str_buf), "%s_%s_%1ld", myInfo->node_instance_id, obj_type, (long)seq_no++); 197 | outgoing_connections.cc:711: for(list::iterator it = myInfo->myBeaconList->begin(); it != myInfo->myBeaconList->end(); it++){ 198 | outgoing_connections.cc:748: m.ttl = myInfo->ttl ; 199 | outgoing_connections.cc:815: if (joinResponse.size() < myInfo->initNeighbor){ 200 | outgoing_connections.cc:825: if(counter==myInfo->minNeighbor) 201 | outgoing_connections.cc:855: pk.msgLifeTime = myInfo->msgLifeTime; 202 | outgoing_connections.cc:869: m.ttl = myInfo->ttl ; 203 | outgoing_connections.cc:890: pk.msgLifeTime = myInfo->msgLifeTime; 204 | outgoing_connections.cc:897: // myInfo->checkResponseTimeout = myInfo->joinTimeOut ; 205 | outgoing_connections.cc:908: m.ttl = myInfo->ttl ; 206 | outgoing_connections.cc:934: pk.msgLifeTime = myInfo->msgLifeTime; 207 | outgoing_connections.cc:968: m.ttl = myInfo->ttl ; 208 | outgoing_connections.cc:990: FILE *fp = fopen((char *)myInfo->status_file, "a") ; 209 | outgoing_connections.cc:1012: sprintf((char *)portS, "%d", myInfo->portNo) ; 210 | outgoing_connections.cc:1015: if (myInfo->isBeacon){ 211 | outgoing_connections.cc:1084: pk.msgLifeTime = myInfo->msgLifeTime; 212 | outgoing_connections.cc:1098: m.ttl = myInfo->status_ttl ; 213 | outgoing_connections.cc:1112: FILE *fp = fopen((char *)myInfo->status_file, "a") ; 214 | outgoing_connections.cc:1121: own.portNo = myInfo->portNo ; 215 | outgoing_connections.cc:1123: own.hostname[h] = myInfo->hostName[h] ; 216 | outgoing_connections.cc:1174: pk.msgLifeTime = myInfo->msgLifeTime; 217 | outgoing_connections.cc:1187: m.ttl = myInfo->ttl ; 218 | outgoing_connections.cc:1210: pk.msgLifeTime = myInfo->msgLifeTime; 219 | outgoing_connections.cc:1220: if((double)drand48() <= myInfo->neighborStoreProb){ 220 | outgoing_connections.cc:1224: m.ttl = myInfo->status_ttl ; 221 | outgoing_connections.cc:1252: pk.msgLifeTime = myInfo->getMsgLifeTime; 222 | outgoing_connections.cc:1265: m.ttl = myInfo->status_ttl ; 223 | signalHandler.cc:16: if(myInfo->joinTimeOut == 0) 224 | signalHandler.cc:21: myInfo->joinTimeOut--; 225 | signalHandler.cc:46: /*if(myInfo->isBeacon) 226 | signalHandler.cc:65: myInfo->statusResponseTimeout = 0; 227 | timer.cc:24: if(!myInfo->isBeacon && inJoinNetwork) 228 | timer.cc:26: if(myInfo->joinTimeOut > 0) 229 | timer.cc:27: myInfo->joinTimeOut--; 230 | timer.cc:30: if(myInfo->joinTimeOut > 0) 231 | timer.cc:31: myInfo->joinTimeOut--; 232 | timer.cc:34: if(myInfo->joinTimeOut==0) 233 | timer.cc:79: if(myInfo->autoShutDown > 0) 234 | timer.cc:80: myInfo->autoShutDown--; 235 | timer.cc:83: if(!myInfo->autoShutDown) 236 | timer.cc:94: if(myInfo->statusResponseTimeout > 0) 237 | timer.cc:95: --myInfo->statusResponseTimeout ; 238 | timer.cc:96: else //if (myInfo->statusResponseTimeout == 0){ 239 | timer.cc:111: --myInfo->checkResponseTimeout ; 240 | timer.cc:112: //printf("Timer deducted %d\n", myInfo->checkResponseTimeout) ; 241 | timer.cc:113: if (myInfo->checkResponseTimeout <= 0){ 242 | -------------------------------------------------------------------------------- /timer.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include "iniParser.h" 8 | #include "main.h" 9 | 10 | // Timer thread, decrements the value of timer for different timers 11 | void *timer_thread(void *arg){ 12 | 13 | while(!shutDown){ 14 | 15 | sleep(1) ; 16 | 17 | if(shutDown) 18 | { 19 | //printf("Timer thread halted\n"); 20 | break; 21 | } 22 | 23 | //JoinTimeOut, only accessible when node is Joining 24 | if(!myInfo->isBeacon && inJoinNetwork) 25 | { 26 | if(myInfo->joinTimeOut > 0) 27 | myInfo->joinTimeOut--; 28 | else 29 | { 30 | if(myInfo->joinTimeOut > 0) 31 | myInfo->joinTimeOut--; 32 | else 33 | { 34 | if(myInfo->joinTimeOut==0) 35 | { 36 | //printf("Timer out..: %d\n", (int)pthread_self()) ; 37 | kill(accept_pid, SIGUSR1); 38 | break; 39 | } 40 | } 41 | } 42 | } 43 | 44 | //KeepAliveTimeOut, monitors the value and then close the connection if the timeout becomes 0 45 | pthread_mutex_lock(&nodeConnectionMapLock) ; 46 | if(!nodeConnectionMap.empty() && !inJoinNetwork) 47 | { 48 | for (map::iterator it = nodeConnectionMap.begin(); it != nodeConnectionMap.end(); ){ 49 | //printf("Values in my mAP are: %s, %d\n", (*it).first.hostname, (*it).first.portNo); 50 | pthread_mutex_lock(&connectionMapLock) ; 51 | if(connectionMap[(*it).second].keepAliveTimeOut > 0) 52 | { 53 | connectionMap[(*it).second].keepAliveTimeOut--; 54 | it++; 55 | } 56 | else 57 | { 58 | if(connectionMap[(*it).second].keepAliveTimeOut == 0) 59 | { 60 | connectionMap[(*it).second].keepAliveTimeOut=-1; 61 | pthread_mutex_unlock(&connectionMapLock) ; 62 | closeConnection((*it).second); 63 | //nodeConnectionMap.erase((*it).first); 64 | nodeConnectionMap.erase(it++); 65 | pthread_mutex_lock(&connectionMapLock) ; 66 | } 67 | else 68 | it++; 69 | 70 | } 71 | pthread_mutex_unlock(&connectionMapLock) ; 72 | } 73 | } 74 | pthread_mutex_unlock(&nodeConnectionMapLock) ; 75 | 76 | //Auto-ShutDown Timer 77 | if(!inJoinNetwork) 78 | { 79 | if(myInfo->autoShutDown > 0) 80 | myInfo->autoShutDown--; 81 | else 82 | { 83 | if(!myInfo->autoShutDown) 84 | { 85 | //sends the SIGTERM when needs to autoshutdown 86 | kill(node_pid, SIGTERM); 87 | } 88 | } 89 | } 90 | 91 | 92 | // Status timer flag 93 | if (statusTimerFlag && !inJoinNetwork){ 94 | // printf("value is now: %d\n", myInfo->statusResponseTimeout); 95 | if(myInfo->statusResponseTimeout > 0) 96 | --myInfo->statusResponseTimeout ; 97 | else //if (myInfo->statusResponseTimeout == 0){ 98 | { 99 | // Write all the status responses in the output file 100 | //writeToStatusFile() ; 101 | 102 | // Reset the status timer flag 103 | pthread_mutex_lock(&statusMsgLock) ; 104 | statusTimerFlag = 0 ; 105 | pthread_cond_signal(&statusMsgCV); 106 | pthread_mutex_unlock(&statusMsgLock) ; 107 | } 108 | } 109 | 110 | // CHECK timer flag 111 | if (checkTimerFlag && !inJoinNetwork){ 112 | --myInfo->checkResponseTimeout ; 113 | //printf("Timer deducted %d\n", myInfo->checkResponseTimeout) ; 114 | if (myInfo->checkResponseTimeout <= 0){ 115 | // Reset the status timer flag 116 | checkTimerFlag = 0 ; 117 | softRestartFlag = 1 ; 118 | 119 | 120 | // Write all the status responses in the output file 121 | //printf("No response from any beacon node. You are disconnected from the network. Connect again\n") ; 122 | pthread_mutex_lock(&nodeConnectionMapLock) ; 123 | for (map::iterator it = nodeConnectionMap.begin(); it != nodeConnectionMap.end(); ++it){ 124 | notifyMessageSend((*it).second, 3); 125 | } 126 | pthread_mutex_unlock(&nodeConnectionMapLock) ; 127 | sleep(1); 128 | kill(node_pid, SIGTERM); 129 | //break; 130 | // writeToStatusFile() ; 131 | 132 | } 133 | 134 | } 135 | 136 | //MsgLifetime timer, erases the message if the timer expires 137 | if(!inJoinNetwork) 138 | { 139 | pthread_mutex_lock(&MessageDBLock) ; 140 | //map::iterator it_temp; 141 | map::iterator tempIt ; 142 | for(map::iterator it_temp = MessageDB.begin(); it_temp != MessageDB.end(); ) 143 | { 144 | if((*it_temp).second.msgLifeTime > 0) 145 | { 146 | (*it_temp).second.msgLifeTime--; 147 | ++it_temp; 148 | continue; 149 | } 150 | else 151 | { 152 | if((*it_temp).second.msgLifeTime == 0) 153 | { 154 | tempIt = it_temp ; 155 | ++it_temp ; 156 | MessageDB.erase(tempIt); 157 | } 158 | else 159 | ++it_temp; 160 | } 161 | } 162 | pthread_mutex_unlock(&MessageDBLock) ; 163 | 164 | } 165 | 166 | 167 | } 168 | pthread_exit(0); 169 | return 0; 170 | } 171 | 172 | --------------------------------------------------------------------------------