OSDN Git Service

modified to save all ip addresses
authorwatanaby <watanaby@users.sourceforge.net>
Tue, 18 Jun 2013 06:18:47 +0000 (15:18 +0900)
committerwatanaby <watanaby@users.sourceforge.net>
Tue, 18 Jun 2013 06:18:47 +0000 (15:18 +0900)
doc/Changes.html
mdsrc/managementdb.c
mdsrc/opengatemd.c
mdsrc/opengatemd.h
mdsrc/packetcache.c
mdsrc/pcap.c
mdsrc/session.c
mdsrc/workdb.c
sqlscript/createtablescript

index ae9801c..60ffd1c 100644 (file)
@@ -214,7 +214,12 @@ OpengateM History</H3>
        </DD>
        <DT>Ver.0.8.2 at 2013.6.13
        </DT><DD>
-       Fixed bug in ip-address conversion(opengatemd)
+       Fixed bug in ip address conversion(opengatemd)
+       </DD>
+       <DT>Ver.0.8.3 at 2013.6.18
+       </DT><DD>
+       Modified to save all ip addresses(opengatemd).
+       At updating, rerun createtablescript to add a table.
        </DD>
 </DL>
 
index 16545c6..87f0dc0 100644 (file)
@@ -122,7 +122,7 @@ int queryMacFromMngDb(char* macAddress, char* userId, char* extraId){
 /******************************************
 put open log to management db 
 ******************************************/
-int putOpenToMngDb(char* macAddress, char* ipAddress){
+int putOpenToMngDb(char* macAddress){
 
   char queryStr[BUFFMAXLN];
   struct utsname uts;
@@ -133,9 +133,9 @@ int putOpenToMngDb(char* macAddress, char* ipAddress){
   /* prepare query string */
   snprintf(queryStr, BUFFMAXLN, 
           "insert into sessionmd "
-          "(macAddress, ipAddress, gatewayName, openTime, closeTime) "
-          "values ('%s','%s','%s', now(), 0)",
-          macAddress, ipAddress, uts.nodename);
+          "(macAddress, gatewayName, openTime, closeTime) "
+          "values ('%s','%s', now(), 0)",
+          macAddress, uts.nodename);
 
   /* send SQL query */
   if (mysql_query(&mysql, queryStr)){
@@ -170,6 +170,34 @@ int putCloseToMngDb(char* macAddress){
 
 }
 
+/******************************************
+put MAC-IP pair to management db
+******************************************/
+int putMacIpPairToMngDb(char* macAddress, char* ipAddress){
+
+  char queryStr[BUFFMAXLN];
+  struct utsname uts;
+
+  /* get domain name */
+  uname(&uts);
+
+  /* prepare query string */
+  snprintf(queryStr, BUFFMAXLN, 
+          "insert into macippair "
+          "(macAddress, ipAddress, findTime) "
+          "values ('%s','%s', now())",
+          macAddress, ipAddress);
+
+  /* send SQL query */
+  if (mysql_query(&mysql, queryStr)){
+     err_msg("ERR at %s#%d: mysql query: %s",__FILE__,__LINE__,
+            mysql_error(&mysql));
+     return FALSE;
+  }
+
+  return TRUE;
+}
+
 /********************************************
  routines for debugging output
 ********************************************/
@@ -200,11 +228,20 @@ int PutCloseToMngDb(char* macAddress){
   if(debug>1) err_msg("DEBUG:(%d)<=putCloseToMngDb()",ret);
   return ret;
 }
-int PutOpenToMngDb(char* macAddress, char* ipAddress){
+
+int PutOpenToMngDb(char* macAddress){
   int ret;
-  if(debug>1) err_msg("DEBUG:=>putOpenToMngDb(%s,%s)", macAddress, ipAddress);
-  ret = putOpenToMngDb(macAddress, ipAddress);
+  if(debug>1) err_msg("DEBUG:=>putOpenToMngDb(%s)", macAddress);
+  ret = putOpenToMngDb(macAddress);
   if(debug>1) err_msg("DEBUG:(%d)<=putOpenToMngDb()",ret);
   return ret;
 }
 
+int PutMacIpPairToMngDb(char* macAddress, char* ipAddress){
+  int ret;
+  if(debug>1) err_msg("DEBUG:=>putMacIpPairToMngDb(%s,%s)", 
+                     macAddress, ipAddress);
+  ret = putMacIpPairToMngDb(macAddress, ipAddress);
+  if(debug>1) err_msg("DEBUG:(%d)<=putMacIpPairToMngDb()",ret);
+  return ret;
+}
index 14370b7..31bff0c 100644 (file)
@@ -29,7 +29,7 @@ to maintain the state of each terminal.
    1. Packet Check Cache
        To speed up the packet check process, the address checked once 
          is ignored for a while.
-       The cache (key: MAC address) is used to decide 
+       The cache (key: MAC&IP address pair) is used to decide 
          the necessity of checking.
        The cache is maintained the information of arrived packets 
          by using hash-table and queue in the memory of local machine.
@@ -47,7 +47,8 @@ to maintain the state of each terminal.
          (key: MAC address) is maintained in the memory of local machine.
 
 MAC address is used as main key for the user terminal.
-IP address is kept only for information (firstly detected address only)
+IP address is kept only for information.
+The packet cache uses the MAC-IP pair, as to record all IP. 
 *************************************/
 
 #include       "opengatemd.h"
@@ -66,10 +67,10 @@ int  main(int argc, char **argv)
 {
   char ipAddress[ADDRMAXLN];  /* packet source ip address */
   char macAddress[ADDRMAXLN]; /* packet source mac address */
-  unsigned char macAddressRaw[ADDRMAXLN];/* mac addr in raw form */
-  unsigned char ipAddressRaw[ADDRMAXLN];/* ip addr in raw form */
-  /* above is network raw binary, MAC(6bytes) and IP(4or16Bytes) */
-  int ipAddrLen;               /* ip address byte length 4 or 16 */         
+    unsigned char macAndIpAddressRaw[ADDRMAXLN];/* mac&ip addr in raw form */
+  /* above is network raw binary concatenating MAC(6bytes) and IP(4or16Bytes) */
+  int addrLen;               /* ip address byte length 6+4 or 6+16 */         
+
   char userId[USERMAXLN];     /* user id related to the mac address */
   char extraId[USERMAXLN];    /* optional id for the user */
   int macFound;               /* flag: mac address is resistered in db */
@@ -80,6 +81,7 @@ int  main(int argc, char **argv)
   int stopServiceMode=FALSE;  /* flag: start with stop service option */ 
   int showVersionMode=FALSE;  /* flag: show version */
   int helpMode=FALSE;         /* flag: start with help mode */
+
   int ttl;                    /* packet ttl(time to live) or hlim(hop limit) */
   int i;                      /* for loop control */
   int uselessCheckTime=0;     /* the last time for useless check */
@@ -181,14 +183,14 @@ int  main(int argc, char **argv)
       sigIoArrived=FALSE;
       while(GetDataFromUdpPort(macAddrInUdp, ADDRMAXLN, clientIpAddress)>0){
        if(IsUdpClientTrusted(clientIpAddress)){
-         DelCacheItem(macAddrInUdp);
+         DelCacheItem(macAddrInUdp,"");
          DelMacCacheItem(macAddrInUdp);
        }
       }
     }      
 
     /* get one packet from pcap */
-    ret=GetNextPacketFromPcap(macAddressRaw, ipAddressRaw, &ipAddrLen, &ttl);
+    ret=GetNextPacketFromPcap(macAndIpAddressRaw, &addrLen, &ttl);
 
     /* if no packet */
     if(ret==0){
@@ -211,13 +213,14 @@ int  main(int argc, char **argv)
     if(ttl<=1) continue;
    
     /* ignore the packet checked recently */
-    if( IsRecentlyCheckedAddress(macAddressRaw) ) continue;
+    if( IsRecentlyCheckedAddress(macAndIpAddressRaw, addrLen) ) continue;
 
     /**** only cache timeout packets proceeds to below ****/
 
     /* convert address from network-raw form to presentation form */
-    ConvertMacFromRawToDisplay(macAddressRaw,macAddress);
-    ConvertIpFromRawToDisplay(ipAddressRaw,ipAddrLen,ipAddress);
+    ConvertMacFromRawToDisplay(macAndIpAddressRaw, macAddress);
+    ConvertIpFromRawToDisplay(macAndIpAddressRaw+MACADDRLN,
+                             addrLen-MACADDRLN, ipAddress);
 
     /* check nat/router and save info to db */
     isNatOrRouter=IsSentViaNatOrRouter(ipAddress, macAddress, ttl);
@@ -225,25 +228,31 @@ int  main(int argc, char **argv)
     PutMacInfoToWorkDb(macAddress, ttl, isNatOrRouter);
 
     /*** get the status of the terminal from session table and DB ***/
+
     /* search the address in session table */
     sessionFound = IsMatchedSessionFound(macAddress);
 
-    /* search the address in MAC DB cache */ 
+    /* search the address in cache of MAC DB */ 
     macFound = QueryMacFromMacCache(macAddress, userId, extraId);
 
-    /* if not found in MAC DB cache, search DB and add it to cache */
+    /* if not found in MAC DB cache, access MAC DB and add result to cache */
     if(!macFound){
       macFound = QueryMacFromMngDb(macAddress, userId, extraId);
       if(macFound) AddMacCacheItem(macAddress, userId, extraId);
     }
 
     /*** depending the states, add/del/renew the session ***/
+
     /* if valid mac and no session, start session */
     if(macFound && !sessionFound){
-       AddSession(macAddress, ipAddress, userId, extraId);
+       AddSession(macAddress, userId, extraId);
+
+       /* save MAC and IP address pair */
+       SetMacIpPair(macAddress, ipAddress, userId, extraId);
     }
 
     /* if no mac and started session, stop session */
+    /* (MAC and IP pairs are removed in stop session) */
     if(!macFound && sessionFound){
       DelSession(macAddress);
     }
@@ -257,11 +266,16 @@ int  main(int argc, char **argv)
       /* when no ipfw rule exists, reset the session */
       else{
        DelSession(macAddress);
-       AddSession(macAddress, ipAddress, userId, extraId);     
+       AddSession(macAddress, userId, extraId);        
       }
+
+      /* save MAC and IP address pair */
+      /* only when new pair is found.  */
+      SetMacIpPair(macAddress, ipAddress, userId, extraId);
     }
 
     /*  check useless sessions at some interval */
+    /* (MAC and IP pairs are removed in stop session) */
     if( time(NULL) - uselessCheckTime > checkInterval ){
       uselessCheckTime = time(NULL);
       DelUselessSessions();
index 0fcb393..4aa7499 100644 (file)
@@ -154,7 +154,7 @@ char *GetNextConfValue(void);
 
 /* pcap.c */
 int InitPcap(void);
-int GetNextPacketFromPcap(unsigned char* macAddressRaw, unsigned char* ipAddressRaw, int* pIpAddrLen, int* pTtl);
+int GetNextPacketFromPcap(unsigned char* macAndIpAddressRaw, int* pAddrLen, int* pTtl);
 void ClosePcap(void);
 int GetMyMacAddress(char* macAddress);
 void ConvertIpFromRawToDisplay(unsigned char* ipAddressRaw, int ipAddrLen, char* ipAddress);
@@ -162,9 +162,9 @@ void ConvertMacFromRawToDisplay(unsigned char* macAddressRaw, char* macAddress);
 
 /* packetcache.c */
 void InitCache(void);
-int IsRecentlyCheckedAddress(unsigned char* macAddressRaw);
+int IsRecentlyCheckedAddress(unsigned char* macAndIpAddressRaw, int addrLen);
 void FreeCache(void);
-int DelCacheItem(char* macAddress);
+int DelCacheItem(char* macAddress, char* ipAddress);
 int DelOldestCacheItem(void);
 int ReFormatMacAddr(char* macAddr);
 
@@ -173,27 +173,30 @@ int InitMngDb(void);
 int QueryMacFromMngDb(char* macAddress, char* userid, char* extraid);
 void CloseMngDb(void);
 int PutCloseToMngDb(char* macAddress);
-int PutOpenToMngDb(char* macAddress, char* ipAddress);
+int PutOpenToMngDb(char* macAddress);
+int PutMacIpPairToMngDb(char* macAddress, char* ipAddress);
 
 /* workdb.c */
 int SetupSqliteBusyTimeoutValue(void);
 int InitWorkDb(void);
 int FinalizeWorkDb(void);
 int InsertSessionToWorkDb(char* macAddress, char* userId, char* extraId, 
-                       char* ipAddress, int ruleNumber);
+                        int ruleNumber);
 int DelSessionFromWorkDb(char* macAddress);
 int GetSessionFromWorkDb(char* macAddress, char* userId, char* extraId, 
-                        int* openTime, int* checkTime, char *ipAddress,
-                          int* ruleNumber);
+                        int* openTime, int* checkTime, int* ruleNumber);
 int UpdateCheckTimeInWorkDb(char* macAddress);
 int DelUselessSessionsInWorkDb(int delayed);
 int GetSessionTableFromWorkDb(DB* sessionTable);
 int PutMacInfoToWorkDb(char* macAddress, int ttl, int isNat);
 int GetMacInfoFromWorkDb(char* macAddress, char* detectTimeStr, int* pTtl);
 int IsActiveRuleInWorkDb(int ruleNumber);
+int IsFoundMacIpPairInWorkDb(char* macAddress, char* ipAddress);
+int PutMacIpPairToWorkDb(char* macAddress, char* ipAddress);
+int DelMacIpPairsInWorkDb(char* macAddress);
 
 /* session.c */
-int AddSession(char* macAddress, char* ipAddress, char* userId, char* extraId);
+int AddSession(char* macAddress, char* userId, char* extraId);
 void DelSession(char* macAddress);
 void RenewSession(char* macAddress);
 void DelUselessSessions(void);
@@ -201,12 +204,14 @@ void DelAllSessions(void);
 int CloseSession(void* pParam, int argc, char *argv[], char* colName[]);
 int IsMatchedSessionFound(char* macAddress);
 void CloseUnmatchSessions(void);
-void WriteOpenToSyslog(char* userId, char* extraId, char* ipAddress, char* macAddress);
-void WriteCloseToSyslog(char* userId, char* extraId, char* ipAddress, char* macAddress, int openTime);
-void WriteSessionInfoToSyslog(char* userId, char* extraId, char* ipAddress, char* macAddress, int ruleNumber);
+void WriteOpenToSyslog(char* userId, char* extraId, char* macAddress);
+void WriteCloseToSyslog(char* userId, char* extraId, char* macAddress, int openTime);
+void WriteSessionInfoToSyslog(char* userId, char* extraId, char* macAddress, int ruleNumber);
 void RemoveSessionUnmatchedToIpfwRule(DB* ruleTable, DB* sessionTable);
 void RemoveIpfwRuleUnmatchedToSession(DB* ruleTable, DB* sessionTable);
 int IsProcessFoundForTheRule(int ruleNumber);
+void SetMacIpPair(char* macAddress, char* ipAddress, char* userId, char* extraId);
+void ResetMacIpPairs(char* macAddress);
 
 /* ttlcheck.c */
 int InitTtlCheck(void);
index 00ea80e..1d5bf63 100644 (file)
@@ -1,19 +1,19 @@
 /**************************************************
-OpengateM - a MAC address authentication system
- module to control packet check cache
+opengate Mac addr auth program
 
+ module to control cache of mac and ip address pair
   to skip checking every packets.
-  All detected mac addresses are cached.
+  All detected address pair (allowable or not) are cached.
 
   As checking packet is time consuming procedure,
   the recently checked addresses are cached and skiped.
   Implemented with HashTable and Queue.
   HashTable:
-    Key= MAC Addresses
+    Key= comcatenation of MAC and IP Addresses
     Val= checked time
-    If address is included in table and time is new, skip checking.
+    If address pair is included in table and time is new, skip checking.
   Queue:
-    Address odrered by checked time.
+    Address pair odrered by checked time.
     If an old item is found in table, elder items are removed from table.
     The queue controls the remove sequence.
 
@@ -46,40 +46,39 @@ int DeQueueForCache(unsigned char* addrRaw, int* pAddrLen);
 int ListQueueForCache(void);
 void FreeQueueForCache(void);
 
-/* Queue to store MacAddress in time order */
+/* Queue to store MacAndIpAddress */
 struct queueNode{
   int addrLen;
-  unsigned char addrRaw[MACADDRLN];
+  unsigned char addrRaw[MACADDRLN+IPV6ADDRLN];
   struct queueNode *next;
 };
 static struct queueNode* queueTail=NULL;
 static struct queueNode* queueHead=NULL;
 
-/* HashTable key=MacAddress and value=DetectTime */
+/* HashTable to store MacAndIpAddress and Time */
 static DB* hashDb;
 
 /* Cache Timeout(seconds) : packet checking interval */
 static int cacheTimeout;
 
-/* number of items in the cache */
 static int cacheItemCount=0;
 
 /**********************************
 This cache is made from HashTable and Queue.
-HashTable for quick access, and Queue for ordering.
+HashTabel for quick access, and Queue for ordering.
 Same data are stored in the two data structures.
 If you add/delete items in cache, treat both structures.
 Don't add/delete items from one structure only. 
 ***********************************/
 
 /****************************************
-Is the macAddress checked recently or not
- input=macAddress return TRUE if checked recently
+Is the IpAddress checked recently or not
+ input=ipAddress return TRUE if checked recently
 ****************************************/
-int isRecentlyCheckedAddress(unsigned char* macAddressRaw){
+int isRecentlyCheckedAddress(unsigned char* macAndIpAddressRaw, int addrLen){
 
   int timeNow;
-  unsigned char storedAddrRaw[ADDRMAXLN];
+  unsigned char storedAddrRaw[MACADDRLN+IPV6ADDRLN];
   int storedAddrLen;
   int ret;
   int* pTime;
@@ -89,9 +88,9 @@ int isRecentlyCheckedAddress(unsigned char* macAddressRaw){
   /* get present time */
   timeNow=time(NULL);
 
-  /***** get item matched to the mac from hash table */
-  hashKey.data = macAddressRaw;
-  hashKey.size = MACADDRLN;
+  /***** get item matched to the mac&ip from hash table */
+  hashKey.data = macAndIpAddressRaw;
+  hashKey.size = addrLen;
   memset(&hashVal, 0, sizeof(DBT));
   ret=hashDb->get(hashDb, &hashKey, &hashVal, 0);
 
@@ -117,10 +116,10 @@ int isRecentlyCheckedAddress(unsigned char* macAddressRaw){
       hashKey.data=storedAddrRaw;
       hashKey.size = storedAddrLen;
       hashDb->del(hashDb, &hashKey, 0);
-      if(memcmp(macAddressRaw,storedAddrRaw,storedAddrLen)==0)break;
+      if(memcmp(macAndIpAddressRaw,storedAddrRaw,storedAddrLen)==0)break;
     }
 
-    /* insert last item after renewing the time */
+    /* insert update item to queue and hashTable */
     EnQueueForCache(storedAddrRaw, storedAddrLen);
     hashVal.data = &timeNow;
     hashVal.size = sizeof(int);    
@@ -145,7 +144,7 @@ int isRecentlyCheckedAddress(unsigned char* macAddressRaw){
       terminateProg(0);
     }
     /* insert to queue */
-    EnQueueForCache(macAddressRaw, MACADDRLN);
+    EnQueueForCache(macAndIpAddressRaw, addrLen);
     /*************** end adding item to Cache ***/
 
     /* if cache size is over, remove oldest one */
@@ -159,8 +158,8 @@ int isRecentlyCheckedAddress(unsigned char* macAddressRaw){
 }
 
 /****************************************
-initialize packet check Cache
The Cache is formed with in HashTable and Queue
+initialize Mac&IpAddress Cache
Mac&Ip Cache is formed with in HashTable and Queue
  HashTable=to search an item quickly
  Queue    =to list items in FIFO order
 ****************************************/
@@ -180,7 +179,7 @@ void initCache(void) {
 }
 
 /****************************************
-memory free for packet check Cache
+memory free for Mac&IpAddress Cache
 ****************************************/
 void freeCache(void) {
 
@@ -190,24 +189,67 @@ void freeCache(void) {
 
 
 /****************************************
-delete item from packet check cache matched to the mac address
+delete item from MacAndIp cache matched to the mac or/and ip address
+set arguments for mac and/or ip to detele
+set argument as "", if the address is not known 
+ eg: to delete item for an ipv4 and unknown mac, ("", "192.168.0.100")
 ****************************************/
-int delCacheItem(char* macAddress) {
+int delCacheItem(char* macAddress, char* ipAddress) {
   int found=FALSE;
   DBT hashKey;
-  unsigned char macAddressRaw[MACADDRLN];
+  unsigned char addrRaw[MACADDRLN+IPV6ADDRLN];
   unsigned char* pRawMac;
   struct queueNode *temp;
   struct queueNode *prev;
+  int inMac=FALSE;
+  int inIpv4=FALSE;
+  int inIpv6=FALSE;
+  int shift=0;
+  int length=0;
 
   /*** set the raw values */
-  /* if mac is null, return fail */
-  if(isNull(macAddress)) return FALSE;
+  /* if mac is not null, set the mac raw value */
+  if(!isNull(macAddress)) {
+    if((pRawMac=(unsigned char*)ether_aton(macAddress)) != NULL){
+      memcpy(addrRaw, pRawMac, MACADDRLN);
+      inMac=TRUE;
+    }
+  }
 
-  /* convert mac to raw form */
-  if((pRawMac=(unsigned char*)ether_aton(macAddress)) != NULL){
-    memcpy(macAddressRaw, pRawMac, MACADDRLN);
-  }else return FALSE;
+  /* if ip is not null, set the ipv6/ipv4 raw value */
+  if(!isNull(ipAddress)) {
+    if(strchr(ipAddress, ':') != NULL) {
+      if(inet_pton(AF_INET6, ipAddress, addrRaw+MACADDRLN) > 0) inIpv6=TRUE;
+    }
+    else{
+      if(inet_pton(AF_INET, ipAddress, addrRaw+MACADDRLN) > 0) inIpv4=TRUE;
+    }
+  }
+  
+  /*** set start point and length for comparing string */
+  if(inMac && !inIpv6 && !inIpv4){ /* only mac is indivcated */
+    shift=0;
+    length=MACADDRLN;
+  }
+  else if(!inMac && inIpv6){ /* only ipv6 is indicated */
+   shift=MACADDRLN;
+   length=IPV6ADDRLN;
+  }
+  else if(!inMac && inIpv4){ /* only ipv4 is indicated */
+    shift=MACADDRLN;
+    length=IPV4ADDRLN;
+  }
+  else if(inMac && inIpv6){ /* mac and ipv6 is indicated */
+    shift=0;
+    length=MACADDRLN+IPV6ADDRLN;
+  }
+  else if(inMac && inIpv4){ /* mac and ipv4 is indicated */
+    shift=0;
+    length=MACADDRLN+IPV4ADDRLN;
+  }
+  else{ /* no one is indicated */
+    return FALSE;
+  }
 
   /*** scan queue to find matched address */
   /* set search point to the head of mac-ip cache */
@@ -219,7 +261,7 @@ int delCacheItem(char* macAddress) {
   while(temp->next!=NULL){
 
     /* compare indicated value and queue value */
-    if(memcmp(macAddressRaw, (temp->addrRaw), MACADDRLN)==0){
+    if(memcmp(addrRaw+shift, (temp->addrRaw)+shift, length)==0){
 
       /* set found flag */
       found=TRUE;
@@ -243,11 +285,11 @@ int delCacheItem(char* macAddress) {
 }
 
 /****************************************
-delete oldest item from packet cache 
+delete oldest item from MacAndIp cache 
 ****************************************/
 int delOldestCacheItem(void) {
   DBT hashKey;
-  unsigned char addrRaw[ADDRMAXLN];
+  unsigned char addrRaw[MACADDRLN+IPV6ADDRLN];
   int addrLen=0;
   
   /* delete oldest item(=head) from queue */
@@ -265,16 +307,15 @@ int delOldestCacheItem(void) {
 }
 
 /*********************************************
-initialize Queue
+initialize MacAndIpAddress Queue
  Queue
  HeadNode - DataNode - DataNode - TailNode
  (dummy)                           (dummy)
   ^queueHead                        ^queueTail
-* this queue is internal struct of packet cache 
 *********************************************/
 int initQueueForCache(void){
 
-  unsigned char addrRaw[MACADDRLN];
+  unsigned char addrRaw[MACADDRLN+IPV6ADDRLN];
   int addrLen;
 
   /* if not exist, prepare head and tail */
@@ -289,9 +330,9 @@ int initQueueForCache(void){
       err_msg("ERR at %s#%d: fail to malloc",__FILE__,__LINE__);
       terminateProg(0);
     }
-    bzero(queueHead->addrRaw, MACADDRLN);
+    bzero(queueHead->addrRaw, MACADDRLN+IPV6ADDRLN);
     queueHead->addrLen=0;
-    bzero(queueTail->addrRaw, MACADDRLN);
+    bzero(queueTail->addrRaw, MACADDRLN+IPV6ADDRLN);
     queueTail->addrLen=0;
     queueHead->next=queueTail;
     queueTail->next=NULL;
@@ -310,7 +351,7 @@ int initQueueForCache(void){
 }
 
 /****************************************
-Add data to the tail of Queue
+Add data to the tail of MacAndIP Queue
  input=addr
 ****************************************/
 int enQueueForCache(unsigned char* addrRaw, int addrLen){
@@ -322,12 +363,6 @@ int enQueueForCache(unsigned char* addrRaw, int addrLen){
     return FALSE;
   }
 
-  /* check length */
-  if(addrLen>MACADDRLN){
-    err_msg("ERR at %s#%d: queue data is too long",__FILE__,__LINE__);
-    return FALSE;
-  }
-
   /* add item after the tail and set it as new tail*/
   newNode=(struct queueNode*)malloc(sizeof(struct queueNode));
   if(newNode==NULL){
@@ -338,7 +373,7 @@ int enQueueForCache(unsigned char* addrRaw, int addrLen){
   queueTail->addrLen=addrLen;
   queueTail->next=newNode;
   queueTail=newNode;
-  bzero(queueTail->addrRaw,MACADDRLN);
+  bzero(queueTail->addrRaw,MACADDRLN+IPV6ADDRLN);
   queueTail->addrLen=0;
   queueTail->next=NULL;
 
@@ -349,15 +384,15 @@ int enQueueForCache(unsigned char* addrRaw, int addrLen){
 }
 
 /****************************************
-Get and remove address data from the head of Queue
+Get and remove address data from the head of MacAndIP Queue
 output
- addrRaw:binary string of Mac (length=MACADDRLN)
+ addrRaw:binary string of Mac&Ip (length=MACADDRLN+IPV6ADDRLN)
  pAddrLen: pointer to the aquired string length 
 ****************************************/
 int deQueueForCache(unsigned char* addrRaw, int* pAddrLen){
 
   /* set null string as default */
-  bzero(addrRaw, MACADDRLN);
+  bzero(addrRaw, MACADDRLN+IPV6ADDRLN);
 
   /* if not prepared, error */
   if(queueHead==NULL){
@@ -391,7 +426,7 @@ int deQueueForCache(unsigned char* addrRaw, int* pAddrLen){
 }
 
 /****************************************
-Listing Queue (for debugging)
+Listing MacAndIpAddress Queue (for debugging)
 ****************************************/
 int listQueueForCache(void){
 
@@ -413,10 +448,10 @@ int listQueueForCache(void){
 }
 
 /****************************************
-memory free for Queue
+memory free for MacAndIpAddress Queue
 ****************************************/
 void freeQueueForCache(void){
-  unsigned char addrRaw[MACADDRLN];
+  unsigned char addrRaw[MACADDRLN+IPV6ADDRLN];
   int addrLen;
   while(DeQueueForCache(addrRaw,&addrLen));
   free(queueHead);
@@ -456,18 +491,18 @@ void FreeCache(void) {
   if(debug>1) err_msg("DEBUG:<=freeCache()");
 }
 
-int IsRecentlyCheckedAddress(unsigned char* macAddressRaw){
+int IsRecentlyCheckedAddress(unsigned char* macAndIpAddressRaw, int addrLen){
   int ret;
-  if(debug>1) err_msg("DEBUG:=>isRecentlyCheckedAddress(%x)", macAddressRaw[0]);
-  ret = isRecentlyCheckedAddress(macAddressRaw);
+  if(debug>1) err_msg("DEBUG:=>isRecentlyCheckedAddress(%x,%d)", macAndIpAddressRaw[0],addrLen);
+  ret = isRecentlyCheckedAddress(macAndIpAddressRaw, addrLen);
   if(debug>1) err_msg("DEBUG:(%d)<=isRecentlyCheckedAddress( )",ret);
   return ret;
 }
 
-int DelCacheItem(char* macAddress) {
+int DelCacheItem(char* macAddress, char* ipAddress) {
   int ret;
-  if(debug>1) err_msg("DEBUG:=>delCacheItem(%s)", macAddress);
-  ret = delCacheItem(macAddress);
+  if(debug>1) err_msg("DEBUG:=>delCacheItem(%s,5s)", macAddress,ipAddress);
+  ret = delCacheItem(macAddress,ipAddress);
   if(debug>1) err_msg("DEBUG:(%d)<=delCacheItem( )",ret);
   return ret;
 }
index 7e44d91..bc43a9d 100644 (file)
@@ -85,7 +85,7 @@ int initPcap(void){
 get next packet from pcap 
 ret=0:no packet,1:ip packet,-1:other packet
 *******************************/
-int getNextPacketFromPcap(unsigned char* macAddressRaw, unsigned char* ipAddressRaw, int* pIpAddrLen, int* pTtl){
+int getNextPacketFromPcap(unsigned char* macAndIpAddressRaw, int* pAddrLen, int* pTtl){
   struct pcap_pkthdr header;   /* The header captured by pcap */
   const u_char *packet;                /* The actual packet */
   struct ip *ipv4h; 
@@ -94,10 +94,9 @@ int getNextPacketFromPcap(unsigned char* macAddressRaw, unsigned char* ipAddress
   int ret=0;
 
   /* initialize to null string */
-  bzero(macAddressRaw,MACADDRLN);
-  bzero(ipAddressRaw,IPV6ADDRLN);
+  bzero(macAndIpAddressRaw,MACADDRLN+IPV6ADDRLN);
   *pTtl=0;
-  *pIpAddrLen=0;
+  *pAddrLen=0;
 
   /* Grab a packet */
   if((packet = pcap_next(handle, &header)) == NULL)return 0; /* 0=no packet*/
@@ -109,22 +108,22 @@ int getNextPacketFromPcap(unsigned char* macAddressRaw, unsigned char* ipAddress
   
   /* get mac address from ether header */
   ethhdr = (struct ether_header *)packet; 
-  memcpy(macAddressRaw, ethhdr->ether_shost, MACADDRLN);
+  memcpy(macAndIpAddressRaw, ethhdr->ether_shost, MACADDRLN);
 
   /* get ip address from ip header */
   switch (ntohs(ethhdr->ether_type)) { 
     case ETHERTYPE_IP: 
-      *pIpAddrLen=IPV4ADDRLN;
+      *pAddrLen=IPV4ADDRLN+MACADDRLN;
       ipv4h = (struct ip *)(packet + sizeof(struct ether_header)); 
-      memcpy( ipAddressRaw, &ipv4h->ip_src, IPV4ADDRLN);
+      memcpy( macAndIpAddressRaw+MACADDRLN, &ipv4h->ip_src, IPV4ADDRLN);
       *pTtl = ipv4h->ip_ttl;
       ret=1; /* 1=success */
       break;
 
     case ETHERTYPE_IPV6: 
-      *pIpAddrLen=IPV6ADDRLN;
+      *pAddrLen=IPV6ADDRLN+MACADDRLN;
       ipv6h = (struct ip6_hdr *)(packet + sizeof(struct ether_header)); 
-      memcpy(ipAddressRaw, &ipv6h->ip6_src, IPV6ADDRLN);
+      memcpy(macAndIpAddressRaw+MACADDRLN, &ipv6h->ip6_src, IPV6ADDRLN);
       *pTtl = ipv6h->ip6_ctlun.ip6_un1.ip6_un1_hlim;
       ret=1; /* 1=success */
       break; 
@@ -234,11 +233,12 @@ int InitPcap(void){
   if(debug>1) err_msg("DEBUG:(%d)<=initPcap( )",ret);
   return ret;
 }
-int GetNextPacketFromPcap(unsigned char* macAddressRaw, unsigned char* ipAddressRaw, int* pIpAddrLen, int* pTtl){
+
+int GetNextPacketFromPcap(unsigned char* macAndIpAddressRaw, int* pAddrLen, int* pTtl){
   int ret;
   if(debug>2) err_msg("DEBUG:=>getNextPacketFromPcap( )");
-  ret = getNextPacketFromPcap(macAddressRaw, ipAddressRaw, pIpAddrLen, pTtl);
-  if(debug>2) err_msg("DEBUG:(%d)<=getNextPacketFromPcap(%x,%x,%d,%d)",ret,macAddressRaw[0],ipAddressRaw,*pIpAddrLen,*pTtl);
+  ret = getNextPacketFromPcap(macAndIpAddressRaw, pAddrLen, pTtl);
+  if(debug>2) err_msg("DEBUG:(%d)<=getNextPacketFromPcap(%x,%d,%d)",ret,macAndIpAddressRaw[0],*pAddrLen,*pTtl);
   return ret;
 }
 
index 3625f44..a78c245 100644 (file)
@@ -27,11 +27,10 @@ Email: watanaby@is.saga-u.ac.jp
 add session for the mac address
 add ipfw-rule and table-entry, write db and log 
 *******************************/
-int addSession(char* macAddress, char* ipAddress, char* userId, char* extraId){
+int addSession(char* macAddress, char* userId, char* extraId){
   int ruleNumber;
   static int nSerialError=0; /* number of serial errors for addition */
   int failToAdd=FALSE;
-  char ipAddressInDb[ADDRMAXLN];
   int openTime;
   int checkTime;
   int ruleNumberInDb;
@@ -47,7 +46,7 @@ int addSession(char* macAddress, char* ipAddress, char* userId, char* extraId){
     
     /* if mac is active session in work db, do nothing */
     if(GetSessionFromWorkDb(macAddress, userId, extraId, &openTime,
-                           &checkTime, ipAddressInDb, &ruleNumberInDb)){ 
+                           &checkTime, &ruleNumberInDb)){ 
       return FALSE;
     }
     /* if not active session in work db, invert sign and goto write db */
@@ -60,7 +59,7 @@ int addSession(char* macAddress, char* ipAddress, char* userId, char* extraId){
   /* as to prevent error loop, retry count is limitted */ 
   if( failToAdd || !IsMacAddressFoundInIpfw(macAddress) ){
     nSerialError++;
-    if(nSerialError<1) DelCacheItem(macAddress);
+    if(nSerialError<1) DelCacheItem(macAddress,"");
     err_msg("ERR at %s#%d: ipfw rule addition is failed(%d-%d)",
              __FILE__,__LINE__, failToAdd, nSerialError);
     return FALSE;
@@ -68,13 +67,13 @@ int addSession(char* macAddress, char* ipAddress, char* userId, char* extraId){
   nSerialError=0;
 
   /* write to session db */
-  InsertSessionToWorkDb(macAddress, userId, extraId, ipAddress, ruleNumber);
+  InsertSessionToWorkDb(macAddress, userId, extraId, ruleNumber);
 
   /* write open log to syslog */
-  WriteOpenToSyslog(userId, extraId, ipAddress, macAddress);
+  WriteOpenToSyslog(userId, extraId, macAddress);
 
   /* write log to management db */
-  PutOpenToMngDb(macAddress, ipAddress);
+  PutOpenToMngDb(macAddress);
   return TRUE;
 }
 
@@ -85,7 +84,6 @@ delete session for the mac address
 void delSession(char* macAddress){
   char userId[USERMAXLN]="";
   char extraId[USERMAXLN]="";
-  char ipAddress[ADDRMAXLN]="";
   int openTime=0;
   int ruleNumber=0;
   int checkTime=0;
@@ -93,24 +91,27 @@ void delSession(char* macAddress){
 
   /* get information from session table in work db */
   success=GetSessionFromWorkDb(macAddress, userId, extraId, &openTime, 
-                                &checkTime, ipAddress, &ruleNumber);
+                                &checkTime, &ruleNumber);
 
   /* close firewall and refresh the cache */
   if(success) CloseClientGate(ruleNumber);
 
   /* del from cache */
-  DelCacheItem(macAddress);
+  DelCacheItem(macAddress,"");
   
   /* del from session from session table in work db */
   DelSessionFromWorkDb(macAddress);
 
   /* write close log to syslog */
-  WriteCloseToSyslog(userId, extraId, ipAddress, macAddress, openTime);
-  if(debug>0) WriteSessionInfoToSyslog(userId, extraId, ipAddress, 
+  WriteCloseToSyslog(userId, extraId, macAddress, openTime);
+  if(debug>0) WriteSessionInfoToSyslog(userId, extraId, 
                                       macAddress, ruleNumber);
 
   /* write close log to management db */
   PutCloseToMngDb(macAddress);
+
+  /* reset the memory of MAC IP pair */
+  ResetMacIpPairs(macAddress);
 }
 
 /*******************************
@@ -146,7 +147,6 @@ int closeSession(void* pParam, int argc, char *argv[], char* colName[]){
   int ruleNumber;
   char* userId;
   char* extraId;
-  char* ipAddress;
   char* macAddress;
   int openTime;
 
@@ -155,22 +155,23 @@ int closeSession(void* pParam, int argc, char *argv[], char* colName[]){
   ruleNumber=atoi(argv[0]);
   userId=argv[1];
   extraId=argv[2];
-  ipAddress=argv[3];
-  macAddress=argv[4];
-  openTime=atoi(argv[5]);
+  macAddress=argv[3];
+  openTime=atoi(argv[4]);
 
   /* close firewall */
   CloseClientGate(ruleNumber);
-  DelCacheItem(macAddress);
+  DelCacheItem(macAddress,"");
 
   /* write close log to syslog */
-  WriteCloseToSyslog(userId, extraId, ipAddress, macAddress, openTime);
-  if(debug>0) WriteSessionInfoToSyslog(userId, extraId, ipAddress, 
-                                      macAddress, ruleNumber);
+  WriteCloseToSyslog(userId, extraId,  macAddress, openTime);
+  if(debug>0) WriteSessionInfoToSyslog(userId, extraId, macAddress, ruleNumber);
 
   /* write close log to management db */
   PutCloseToMngDb(macAddress);
 
+  /* reset the memory of MAC IP pair */
+  ResetMacIpPairs(macAddress);
+
   return 0; /* SQLITE_OK */
 }
 
@@ -195,13 +196,11 @@ int isMatchedSessionFound(char* macAddress){
   char extraId[USERMAXLN];
   int openTime;
   int checkTime;
-  char ipAddress[ADDRMAXLN];
   int ruleNumber;
 
   /* get info for the macAddress */
   return GetSessionFromWorkDb(macAddress, userId, extraId, 
-                        &openTime, &checkTime, ipAddress,
-                            &ruleNumber);
+                        &openTime, &checkTime, &ruleNumber);
 }
 
 /************************************
@@ -289,7 +288,6 @@ void removeSessionUnmatchedToIpfwRule(DB* ruleTable, DB* sessionTable){
   int retRuleTbl;
   int retSesTbl;
   int ruleNumber;
-  char ipAddress[ADDRMAXLN];
   char userId[USERMAXLN];
   char extraId[USERMAXLN];
   char macAddress[ADDRMAXLN];
@@ -323,16 +321,16 @@ void removeSessionUnmatchedToIpfwRule(DB* ruleTable, DB* sessionTable){
     else{
       /* write log and close session */
       if(!GetSessionFromWorkDb(macAddress, userId, extraId, 
-                             &openTime, &checkTime,ipAddress, &ruleNumber)){
+                             &openTime, &checkTime, &ruleNumber)){
        err_msg("ERR at %s#%d: fail to get session info",__FILE__,__LINE__);
       }else{
-       WriteCloseToSyslog(userId, extraId, ipAddress, macAddress, openTime);
+       WriteCloseToSyslog(userId, extraId, macAddress, openTime);
        PutCloseToMngDb(macAddress);
        DelSessionFromWorkDb(macAddress);
       }
 
       /* write session info to syslog */
-      if(debug>0) WriteSessionInfoToSyslog(userId, extraId, ipAddress, 
+      if(debug>0) WriteSessionInfoToSyslog(userId, extraId, 
                                           macAddress, ruleNumber);
     }
 
@@ -381,14 +379,14 @@ void  removeIpfwRuleUnmatchedToSession(DB* ruleTable, DB* sessionTable){
 
       /* remove entry in ipfw rule */
       CloseClientGate(ruleNumber);
-      DelCacheItem(macAddress);
+      DelCacheItem(macAddress,"");
 
       /* write log */
-      WriteCloseToSyslog("?", "", "?", macAddress, time(NULL));
+      WriteCloseToSyslog("?", "", macAddress, time(NULL));
       PutCloseToMngDb(macAddress);
       
       /* write session info to syslog */
-      if(debug>0) WriteSessionInfoToSyslog("?","","?",macAddress, ruleNumber);
+      if(debug>0) WriteSessionInfoToSyslog("?","", macAddress, ruleNumber);
     }
 
     /* get next rule entry */
@@ -400,22 +398,21 @@ void  removeIpfwRuleUnmatchedToSession(DB* ruleTable, DB* sessionTable){
 /******************************************
 write open message to syslog
 ******************************************/
-void writeOpenToSyslog(char* userId, char* extraId, char* ipAddress, char* macAddress){
+void writeOpenToSyslog(char* userId, char* extraId, char* macAddress){
 
   if(extraId[0]=='\0'){
-    err_msg("OPEN: user %s from %s at %s", 
-           userId, ipAddress, macAddress);
+    err_msg("OPEN: user %s at %s", 
+           userId, macAddress);
   }else{
-    err_msg("OPEN: user %s%s%s from %s at %s", 
-           userId, GetConfValue("UserIdSeparator"), extraId, 
-           ipAddress, macAddress);
+    err_msg("OPEN: user %s%s%s at %s", 
+           userId, GetConfValue("UserIdSeparator"), extraId, macAddress);
   }
 }
 
 /******************************************
 write close message to syslog
 ******************************************/
-void writeCloseToSyslog(char* userId, char* extraId, char* ipAddress, char* macAddress, int openTime){
+void writeCloseToSyslog(char* userId, char* extraId, char* macAddress, int openTime){
 
   double time_l;
   int hour, min, sec;
@@ -426,19 +423,19 @@ void writeCloseToSyslog(char* userId, char* extraId, char* ipAddress, char* macA
   sec=(time_l-hour*60*60-min*60);
 
   if(extraId[0]=='\0'){
-    err_msg("CLOS: user %s from %s at %s ( %02d:%02d:%02d )", 
-           userId, ipAddress, macAddress, hour,min,sec);
+    err_msg("CLOS: user %s at %s ( %02d:%02d:%02d )", 
+           userId, macAddress, hour,min,sec);
   }else{
-    err_msg("CLOS: user %s%s%s from %s at %s ( %02d:%02d:%02d )", 
+    err_msg("CLOS: user %s%s%s at %s ( %02d:%02d:%02d )", 
            userId, GetConfValue("UserIdSeparator"), extraId, 
-           ipAddress, macAddress, hour,min,sec);
+           macAddress, hour,min,sec);
   }
 }
 
 /******************************************
 write session info message to syslog
 ******************************************/
-void writeSessionInfoToSyslog(char* userId, char* extraId, char* ipAddress, char* macAddress, int ruleNumber){
+void writeSessionInfoToSyslog(char* userId, char* extraId, char* macAddress, int ruleNumber){
 
   char detectTimeStr[WORDMAXLN];
   int ttl;
@@ -447,27 +444,59 @@ void writeSessionInfoToSyslog(char* userId, char* extraId, char* ipAddress, char
   GetMacInfoFromWorkDb(macAddress, detectTimeStr, &ttl);
 
   if(extraId[0]=='\0'){
-    err_msg("INFO: user=%s ipaddr=%s macaddr=%s "
+    err_msg("INFO: user=%s macaddr=%s "
            "ipfwrule=%d ttl=%d lastcheck=%s", 
-           userId, ipAddress, macAddress, ruleNumber, ttl, detectTimeStr);
+           userId, macAddress, ruleNumber, ttl, detectTimeStr);
   }else{
-    err_msg("INFO: user=%s%s%s ipaddr=%s macaddr=%s "
+    err_msg("INFO: user=%s%s%s macaddr=%s "
            "ipfwrule=%d ttl=%d lastcheck=%s", 
            userId, GetConfValue("UserIdSeparator"), extraId, 
-           ipAddress, macAddress, ruleNumber, ttl, detectTimeStr);
+           macAddress, ruleNumber, ttl, detectTimeStr);
   }
 }
 
+/**********************************************
+Memorize the MAC&IP address pair to DB and log
+**********************************************/
+void setMacIpPair(char* macAddress, char* ipAddress, char* userId, char* extraId){
+  
+  /* if the pair is not found in work db, record it */ 
+  if(!IsFoundMacIpPairInWorkDb(macAddress, ipAddress)){
+    PutMacIpPairToWorkDb(macAddress, ipAddress);
+
+    /* record the pair to management db */
+    PutMacIpPairToMngDb(macAddress, ipAddress);
+
+    /* write to syslog */
+    if(isNull(extraId)){
+      err_msg("FIND: user %s from %s at %s", userId, ipAddress, macAddress);
+    }else{
+      err_msg("FIND: user %s%s%s from %s at %s", 
+             userId, GetConfValue("UserIdSeparator"), extraId, 
+             ipAddress, macAddress);
+    }
+  }
+}
+
+/**********************************
+Reset the MAC&IP address pair in DB
+***********************************/
+void resetMacIpPairs(char* macAddress){
+
+  /* remove the all-pairs having the MAC from work db */
+  DelMacIpPairsInWorkDb(macAddress);
+}
+
 
 /**************************************************
  routines for debugging output
  *************************************************/
 
-int AddSession(char* macAddress, char* ipAddress, char* userId, char* extraId){
+int AddSession(char* macAddress, char* userId, char* extraId){
   int ret;
-  if(debug>1) err_msg("DEBUG:=>addSession(%s,%s,%s,%s)",
-                     macAddress, ipAddress, userId, extraId);
-  ret = addSession(macAddress, ipAddress, userId, extraId);
+  if(debug>1) err_msg("DEBUG:=>addSession(%s,%s,%s)",
+                     macAddress, userId, extraId);
+  ret = addSession(macAddress, userId, extraId);
   if(debug>1) err_msg("DEBUG:(%d)<=addSession( )",ret);
   return ret;
 }
@@ -513,21 +542,21 @@ void CloseUnmatchSessions(void){
   if(debug>1) err_msg("DEBUG:<=closeUnmatchSessions( )");
 }
 
-void WriteOpenToSyslog(char* userId, char* extraId, char* ipAddress, char* macAddress){
-  if(debug>1) err_msg("DEBUG:=>writeOpenToSyslog(%s,%s,%s,%s)", userId, extraId, ipAddress, macAddress);
-  writeOpenToSyslog(userId, extraId, ipAddress, macAddress);
+void WriteOpenToSyslog(char* userId, char* extraId, char* macAddress){
+  if(debug>1) err_msg("DEBUG:=>writeOpenToSyslog(%s,%s,%s)", userId, extraId, macAddress);
+  writeOpenToSyslog(userId, extraId, macAddress);
   if(debug>1) err_msg("DEBUG:<=writeOpenToSyslog( )");
 }
 
-void WriteCloseToSyslog(char* userId, char* extraId, char* ipAddress, char* macAddress, int openTime){
-  if(debug>1) err_msg("DEBUG:=>writeCloseToSyslog(%s,%s,%s,%s,%d)", userId, extraId, ipAddress, macAddress, openTime);
-  writeCloseToSyslog(userId, extraId, ipAddress, macAddress, openTime);
+void WriteCloseToSyslog(char* userId, char* extraId, char* macAddress, int openTime){
+  if(debug>1) err_msg("DEBUG:=>writeCloseToSyslog(%s,%s,%s,%d)", userId, extraId, macAddress, openTime);
+  writeCloseToSyslog(userId, extraId, macAddress, openTime);
   if(debug>1) err_msg("DEBUG:<=writeCloseToSyslog( )");
 }
 
-void WriteSessionInfoToSyslog(char* userId, char* extraId, char* ipAddress, char* macAddress, int ruleNumber){
-  if(debug>1) err_msg("DEBUG:=>writeSessionInfoToSyslog(%s,%s,%s,%s,%d)", userId, extraId, ipAddress, macAddress, ruleNumber);
-  writeSessionInfoToSyslog(userId, extraId, ipAddress, macAddress, ruleNumber);
+void WriteSessionInfoToSyslog(char* userId, char* extraId, char* macAddress, int ruleNumber){
+  if(debug>1) err_msg("DEBUG:=>writeSessionInfoToSyslog(%s,%s,%s,%d)", userId, extraId, macAddress, ruleNumber);
+  writeSessionInfoToSyslog(userId, extraId, macAddress, ruleNumber);
   if(debug>1) err_msg("DEBUG:<=writeSessionInfoToSyslog( )");
 }
 
@@ -545,6 +574,18 @@ void RemoveIpfwRuleUnmatchedToSession(DB* ruleTable, DB* sessionTable){
 
 }
 
+void SetMacIpPair(char* macAddress, char* ipAddress, char* userId, char* extraId){
+  if(debug>1) err_msg("DEBUG:=>setMacIpPair(%s,%s,%s,%s)",
+                     macAddress, ipAddress, userId, extraId);
+  setMacIpPair(macAddress, ipAddress, userId, extraId);
+  if(debug>1) err_msg("DEBUG:<=setMacIpPair( )");
+}
+
+void ResetMacIpPairs(char* macAddress){
+  if(debug>1) err_msg("DEBUG:=>resetMacIpPairs(%s)", macAddress);
+  resetMacIpPairs(macAddress);
+  if(debug>1) err_msg("DEBUG:<=resetMacIpPairs( )");
+}
 
 /********************testmain********************
 void testmain(){
index 661daac..c341673 100644 (file)
@@ -52,10 +52,13 @@ int initWorkDb(void){
   char *createCmd1="CREATE TABLE IF NOT EXISTS sessionmd "
     "(macAddress TEXT PRIMARY KEY, "
     "userId TEXT, extraId TEXT, openTime INTEGER, checkTime INTEGER, "
-    "ipAddress TEXT, ruleNumber INTEGER)";
+    "ruleNumber INTEGER)";
   char *createCmd2="CREATE TABLE IF NOT EXISTS macinfo "
     "(macAddress TEXT PRIMARY KEY ON CONFLICT REPLACE, "
     "detectTime INTEGER, ttl INTEGER, isNat INTEGER)";
+  char *createCmd3="CREATE TABLE IF NOT EXISTS macippair "
+    "(macAddress TEXT, "
+    "ipAddress TEXT, findTime INTEGER)";
 
   /* setup static variable value for SqLite3_busy_timeout from conf */
   SetupSqliteBusyTimeoutValue();
@@ -79,6 +82,12 @@ int initWorkDb(void){
     terminateProg(0);
   }
 
+  /* create table3 */
+  if(sqlite3_exec(dbMd, createCmd3, NULL, NULL, &pErrMsg)!=SQLITE_OK){
+    err_msg("ERR at %s#%d: sqlite3_exec: %s",__FILE__,__LINE__,pErrMsg);
+    terminateProg(0);
+  }
+
   return TRUE;
 }
 
@@ -97,21 +106,21 @@ int finalizeWorkDb(void){
  insert session info to db at start     
 ************************************************************/
 int insertSessionToWorkDb(char* macAddress, char* userId, char* extraId, 
-                       char* ipAddress, int ruleNumber){
+                       int ruleNumber){
 
   int rc;
   char *pErrMsg=NULL;
 
   /* SQL INSERT COMMAND, where %x is replaced in snprintf */
   char *insertFormat="INSERT INTO sessionmd "
-    "(macAddress, userId, extraId, openTime, checkTime, ipAddress, ruleNumber) "
-    "values ('%s','%s','%s', %d, %d,'%s', %d)";
+    "(macAddress, userId, extraId, openTime, checkTime, ruleNumber) "
+    "values ('%s','%s','%s', %d, %d, %d)";
   char *insertCmd;
   int resultFlag=TRUE;
 
   /* Prepare insert command */
   insertCmd=sqlite3_mprintf(insertFormat, macAddress, userId,extraId, 
-                           time(NULL), time(NULL), ipAddress, ruleNumber);
+                           time(NULL), time(NULL), ruleNumber);
 
   /* Execute insert to sqlite */
   if((rc=sqlite3_exec(dbMd, insertCmd, NULL, NULL, &pErrMsg))!=SQLITE_OK){
@@ -154,7 +163,7 @@ int updateCheckTimeInWorkDb(char* macAddress){
 }
 
 /*************************************************************
- delete session info to db at stop     
+ delete session info in db at stop     
 *************************************************************/
 int delSessionFromWorkDb(char* macAddress){
 
@@ -177,22 +186,22 @@ int delSessionFromWorkDb(char* macAddress){
   /*memory free for sqlite3 string */
   sqlite3_free(deleteCmd);
 
-  return TRUE;
+  return resultFlag;
 }
 
 /************************************************
- get info for active session about ip addr from db  
+ get info for active session about mac addr from db  
 input = macAddress, output = others
 *************************************************/
 int getSessionFromWorkDb(char* macAddress, char* userId, char* extraId, 
-                        int* openTime, int* checkTime, char *ipAddress,
+                        int* openTime, int* checkTime, 
                         int* ruleNumber){
 
   sqlite3_stmt *stmt;
  
   /* SQL SELECT COMMAND, where %x is replaced in snprintf */
   char *selectFormat="SELECT userId, extraId, openTime, checkTime, "
-    "ipAddress, ruleNumber FROM sessionmd WHERE macAddress='%s'";
+    "ruleNumber FROM sessionmd WHERE macAddress='%s'";
   char *selectCmd;
   int resultFlag=TRUE;
 
@@ -217,15 +226,13 @@ int getSessionFromWorkDb(char* macAddress, char* userId, char* extraId,
     strncpy(extraId, (char*)sqlite3_column_text(stmt, 1), USERMAXLN);
     *openTime=(int)sqlite3_column_int(stmt, 2);
     *checkTime=(int)sqlite3_column_int(stmt, 3);
-    strncpy(ipAddress, (char*)sqlite3_column_text(stmt, 4), ADDRMAXLN);
-    *ruleNumber=(int)sqlite3_column_int(stmt, 5);
+    *ruleNumber=(int)sqlite3_column_int(stmt, 4);
     resultFlag=TRUE;
   }else{
     userId[0]='\0';
     extraId[0]='\0';
     *openTime=0;
     *checkTime=0;
-    ipAddress[0]='\0';
     *ruleNumber=0;
     resultFlag=FALSE;
   }
@@ -256,7 +263,7 @@ int delUselessSessionsInWorkDb(int delayed){
   if(!delayed) uselessLimitTime = time(NULL);
 
   /* SQL SELECT COMMAND, where %x is replaced in snprintf */
-  char *selectFormat="SELECT ruleNumber, userId, extraId, ipAddress, "
+  char *selectFormat="SELECT ruleNumber, userId, extraId, "
     "macAddress, openTime FROM sessionmd WHERE checkTime<%d";
   char *deleteFormat="DELETE FROM sessionmd WHERE checkTime<%d";
   char *selectCmd;
@@ -451,7 +458,98 @@ int isActiveRuleInWorkDb(int ruleNumber){
   return resultFlag;
 }
 
+/********************************************
+Is the MAC-IP pair found in work db
+********************************************/
+int isFoundMacIpPairInWorkDb(char* macAddress, char* ipAddress){
+  sqlite3_stmt *stmt;
+  /* SQL SELECT COMMAND, where %x is replaced in snprintf */
+  char *selectFormat="SELECT * FROM macippair "
+    " WHERE macAddress='%s' AND ipAddress='%s'";
+  char *selectCmd;
+  int resultFlag=TRUE;
 
+  /* prepare command string */
+  selectCmd=sqlite3_mprintf(selectFormat, macAddress, ipAddress);
+  
+  /* compile to internal statement */
+  if(sqlite3_prepare(dbMd, selectCmd, BUFFMAXLN, &stmt, NULL)!=SQLITE_OK){
+    resultFlag=FALSE;
+    err_msg("ERR at %s#%d: sqlite3_prepare",__FILE__,__LINE__);
+
+    /* finalize */
+    sqlite3_free(selectCmd);
+    sqlite3_finalize(stmt);
+    return FALSE;
+  }
+
+  /* get first record */
+  if(sqlite3_step(stmt)==SQLITE_ROW) resultFlag=TRUE;
+  else resultFlag=FALSE;
+
+  /* finalize */
+  sqlite3_free(selectCmd);
+  sqlite3_finalize(stmt);
+  return resultFlag;
+}
+
+
+/********************************************
+Insert MAC-IP pair to work db
+********************************************/
+int putMacIpPairToWorkDb(char* macAddress, char* ipAddress){
+  int rc;
+  char *pErrMsg=NULL;
+
+  /* SQL INSERT COMMAND, where %x is replaced in snprintf */
+  char *insertFormat="INSERT INTO macippair "
+    "(macAddress, ipAddress, findTime) "
+    "values ('%s','%s', %d)";
+  char *insertCmd;
+  int resultFlag=TRUE;
+
+  /* Prepare insert command */
+  insertCmd=sqlite3_mprintf(insertFormat, macAddress, ipAddress, time(NULL));
+
+  /* Execute insert to sqlite */
+  if((rc=sqlite3_exec(dbMd, insertCmd, NULL, NULL, &pErrMsg))!=SQLITE_OK){
+    resultFlag=FALSE;
+    err_msg("ERR at %s#%d: sqlite3_exec: %s",__FILE__,__LINE__,pErrMsg);
+  }
+
+  /*Memory free for sqlite3 string */
+  sqlite3_free(insertCmd);
+
+  return resultFlag;
+}
+
+/********************************************
+Delete the mac-ip pairs in work db for the mac
+********************************************/
+int delMacIpPairsInWorkDb(char* macAddress){
+  char *pErrMsg=NULL;
+
+  /* SQL DELETE COMMAND, where %x is replaced in mprintf */
+  char *deleteFormat="DELETE FROM macippair WHERE macAddress='%s'";
+  char *deleteCmd;
+  int resultFlag=TRUE;
+
+  /* prepare command */
+  deleteCmd=sqlite3_mprintf(deleteFormat, macAddress);
+
+  /* execute delete */
+  if(sqlite3_exec(dbMd, deleteCmd, NULL, NULL, &pErrMsg)!=SQLITE_OK){
+    resultFlag=FALSE;
+    err_msg("ERR at %s#%d: sqlite3_exec: %s",__FILE__,__LINE__,pErrMsg);
+  }
+
+  /*memory free for sqlite3 string */
+  sqlite3_free(deleteCmd);
+
+  return resultFlag;
+
+}
 
 /*********************************************************
  routines for debugging output
@@ -481,11 +579,11 @@ int FinalizeWorkDb(void){
 }
 
 int InsertSessionToWorkDb(char* macAddress, char* userId, char* extraId, 
-                       char* ipAddress, int ruleNumber){
+                        int ruleNumber){
   int ret;
-  if(debug>1) err_msg("DEBUG:=>insertSessionToWorkDb(%s,%s,%s,%s,%d)",
-                     macAddress, userId, extraId, ipAddress, ruleNumber);
-  ret = insertSessionToWorkDb(macAddress, userId, extraId, ipAddress, ruleNumber);
+  if(debug>1) err_msg("DEBUG:=>insertSessionToWorkDb(%s,%s,%s,%d)",
+                     macAddress, userId, extraId, ruleNumber);
+  ret = insertSessionToWorkDb(macAddress, userId, extraId, ruleNumber);
   if(debug>1) err_msg("DEBUG:(%d)<=insertSessionToWorkDb( )",ret);
   return ret;
 }
@@ -507,15 +605,13 @@ int DelSessionFromWorkDb(char* macAddress){
 }
 
 int GetSessionFromWorkDb(char* macAddress, char* userId, char* extraId, 
-                        int* openTime, int* checkTime, char *ipAddress,
-                        int* ruleNumber){
+                        int* openTime, int* checkTime, int* ruleNumber){
   int ret;
   if(debug>1) err_msg("DEBUG:=>getSessionFromWorkDb(%s)", macAddress);
   ret = getSessionFromWorkDb(macAddress, userId, extraId, openTime, 
-                              checkTime, ipAddress, ruleNumber);
-  if(debug>1) err_msg("DEBUG:(%d)<=getSessionFromWorkDb(,%s,%s,%d,%d,%s,%d)",
-                     ret,userId,extraId,*openTime,*checkTime,ipAddress,
-                     *ruleNumber);
+                              checkTime, ruleNumber);
+  if(debug>1) err_msg("DEBUG:(%d)<=getSessionFromWorkDb(,%s,%s,%d,%d,%d)",
+                     ret,userId,extraId,*openTime,*checkTime, *ruleNumber);
   return ret;
 }
 
@@ -559,3 +655,31 @@ int GetMacInfoFromWorkDb(char* macAddress, char* detectTimeStr, int* pTtl){
                      ret, detectTimeStr, *pTtl);
   return ret;
 }
+
+int IsFoundMacIpPairInWorkDb(char* macAddress, char* ipAddress){
+  int ret;
+  if(debug>1) err_msg("DEBUG:=>isFoundMacIpPairInWorkDb(%s,%s)",
+                     macAddress,ipAddress);
+  ret=isFoundMacIpPairInWorkDb(macAddress, ipAddress);
+  if(debug>1) err_msg("DEBUG:(%d)<=isfoundMacIpPairInWorkDb( )", ret);
+  return ret;
+}
+
+int PutMacIpPairToWorkDb(char* macAddress, char* ipAddress){
+  int ret;
+  if(debug>1) err_msg("DEBUG:=>putMacIpPairToWorkDb(%s,%s)",
+                     macAddress,ipAddress);
+  ret=putMacIpPairToWorkDb(macAddress, ipAddress);
+  if(debug>1) err_msg("DEBUG:(%d)<=putMacIpPairtoWorkDb( )", ret);
+  return ret;
+}
+
+
+int DelMacIpPairsInWorkDb(char* macAddress){
+  int ret;
+  if(debug>1) err_msg("DEBUG:=>delMacIpPairsInWorkDb(%s)",
+                     macAddress);
+  ret=delMacIpPairsInWorkDb(macAddress);
+  if(debug>1) err_msg("DEBUG:(%d)<=delMacIpPairsInWorkDb( )", ret);
+  return ret;
+}
index 8db0523..ab3eda3 100644 (file)
@@ -17,11 +17,15 @@ create table if not exists macaddrs(
 
 create table if not exists sessionmd(
        macAddress CHAR(18),
-       ipAddress TINYTEXT,
        gatewayName TINYTEXT,
        openTime DATETIME,
        closeTime DATETIME);
 
+create table if not exists macippair(
+       macAddress CHAR(18),
+       ipAddress TINYTEXT,
+       findTime DATETIME);
+
 create table if not exists macmodify(
        userId TINYTEXT,
        extraId TINYTEXT,
@@ -40,8 +44,8 @@ create view sessionview as select
        device,
        openTime,
        closeTime,
-       gatewayName,
-       ipAddress
+       gatewayName 
        from macaddrs,sessionmd 
        where macaddrs.macAddress=sessionmd.macAddress 
        and entryDate<openTime and openTime<limitDate;
+