OSDN Git Service

modified comments
[opengatem/opengatem.git] / mngsrc / workdb.c
1 /**************************************************
2 OpengateM - MAC address authentication system 
3    module for local work database (SQLite3)
4
5 Copyright (C) 2011 Opengate Project Team
6 Written by Yoshiaki Watanabe
7
8 This program is free software; you can redistribute it and/or
9 modify it under the terms of the GNU General Public License
10 as published by the Free Software Foundation; either version 2
11 of the License, or (at your option) any later version.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21
22 Email: watanaby@is.saga-u.ac.jp
23 **************************************************/
24 #include "opengatemmng.h"
25 #include <sqlite3.h>
26
27 static int sqliteBusyTimeout=100;  /* value used in sqite3_busy_timeout() */
28
29 /********************************************************************/
30 /* set static variable for sqlite-busy-timeout defined in conf file */
31 /********************************************************************/
32 int setupSqliteBusyTimeoutValue(void){
33
34   char *str;
35   
36   /* if set in conf, use the value. if not, use the above default. */
37   str=GetConfValue("SqliteBusyTimeout");
38   if(str!=NULL) sqliteBusyTimeout=atoi(str);
39
40   return sqliteBusyTimeout;
41 }
42
43 /**********************************************/
44 /* initialize work db implemented with sqlite */
45 /**********************************************/
46 int initWorkDb(void){
47   char *pErrMsg=NULL;
48   sqlite3 *db;
49
50   char *createCmd1="CREATE TABLE IF NOT EXISTS maccheck "
51     "(macAddress TEXT PRIMARY KEY, "
52     "ipv4 TEXT DEFAULT '', ipv6 TEXT DEFAULT '', "
53     " pid INTEGER DEFAULT 0, ruleIpv4 INTEGER DEFAULT 0, "
54     " ruleIpv6 INTEGER DEFAULT 0, detectTime INTEGER DEFAULT 0)";
55
56   char *createCmd2="CREATE TABLE IF NOT EXISTS cookietable "
57     "(cookie TEXT PRIMARY KEY, "
58     " saveTime INTEGER DEFAULT 0,"
59     " userId TEXT DEFAULT '',"
60     " extraId TEXT DEFAULT '',"
61     " userType INTEGER DEFAULT 0,"
62     " mailDefault TEXT DEFAULT '',"
63     " macAddress TEXT DEFAULT '')";
64
65   char *createCmd3="CREATE TABLE IF NOT EXISTS sessionmd "
66     "(ipAddress TEXT PRIMARY KEY, "
67     "userId TEXT, extraId TEXT, openTime INTEGER, checkTime INTEGER, "
68     "macAddress TEXT, ruleNumber INTEGER)";
69
70   char *createCmd4="CREATE TABLE IF NOT EXISTS macinfo "
71     "(macAddress TEXT PRIMARY KEY ON CONFLICT REPLACE, "
72     "detectTime INTEGER, ttl INTEGER, isNat INTEGER)";
73
74   /* setup static variable value for SqLite3_busy_timeout from conf */
75   SetupSqliteBusyTimeoutValue();
76
77   /* Open sqlite for opengateMmng */
78   if(sqlite3_open(GetConfValue("SqliteDbMmng"),&db)!=SQLITE_OK){
79     err_msg("ERR at %s#%d: sqlite3_open",__FILE__,__LINE__);
80     sqlite3_close(db);
81     terminateProg(0);
82   }
83   sqlite3_busy_timeout(db, sqliteBusyTimeout);
84
85   /* create table1 (maccheck table in opengateMmng) */
86   if(sqlite3_exec(db, createCmd1, NULL, NULL, &pErrMsg)!=SQLITE_OK){
87     err_msg("ERR at %s#%d: sqlite3_exec: %s",__FILE__,__LINE__,pErrMsg);
88     terminateProg(0);
89   }
90
91   /* create table2 (cookietable in opengateMmng) */
92   if(sqlite3_exec(db, createCmd2, NULL, NULL, &pErrMsg)!=SQLITE_OK){
93     err_msg("ERR at %s#%d: sqlite3_exec: %s",__FILE__,__LINE__,pErrMsg);
94     terminateProg(0);
95   }
96
97   /* close opengateMmng */
98   sqlite3_close(db);
99
100   /* Open sqlite for opengateMd */
101   if(sqlite3_open(GetConfValue("SqliteDbMd"),&db)!=SQLITE_OK){
102     err_msg("ERR at %s#%d: sqlite3_open",__FILE__,__LINE__);
103     sqlite3_close(db);
104     terminateProg(0);
105   }
106   sqlite3_busy_timeout(db, sqliteBusyTimeout);
107
108   /* create table3 (sessionmd table in opengateMd) */
109   if(sqlite3_exec(db, createCmd3, NULL, NULL, &pErrMsg)!=SQLITE_OK){
110     err_msg("ERR at %s#%d: sqlite3_exec: %s",__FILE__,__LINE__,pErrMsg);
111     terminateProg(0);
112   }
113
114   /* create table4 (macinfo table in opengateMd) */
115   if(sqlite3_exec(db, createCmd4, NULL, NULL, &pErrMsg)!=SQLITE_OK){
116     err_msg("ERR at %s#%d: sqlite3_exec: %s",__FILE__,__LINE__,pErrMsg);
117     terminateProg(0);
118   }
119
120   /* close opengateMd */
121   sqlite3_close(db);
122   return TRUE;
123 }
124
125 /********************************************/
126 /* create temporary table for mac checking  */
127 /* (gather mac addresses from arp and ndp)  */
128 /********************************************/
129 int createMacCheckTableInWorkDb(void){
130
131   char *pErrMsg=NULL;
132   sqlite3 *db;
133
134   char *delCmd="DELETE FROM maccheck";
135
136   /* Open sqlite */
137   if(sqlite3_open(GetConfValue("SqliteDbMmng"),&db)!=SQLITE_OK){
138     err_msg("ERR at %s#%d: sqlite3_open",__FILE__,__LINE__);
139     sqlite3_close(db);
140     terminateProg(0);
141   }
142   sqlite3_busy_timeout(db, sqliteBusyTimeout);
143
144   /* renew mac check table */
145    if(sqlite3_exec(db, delCmd, NULL, NULL, &pErrMsg)!=SQLITE_OK){
146      err_msg("ERR at %s#%d: sqlite3_exec: %s",__FILE__,__LINE__,pErrMsg);
147      terminateProg(0);
148    }
149
150   /* get arp entry and add to mac check table */
151   Initqueue();
152   GetMacAddrListFromArp(GetConfValue("Device"));
153   AddIpv4ToMacCheckTable();
154   
155   /* get ndp entry and add to mac check table */
156   Initqueue();
157   GetMacAddrListFromNdp(GetConfValue("Device"));
158   AddIpv6ToMacCheckTable();
159   Freequeue();
160
161   sqlite3_close(db);
162   return TRUE;
163 }
164
165 /********************************************************/
166 /* add mac-ipv4 pair to mac check table                 */
167 /* execute both of update and insert commands           */
168 /* because the mac address exists or not exist in table */
169 /********************************************************/
170 int addIpv4ToMacCheckTable(void){
171
172   int rc;
173   sqlite3 *db;
174   char *pErrMsg=NULL;
175   char macAddr[ADDRMAXLN];
176   char ipAddr[ADDRMAXLN];
177   char* serverAddr="";
178   int detectTime=0;
179
180   /* SQL COMMAND, where %x is replaced in snprintf */
181   char *insertFormat="INSERT INTO maccheck "
182     " (ipv4, macAddress, detectTime) values ('%s','%s', %d)";
183
184   char *insertCmd;
185   int resultFlag=TRUE;
186
187   /* get server and remote client address */
188   serverAddr=getenv("SERVER_ADDR");
189
190   /* Open sqlite */
191   if(sqlite3_open(GetConfValue("SqliteDbMmng"),&db)!=SQLITE_OK){
192     err_msg("ERR at %s#%d: sqlite3_open",__FILE__,__LINE__);
193     sqlite3_close(db);
194     terminateProg(0);
195   }
196   sqlite3_busy_timeout(db, sqliteBusyTimeout);
197
198   /* get queued items */
199   while(Dequeue(macAddr, ipAddr)){
200
201     /* if server addr (localhost addr), ignore */
202     if(strcmp(serverAddr,ipAddr)==0)continue;
203
204     /* get detect time from md.db */
205     detectTime=GetDetectTimeFromMacinfoTable(macAddr);
206
207      /* execute insert command */
208     insertCmd=sqlite3_mprintf(insertFormat, ipAddr, macAddr, detectTime);
209     if((rc=sqlite3_exec(db, insertCmd, NULL, NULL, &pErrMsg))!=SQLITE_OK){
210       resultFlag=FALSE;
211       err_msg("ERR at %s#%d: sqlite3_exec: %s",__FILE__,__LINE__,pErrMsg);
212     }
213     sqlite3_free(insertCmd);
214   }
215   sqlite3_close(db);
216   return resultFlag;
217 }
218
219 /********************************************************/
220 /* add mac-ipv6 pair to mac check table                 */
221 /* execute both of update and insert commands           */
222 /* because the mac address exists or not exist in table */
223 /********************************************************/
224 int addIpv6ToMacCheckTable(void){
225
226   int rc;
227   sqlite3 *db;
228   char *pErrMsg=NULL;
229   char macAddr[ADDRMAXLN];
230   char ipAddr[ADDRMAXLN];
231   char* serverAddr="";
232   int detectTime=0;
233
234   /* get server and remote client address */
235   serverAddr=getenv("SERVER_ADDR");
236
237   /* SQL COMMAND, where %x is replaced in snprintf */
238   char *updateFormat="UPDATE maccheck "
239     " SET ipv6='%s',detectTime=%d where macAddress='%s'";
240   char *insertFormat="INSERT INTO maccheck "
241     " (ipv6, macAddress, detectTime) values ('%s','%s', %d)";
242
243   char *updateCmd;
244   char *insertCmd;
245   int resultFlag=TRUE;
246
247   /* Open sqlite */
248   if(sqlite3_open(GetConfValue("SqliteDbMmng"),&db)!=SQLITE_OK){
249     err_msg("ERR at %s#%d: sqlite3_open",__FILE__,__LINE__);
250     sqlite3_close(db);
251     terminateProg(0);
252   }
253   sqlite3_busy_timeout(db, sqliteBusyTimeout);
254
255   /* get queued items */
256   while(Dequeue(macAddr, ipAddr)){
257
258     /* if server addr, ignore */
259     if(strcmp(serverAddr,ipAddr)==0)continue;
260
261     /* get detect time from md.db */
262     detectTime=GetDetectTimeFromMacinfoTable(macAddr);
263
264     /* execute update command */
265     updateCmd=sqlite3_mprintf(updateFormat, ipAddr, detectTime, macAddr);
266     if((rc=sqlite3_exec(db, updateCmd, NULL, NULL, &pErrMsg))!=SQLITE_OK){
267
268       /* if failed, execute insert command */
269       insertCmd=sqlite3_mprintf(insertFormat, ipAddr, macAddr, detectTime);
270       if((rc=sqlite3_exec(db, insertCmd, NULL, NULL, &pErrMsg))!=SQLITE_OK){
271         resultFlag=FALSE;
272         err_msg("ERR at %s#%d: sqlite3_exec: %s",__FILE__,__LINE__,pErrMsg);
273       }
274       sqlite3_free(insertCmd);
275     }
276     sqlite3_free(updateCmd);
277   }
278   sqlite3_close(db);
279   return resultFlag;
280 }
281
282
283 /***********************************************************************/
284 /* get maccheck table row                                              */
285 /* at first call, query is done and the first row is returned          */
286 /* and from second call, next row of previous query is returned        */
287 /* this function should be called continuously until false is returned */
288 /***********************************************************************/
289 int getNextRowInMacCheckTable(char* macAddress, char* ipv4, char* ipv6){
290
291   static sqlite3_stmt *stmt=NULL;
292   static sqlite3 *db;
293
294   /* SQL SELECT COMMAND, where %x is replaced in snprintf */
295   /* get info order by detecting time */
296   char *selectCmd="SELECT macAddress,ipv4,ipv6 "
297     " FROM maccheck order by detectTime desc ";
298   int resultFlag=TRUE;
299
300   /* set default */
301   *macAddress='\0';
302   *ipv4='\0';
303   *ipv6='\0';
304
305   /* execute at the first call of this func */
306   /* from second call, query is not done and query result in first call is used */  
307   if(stmt==NULL){
308
309     /* Open sqlite */
310     if(sqlite3_open(GetConfValue("SqliteDbMmng"),&db)!=SQLITE_OK){
311       err_msg("ERR at %s#%d: sqlite3_open",__FILE__,__LINE__);
312       sqlite3_close(db);
313       terminateProg(0);
314     }
315     sqlite3_busy_timeout(db, sqliteBusyTimeout);
316
317     /* compile to internal statement */
318     if(sqlite3_prepare(db, selectCmd, BUFFMAXLN, &stmt, NULL)!=SQLITE_OK){
319       resultFlag=FALSE;
320       err_msg("ERR at %s#%d: sqlite3_prepare",__FILE__,__LINE__);
321       
322       /* finalize */
323       sqlite3_finalize(stmt);
324       sqlite3_close(db);
325       terminateProg(0);
326     }
327   }
328
329   /* get a record (the query result is held until next call of this func) */
330   if(sqlite3_step(stmt)==SQLITE_ROW){
331     strlcpy(macAddress, (char*)sqlite3_column_text(stmt, 0), ADDRMAXLN);
332     strlcpy(ipv4, (char*)sqlite3_column_text(stmt, 1), ADDRMAXLN);
333     strlcpy(ipv6, (char*)sqlite3_column_text(stmt, 2), ADDRMAXLN);
334     resultFlag=TRUE;
335   }
336   
337   /* if not get record, clear the query result and return false */
338   else{
339     sqlite3_finalize(stmt);
340     sqlite3_close(db);
341     resultFlag=FALSE;
342   }
343
344   return resultFlag;
345 }
346
347 /*******************************************************/
348 /* get info from db input=macAddress, output=ipv4,ipv6 */
349 /*******************************************************/
350 int getIpFromMacCheckTable(char* macAddress, char* ipv4, char* ipv6){
351
352   sqlite3_stmt *stmt=NULL;
353   sqlite3 *db;
354
355   /* SQL SELECT COMMAND, where %x is replaced in snprintf */
356   char* selectFormat="SELECT ipv4,ipv6 "
357     " FROM maccheck where macAddress='%s'";
358   int resultFlag=TRUE;
359   char* selectCmd; 
360
361   /* set default */
362   *ipv4='\0';
363   *ipv6='\0';
364
365   /* Open sqlite */
366   if(sqlite3_open(GetConfValue("SqliteDbMmng"),&db)!=SQLITE_OK){
367     err_msg("ERR at %s#%d: sqlite3_open",__FILE__,__LINE__);
368     sqlite3_close(db);
369     terminateProg(0);
370   }
371   sqlite3_busy_timeout(db, sqliteBusyTimeout);
372
373   /* prepare execute command */
374   selectCmd=sqlite3_mprintf(selectFormat, macAddress);
375
376   /* compile to internal statement */
377   if(sqlite3_prepare(db, selectCmd, BUFFMAXLN, &stmt, NULL)!=SQLITE_OK){
378     resultFlag=FALSE;
379     err_msg("ERR at %s#%d: sqlite3_prepare",__FILE__,__LINE__);
380     
381     /* finalize */
382     sqlite3_free(selectCmd);
383     sqlite3_finalize(stmt);
384     sqlite3_close(db);
385     return FALSE;
386   }
387
388   /* get a record */
389   if(sqlite3_step(stmt)==SQLITE_ROW){
390     strlcpy(ipv4, (char*)sqlite3_column_text(stmt, 0), ADDRMAXLN);
391     strlcpy(ipv6, (char*)sqlite3_column_text(stmt, 1), ADDRMAXLN);
392     resultFlag=TRUE;
393   }
394   
395   /* if not get record, return false */
396   else{
397     resultFlag=FALSE;
398   }
399
400   /* finalize */
401   sqlite3_free(selectCmd);
402   sqlite3_finalize(stmt);
403   sqlite3_close(db);
404   return resultFlag;
405 }
406
407 /*****************************************************/
408 /* get pid and rule number from maccheck table in db */
409 /* macAddress:(input),pid,ruleIpv4,ruleIpv6:(output) */
410 /*****************************************************/
411 int getPidFromMacCheckTable(char* macAddress, int* pid, int* ruleIpv4, int* ruleIpv6){
412   sqlite3_stmt *stmt=NULL;
413   sqlite3 *db;
414
415   /* SQL SELECT COMMAND, where %x is replaced in snprintf */
416   char* selectFormat="SELECT pid,ruleIpv4,ruleIpv6 "
417     " FROM maccheck where macAddress='%s'";
418   int resultFlag=TRUE;
419   char* selectCmd; 
420
421   /* set default */
422   *pid=0;
423   *ruleIpv4=0;
424   *ruleIpv6=0;
425
426   /* Open sqlite */
427   if(sqlite3_open(GetConfValue("SqliteDbMmng"),&db)!=SQLITE_OK){
428     err_msg("ERR at %s#%d: sqlite3_open",__FILE__,__LINE__);
429     sqlite3_close(db);
430     terminateProg(0);
431   }
432   sqlite3_busy_timeout(db, sqliteBusyTimeout);
433
434   /* prepare execute command */
435   selectCmd=sqlite3_mprintf(selectFormat, macAddress);
436
437   /* compile to internal statement */
438   if(sqlite3_prepare(db, selectCmd, BUFFMAXLN, &stmt, NULL)!=SQLITE_OK){
439     resultFlag=FALSE;
440     err_msg("ERR at %s#%d: sqlite3_prepare",__FILE__,__LINE__);
441     
442     /* finalize */
443     sqlite3_free(selectCmd);
444     sqlite3_finalize(stmt);
445     sqlite3_close(db);
446     return FALSE;
447   }
448
449   /* get a record */
450   if(sqlite3_step(stmt)==SQLITE_ROW){
451     *pid = (int)sqlite3_column_int(stmt, 0);
452     *ruleIpv4 = (int)sqlite3_column_int(stmt, 1);
453     *ruleIpv6 = (int)sqlite3_column_int(stmt, 2);
454     resultFlag=TRUE;
455   }
456   
457   /* if not get record, return false */
458   else{
459     resultFlag=FALSE;
460   }
461
462   /* finalize */
463   sqlite3_free(selectCmd);
464   sqlite3_finalize(stmt);
465   sqlite3_close(db);
466   return resultFlag;
467 }
468
469 /****************************************************/
470 /* save pid and rule number to maccheck table in db */
471 /****************************************************/
472 int savePidToMacCheckTable(char* macAddress, int pid, int ruleIpv4, int ruleIpv6){
473   int rc;
474   sqlite3 *db;
475   char *pErrMsg=NULL;
476
477   /* SQL COMMAND, where %x is replaced in snprintf */
478   char *updateFormat="UPDATE maccheck "
479     " SET pid=%d, ruleIpv4=%d, ruleIpv6=%d where macAddress='%s'";
480   char *updateCmd;
481   int resultFlag=TRUE;
482
483   /* Open sqlite */
484   if(sqlite3_open(GetConfValue("SqliteDbMmng"),&db)!=SQLITE_OK){
485     err_msg("ERR at %s#%d: sqlite3_open",__FILE__,__LINE__);
486     sqlite3_close(db);
487     terminateProg(0);
488   }
489   sqlite3_busy_timeout(db, sqliteBusyTimeout);
490
491   /* prepare execute update command */
492   updateCmd=sqlite3_mprintf(updateFormat, pid,
493                             ruleIpv4, ruleIpv6, macAddress);
494   if((rc=sqlite3_exec(db, updateCmd, NULL, NULL, &pErrMsg))!=SQLITE_OK){
495     resultFlag=FALSE;
496     err_msg("ERR at %s#%d: sqlite3_exec: %s",__FILE__,__LINE__,pErrMsg);
497   }
498
499   /* finalize */
500   sqlite3_free(updateCmd);
501   sqlite3_close(db);
502   return resultFlag;
503 }
504
505 /****************************************************/
506 /* get detect time of mac from macinfo table in db  */
507 /****************************************************/
508 int getDetectTimeFromMacinfoTable(char* macAddress){
509
510   sqlite3_stmt *stmt=NULL;
511   sqlite3 *db;
512   int detectTime=0;
513
514   /* SQL SELECT COMMAND, where %x is replaced in snprintf */
515   char* selectFormat="SELECT detectTime "
516     " FROM macinfo where macAddress='%s'";
517   int resultFlag=TRUE;
518   char* selectCmd; 
519
520   /* Open sqlite */
521   if(sqlite3_open(GetConfValue("SqliteDbMd"),&db)!=SQLITE_OK){
522     err_msg("ERR at %s#%d: sqlite3_open",__FILE__,__LINE__);
523     sqlite3_close(db);
524     return 0;
525   }
526   sqlite3_busy_timeout(db, sqliteBusyTimeout);
527
528   /* prepare execute command */
529   selectCmd=sqlite3_mprintf(selectFormat, macAddress);
530
531   /* compile to internal statement */
532   if(sqlite3_prepare(db, selectCmd, BUFFMAXLN, &stmt, NULL)!=SQLITE_OK){
533     resultFlag=FALSE;
534     err_msg("ERR at %s#%d: sqlite3_prepare",__FILE__,__LINE__);
535     
536     /* finalize */
537     sqlite3_free(selectCmd);
538     sqlite3_finalize(stmt);
539     sqlite3_close(db);
540     return FALSE;
541   }
542
543   /* get a record */
544   if(sqlite3_step(stmt)==SQLITE_ROW){
545     detectTime = (int)sqlite3_column_int(stmt, 0);
546   }
547
548   /* finalize */
549   sqlite3_free(selectCmd);
550   sqlite3_finalize(stmt);
551   sqlite3_close(db);
552   return detectTime;
553 }
554
555 /*********************************************/
556 /* the cookie is found in db or not found    */
557 /* in: cookie, userType; out: userId,extraId */
558 /*********************************************/
559 int isCookieFoundInWorkDb(char* cookie, char* userId, char* extraId, int userType){
560   sqlite3_stmt *stmt=NULL;
561   sqlite3 *db;
562
563   /* SQL SELECT COMMAND, where %x is replaced in snprintf */
564   char* selectFormat="SELECT userId,extraId "
565     " FROM cookietable WHERE cookie='%s' and userType=%d" ;
566   int resultFlag=TRUE;
567   char* selectCmd; 
568
569   /* Open sqlite */
570   if(sqlite3_open(GetConfValue("SqliteDbMmng"),&db)!=SQLITE_OK){
571     err_msg("ERR at %s#%d: sqlite3_open",__FILE__,__LINE__);
572     sqlite3_close(db);
573     return FALSE;
574   }
575   sqlite3_busy_timeout(db, sqliteBusyTimeout);
576
577   /* prepare execute command */
578   selectCmd=sqlite3_mprintf(selectFormat, cookie, userType);
579
580   /* compile to internal statement */
581   if(sqlite3_prepare(db, selectCmd, BUFFMAXLN, &stmt, NULL)!=SQLITE_OK){
582     resultFlag=FALSE;
583     err_msg("ERR at %s#%d: sqlite3_prepare",__FILE__,__LINE__);
584     
585     /* finalize */
586     sqlite3_free(selectCmd);
587     sqlite3_finalize(stmt);
588     sqlite3_close(db);
589     return FALSE;
590   }
591
592   /* get a record */
593   if(sqlite3_step(stmt)==SQLITE_ROW){
594     strlcpy(userId, (char*)sqlite3_column_text(stmt, 0), USERMAXLN);
595     strlcpy(extraId, (char*)sqlite3_column_text(stmt, 1), USERMAXLN);
596     resultFlag=TRUE;
597   }
598   else resultFlag=FALSE;
599
600   /* finalize */
601   sqlite3_free(selectCmd);
602   sqlite3_finalize(stmt);
603   sqlite3_close(db);
604   return resultFlag;
605 }
606
607 /***************************************************/
608 /* is session for the mac found in table sessionmd */
609 /***************************************************/
610 int isSessionFoundInSessionTable(char* macAddress){
611
612   sqlite3_stmt *stmt=NULL;
613   sqlite3 *db;
614   int  count=0;
615
616   /* SQL SELECT COMMAND, where %x is replaced in snprintf */
617   char* selectFormat="SELECT count(*) "
618     " FROM sessionmd where macAddress='%s' limit 1";
619   int resultFlag=TRUE;
620   char* selectCmd; 
621
622   /* Open sqlite */
623   if(sqlite3_open(GetConfValue("SqliteDbMd"),&db)!=SQLITE_OK){
624     err_msg("ERR at %s#%d: sqlite3_open",__FILE__,__LINE__);
625     sqlite3_close(db);
626     return 0;
627   }
628   sqlite3_busy_timeout(db, sqliteBusyTimeout);
629
630   /* prepare execute command */
631   selectCmd=sqlite3_mprintf(selectFormat, macAddress);
632
633   /* compile to internal statement */
634   if(sqlite3_prepare(db, selectCmd, BUFFMAXLN, &stmt, NULL)!=SQLITE_OK){
635     resultFlag=FALSE;
636     err_msg("ERR at %s#%d: sqlite3_prepare",__FILE__,__LINE__);
637     
638     /* finalize */
639     sqlite3_free(selectCmd);
640     sqlite3_finalize(stmt);
641     sqlite3_close(db);
642     return 0;
643   }
644
645   /* get a record */
646   if(sqlite3_step(stmt)==SQLITE_ROW){
647     count = (int)sqlite3_column_int(stmt, 0);
648   }
649
650   /* finalize */
651   sqlite3_free(selectCmd);
652   sqlite3_finalize(stmt);
653   sqlite3_close(db);
654   return count;
655 }
656
657
658 /*******************************************************/
659 /* save cookie(sended to client) to cookie table in db */ 
660 /*******************************************************/
661 int saveCookieToWorkDb(char* cookie, char* userId, char* extraId, int userType){
662   int rc;
663   sqlite3 *db;
664   char *pErrMsg=NULL;
665
666   /* SQL COMMAND */
667   char* delFormat="DELETE FROM cookietable where saveTime < %d";
668   char* delCmd;
669   char* insertFormat="INSERT INTO cookietable "
670     " (cookie, saveTime, userId, extraId, userType) "
671     " values ('%s', %d, '%s', '%s', %d)";
672   char* insertCmd;
673   int resultFlag=TRUE;
674
675   /* Open sqlite */
676   if(sqlite3_open(GetConfValue("SqliteDbMmng"),&db)!=SQLITE_OK){
677     err_msg("ERR at %s#%d: sqlite3_open",__FILE__,__LINE__);
678     sqlite3_close(db);
679     terminateProg(0);
680   }
681   sqlite3_busy_timeout(db, sqliteBusyTimeout);
682
683   /* execute delete command to delete items before 24 hours */
684   delCmd=sqlite3_mprintf(delFormat, time(NULL)-(60*60*24));
685   if((rc=sqlite3_exec(db, delCmd, NULL, NULL, &pErrMsg))!=SQLITE_OK){
686     resultFlag=FALSE;
687     err_msg("ERR at %s#%d: sqlite3_exec: %s",__FILE__,__LINE__,pErrMsg);
688   }
689
690   /* execute insert command */
691   insertCmd=sqlite3_mprintf(insertFormat, cookie, time(NULL), userId, extraId, userType);
692   if((rc=sqlite3_exec(db, insertCmd, NULL, NULL, &pErrMsg))!=SQLITE_OK){
693     resultFlag=FALSE;
694     err_msg("ERR at %s#%d: sqlite3_exec: %s",__FILE__,__LINE__,pErrMsg);
695   }
696
697   /* finalize */
698   sqlite3_free(delCmd);
699   sqlite3_free(insertCmd);
700   sqlite3_close(db);
701   return resultFlag;
702 }
703
704 /********************************************/
705 /* save mac address corresponding to cookie */
706 /* to cookie table in db                    */
707 /********************************************/
708 int saveMacForCookieToWorkDb(char* cookie, char* macAddress){
709   int rc;
710   sqlite3 *db;
711   char *pErrMsg=NULL;
712
713   /* SQL COMMAND */
714   char* updateFormat="UPDATE cookietable "
715     " SET macAddress='%s' where cookie='%s'";
716   char* updateCmd;
717   int resultFlag=TRUE;
718
719   /* Open sqlite */
720   if(sqlite3_open(GetConfValue("SqliteDbMmng"),&db)!=SQLITE_OK){
721     err_msg("ERR at %s#%d: sqlite3_open",__FILE__,__LINE__);
722     sqlite3_close(db);
723     terminateProg(0);
724   }
725   sqlite3_busy_timeout(db, sqliteBusyTimeout);
726
727   /* execute update command */
728   updateCmd=sqlite3_mprintf(updateFormat, macAddress, cookie);
729   if((rc=sqlite3_exec(db, updateCmd, NULL, NULL, &pErrMsg))!=SQLITE_OK){
730     resultFlag=FALSE;
731     err_msg("ERR at %s#%d: sqlite3_exec: %s",__FILE__,__LINE__,pErrMsg);
732   }
733
734   /* finalize */
735   sqlite3_free(updateCmd);
736   sqlite3_close(db);
737   return resultFlag;
738 }
739
740 /*****************************************************/
741 /* save mail address default corresponding to cookie */
742 /* to cookie table in db                             */
743 /*****************************************************/
744 int saveMailDefalutForCookieToWorkDb(char* cookie, char* mailDefault){
745   int rc;
746   sqlite3 *db;
747   char *pErrMsg=NULL;
748
749   /* SQL COMMAND */
750   char* updateFormat="UPDATE cookietable "
751     " SET mailDefault='%s' where cookie='%s'";
752   char* updateCmd;
753   int resultFlag=TRUE;
754
755   /* Open sqlite */
756   if(sqlite3_open(GetConfValue("SqliteDbMmng"),&db)!=SQLITE_OK){
757     err_msg("ERR at %s#%d: sqlite3_open",__FILE__,__LINE__);
758     sqlite3_close(db);
759     terminateProg(0);
760   }
761   sqlite3_busy_timeout(db, sqliteBusyTimeout);
762
763   /* execute update command */
764   updateCmd=sqlite3_mprintf(updateFormat, mailDefault, cookie);
765   if((rc=sqlite3_exec(db, updateCmd, NULL, NULL, &pErrMsg))!=SQLITE_OK){
766     resultFlag=FALSE;
767     err_msg("ERR at %s#%d: sqlite3_exec: %s",__FILE__,__LINE__,pErrMsg);
768   }
769
770   /* finalize */
771   sqlite3_free(updateCmd);
772   sqlite3_close(db);
773   return resultFlag;
774 }
775
776 /*******************************************/
777 /* get maildefault corresponding to cookie */
778 /* from cookie table in db                 */
779 /*******************************************/
780 int getMailDefaultFromWorkDb(char* cookie, char* mailDefault){
781   sqlite3_stmt *stmt=NULL;
782   sqlite3 *db;
783
784   /* SQL SELECT COMMAND, where %x is replaced in snprintf */
785   char* selectFormat="SELECT mailDefault "
786     " FROM cookietable WHERE cookie='%s'" ;
787   int resultFlag=TRUE;
788   char* selectCmd; 
789
790   /* Open sqlite */
791   if(sqlite3_open(GetConfValue("SqliteDbMmng"),&db)!=SQLITE_OK){
792     err_msg("ERR at %s#%d: sqlite3_open",__FILE__,__LINE__);
793     sqlite3_close(db);
794     return FALSE;
795   }
796   sqlite3_busy_timeout(db, sqliteBusyTimeout);
797
798   /* prepare execute command */
799   selectCmd=sqlite3_mprintf(selectFormat, cookie);
800
801   /* compile to internal statement */
802   if(sqlite3_prepare(db, selectCmd, BUFFMAXLN, &stmt, NULL)!=SQLITE_OK){
803     resultFlag=FALSE;
804     err_msg("ERR at %s#%d: sqlite3_prepare",__FILE__,__LINE__);
805     
806     /* finalize */
807     sqlite3_free(selectCmd);
808     sqlite3_finalize(stmt);
809     sqlite3_close(db);
810     return FALSE;
811   }
812
813   /* get a record */
814   if(sqlite3_step(stmt)==SQLITE_ROW){
815     strlcpy(mailDefault, (char*)sqlite3_column_text(stmt, 0), USERMAXLN);
816     resultFlag=TRUE;
817   }
818   else resultFlag=FALSE;
819
820   /* finalize */
821   sqlite3_free(selectCmd);
822   sqlite3_finalize(stmt);
823   sqlite3_close(db);
824   return resultFlag;
825 }
826
827 /************************************************/
828 /* read mac address corresponding to cookie     */
829 /* in cookie table in work db                   */
830 /************************************************/
831 int loadMacForCookieFromWorkDb(char* cookie, char* macAddress){
832   sqlite3_stmt *stmt=NULL;
833   sqlite3 *db;
834
835   /* SQL SELECT COMMAND, where %x is replaced in snprintf */
836   char* selectFormat="SELECT macAddress "
837     " FROM cookietable WHERE cookie='%s'" ;
838   int resultFlag=TRUE;
839   char* selectCmd; 
840
841   /* Open sqlite */
842   if(sqlite3_open(GetConfValue("SqliteDbMmng"),&db)!=SQLITE_OK){
843     err_msg("ERR at %s#%d: sqlite3_open",__FILE__,__LINE__);
844     sqlite3_close(db);
845     return FALSE;
846   }
847   sqlite3_busy_timeout(db, sqliteBusyTimeout);
848
849   /* prepare execute command */
850   selectCmd=sqlite3_mprintf(selectFormat, cookie);
851
852   /* compile to internal statement */
853   if(sqlite3_prepare(db, selectCmd, BUFFMAXLN, &stmt, NULL)!=SQLITE_OK){
854     resultFlag=FALSE;
855     err_msg("ERR at %s#%d: sqlite3_prepare",__FILE__,__LINE__);
856     
857     /* finalize */
858     sqlite3_free(selectCmd);
859     sqlite3_finalize(stmt);
860     sqlite3_close(db);
861     return FALSE;
862   }
863
864   /* get a record */
865   if(sqlite3_step(stmt)==SQLITE_ROW){
866     strlcpy(macAddress, (char*)sqlite3_column_text(stmt, 0), USERMAXLN);
867     resultFlag=TRUE;
868   }
869   else resultFlag=FALSE;
870
871   sqlite3_free(selectCmd);
872   sqlite3_finalize(stmt);
873   sqlite3_close(db);
874   return resultFlag;
875 }
876
877
878
879 /**********************************************/
880 /* is the mac address NAT                     */
881 /* (suspected info is in macinfo table in db) */
882 /*  *if db access fails, return false*        */
883 /**********************************************/
884 int isNatSuspectedInWorkDb(char* macAddr){
885
886   sqlite3 *db;
887   sqlite3_stmt *stmt;
888   int isNat;
889  
890   /* SQL SELECT COMMAND, where %x is replaced in snprintf */
891   char *selectFormat="SELECT isNat "
892  "FROM macinfo WHERE macAddress='%s'";
893   char *selectCmd;
894   int resultFlag;
895
896   /* open sqlite */
897   if(sqlite3_open(GetConfValue("SqliteDbMd"),&db)!=SQLITE_OK){
898     err_msg("ERR at %s#%d: sqlite3_open",__FILE__,__LINE__);
899     sqlite3_close(db);
900     return FALSE;
901   }
902   sqlite3_busy_timeout(db, sqliteBusyTimeout);
903
904   /* prepare command string */
905   selectCmd=sqlite3_mprintf(selectFormat, macAddr);
906   
907   /* compile to internal statement */
908   if(sqlite3_prepare(db, selectCmd, BUFFMAXLN, &stmt, NULL)!=SQLITE_OK){
909     err_msg("ERR at %s#%d: sqlite3_prepare",__FILE__,__LINE__);
910
911     /* finalize */
912     sqlite3_free(selectCmd);
913     sqlite3_finalize(stmt);
914     sqlite3_close(db);
915     return FALSE;
916   }
917
918   /* get first record */
919   if(sqlite3_step(stmt)==SQLITE_ROW){
920     isNat=(int)sqlite3_column_int(stmt, 0);
921     resultFlag=isNat;
922   }else{
923     resultFlag=FALSE;
924   }
925
926   /* finalize */
927   sqlite3_free(selectCmd);
928   sqlite3_finalize(stmt);
929   sqlite3_close(db);
930   
931   return resultFlag;
932 }
933
934
935 /*******************************************************************/
936 /* is active session for Opengate(not OpengateM) found for the mac */ 
937 /*******************************************************************/
938 int isActiveSessionFoundInOpengateSessionTable(char* macAddress){
939
940   sqlite3_stmt *stmt=NULL;
941   sqlite3 *db;
942   int  count=0;
943
944   /* SQL SELECT COMMAND, where %x is replaced in snprintf */
945   char* selectFormat="SELECT count(*) "
946     " FROM session where (clientAddr4='%s' or clientAddr6='%s') "
947     " and closeTime='-' limit 1";
948   int resultFlag=TRUE;
949   char* selectCmd; 
950
951   /* Open sqlite (failed if no opengate usage) */
952   if(sqlite3_open(GetConfValue("SqliteDb"),&db)!=SQLITE_OK){
953     sqlite3_close(db);
954     return 0;
955   }
956   sqlite3_busy_timeout(db, sqliteBusyTimeout);
957
958   /* prepare execute command */
959   selectCmd=sqlite3_mprintf(selectFormat, macAddress, macAddress);
960
961   /* compile to internal statement */
962   if(sqlite3_prepare(db, selectCmd, BUFFMAXLN, &stmt, NULL)!=SQLITE_OK){
963     resultFlag=FALSE;
964     err_msg("ERR at %s#%d: sqlite3_prepare",__FILE__,__LINE__);
965     
966     /* finalize */
967     sqlite3_free(selectCmd);
968     sqlite3_finalize(stmt);
969     sqlite3_close(db);
970     return 0;
971   }
972
973   /* get a record */
974   if(sqlite3_step(stmt)==SQLITE_ROW){
975     count = (int)sqlite3_column_int(stmt, 0);
976   }
977
978   /* finalize */
979   sqlite3_free(selectCmd);
980   sqlite3_finalize(stmt);
981   sqlite3_close(db);
982   return count;
983 }
984
985
986 /*********************************************************
987  routines for debugging output
988 *********************************************************/
989 int SetupSqliteBusyTimeoutValue(void){
990   int ret;
991   if(debug>1) err_msg("DEBUG:=>setupSqliteBusyTimeoutValue()");
992   ret=setupSqliteBusyTimeoutValue();
993   if(debug>1) err_msg("DEBUG:(%d)<=setupSqliteBusyTimeoutValue()",ret);
994   return ret;
995 }
996
997 int InitWorkDb(void){
998   int ret;
999   if(debug>1) err_msg("DEBUG:=>initWorkDb( )");
1000   ret = initWorkDb();
1001   if(debug>1) err_msg("DEBUG:(%d)<=initWorkDb( )",ret);
1002   return ret;
1003 }
1004
1005 int CreateMacCheckTableInWorkDb(void){
1006   int ret;
1007   if(debug>1) err_msg("DEBUG:=>createmacChecktableinWorkDb( )");
1008   ret = createMacCheckTableInWorkDb();
1009   if(debug>1) err_msg("DEBUG:(%d)<=createMacCheckTableInWorkDb()", ret);
1010   return ret;
1011 }
1012
1013 int AddIpv4ToMacCheckTable(void){
1014   int ret;
1015   if(debug>1) err_msg("DEBUG:=> addIpv4ToMacCheckTable( )");
1016   ret = addIpv4ToMacCheckTable();
1017   if(debug>1) err_msg("DEBUG:(%d)<= addIpv4ToMacCheckTable( )", ret);
1018   return ret;
1019 }
1020
1021 int AddIpv6ToMacCheckTable(void){
1022   int ret;
1023   if(debug>1) err_msg("DEBUG:=>addIpv6ToMacCheckTable( )");
1024   ret = addIpv6ToMacCheckTable();
1025   if(debug>1) err_msg("DEBUG:(%d)<=addIpv6ToMacCheckTable( )", ret);
1026   return ret;
1027 }
1028
1029 int GetNextRowInMacCheckTable(char* macAddress, char* ipv4, char* ipv6){
1030   int ret;
1031   if(debug>1) err_msg("DEBUG:=>getNextRowInMacCheckTable( )");
1032   ret = getNextRowInMacCheckTable(macAddress, ipv4, ipv6);
1033   if(debug>1) err_msg("DEBUG:(%d)<=getNextRowInMacCheckTable(%s,%s,%s)",
1034                       ret,macAddress,ipv4,ipv6);
1035   return ret;
1036 }
1037
1038 int GetIpFromMacCheckTable(char* macAddress, char* ipv4, char* ipv6){
1039   int ret;
1040   if(debug>1) err_msg("DEBUG:=>getIpFromMacCheckTable(%s)",macAddress);
1041   ret = getIpFromMacCheckTable(macAddress, ipv4, ipv6);
1042   if(debug>1) err_msg("DEBUG:(%d)<=getIpFromMacCheckTable(,%s,%s)",
1043                       ret,ipv4,ipv6);
1044   return ret;
1045 }
1046 int GetPidFromMacCheckTable(char* macAddress, int* pid, int* ruleIpv4, int* ruleIpv6){
1047   int ret;
1048   if(debug>1) err_msg("DEBUG:=>getPidFromMacCheckTable(%s)",macAddress);
1049   ret = getPidFromMacCheckTable(macAddress, pid, ruleIpv4, ruleIpv6);
1050   if(debug>1) err_msg("DEBUG:(%d)<=getPidFromMacCheckTable(,%d,%d,%d)",
1051                       ret,*pid,*ruleIpv4,*ruleIpv6);
1052   return ret;
1053 }
1054 int SavePidToMacCheckTable(char* macAddress, int pid, int ruleIpv4, int ruleIpv6){
1055   int ret;
1056   if(debug>1) err_msg("DEBUG:=>savePidToMacCheckTable(%s,%d,%d,%d)",
1057                       macAddress, pid, ruleIpv4, ruleIpv6);
1058   ret = savePidToMacCheckTable(macAddress, pid, ruleIpv4, ruleIpv6);
1059   if(debug>1) err_msg("DEBUG:(%d)<=savePidToMacCheckTable( )",ret);
1060   return ret;
1061 }
1062
1063 int GetDetectTimeFromMacinfoTable(char* macAddress){
1064   int ret;
1065   if(debug>1) err_msg("DEBUG:=>getDetectTimeFromMacinfoTable(%s)",macAddress);
1066   ret = getDetectTimeFromMacinfoTable(macAddress);
1067   if(debug>1) err_msg("DEBUG:(%d)<=getDetectTimeFromMacinfoTable( )",ret);
1068   return ret;
1069 }
1070 int IsSessionFoundInSessionTable(char* macAddress){
1071   int ret;
1072   if(debug>1) err_msg("DEBUG:=>isSessionFoundInSessionTable(%s)",macAddress);
1073   ret = isSessionFoundInSessionTable(macAddress);
1074   if(debug>1) err_msg("DEBUG:(%d)<=isSessionFoundInSessionTable( )",ret);
1075   return ret;
1076 }
1077
1078 int SaveCookieToWorkDb(char* cookie, char* userId, char* extraId, int userType){
1079   int ret;
1080   if(debug>1) err_msg("DEBUG:=>saveCookieToWorkDb(%s,%s,%s,%d)",cookie,userId,extraId,userType);
1081   ret = saveCookieToWorkDb(cookie,userId,extraId,userType);
1082   if(debug>1) err_msg("DEBUG:(%d)<=saveCookieToWorkDb( )",ret);
1083   return ret;
1084 }
1085
1086 int IsCookieFoundInWorkDb(char* cookie, char* userId, char* extraId, int userType){
1087   int ret;
1088   if(debug>1) err_msg("DEBUG:=> isCookieFoundInWorkDb(%s,%d)",cookie, userType);
1089   ret = isCookieFoundInWorkDb(cookie,userId,extraId,userType);
1090   if(debug>1) err_msg("DEBUG:(%d)<=isCookieFoundInWorkDb(%s,%s)",ret, userId,extraId);
1091   return ret;
1092 }
1093
1094 int GetMailDefaultFromWorkDb(char* cookie, char* mailDefault){
1095   int ret;
1096   if(debug>1) err_msg("DEBUG:=> getMailDefaultFromWorkDb(%s)",cookie);
1097   ret = getMailDefaultFromWorkDb(cookie,mailDefault);
1098   if(debug>1) err_msg("DEBUG:(%d)<=getMailDefaultFromWorkDb(%s)",ret,mailDefault);
1099   return ret;
1100 }
1101
1102 int IsNatSuspectedInWorkDb(char* macAddr){
1103   int ret;
1104   if(debug>1) err_msg("DEBUG:=>isNatSuspectedInWorkDb(%s)", macAddr);
1105   ret = isNatSuspectedInWorkDb(macAddr);
1106   if(debug>1) err_msg("DEBUG:(%d)<=isNatSuspectedInWorkDb( )", ret);
1107   return ret;
1108 }
1109
1110 int SaveMacForCookieToWorkDb(char* cookie, char* macAddress){
1111   int ret;
1112   if(debug>1) err_msg("DEBUG:=>saveMacForCookieToWorkDb(%s,%s)", cookie,macAddress);
1113   ret = saveMacForCookieToWorkDb(cookie,macAddress);
1114   if(debug>1) err_msg("DEBUG:(%d)<=saveMacForCookieToWorkDb( )", ret);
1115   return ret;
1116 }
1117
1118 int SaveMailDefalutForCookieToWorkDb(char* cookie, char* mailDefault){
1119   int ret;
1120   if(debug>1) err_msg("DEBUG:=>saveMailDefalutForCookieToWorkDb(%s,%s)", cookie,mailDefault);
1121   ret = saveMailDefalutForCookieToWorkDb(cookie,mailDefault);
1122   if(debug>1) err_msg("DEBUG:(%d)<=saveMailDefalutForCookieToWorkDb( )", ret);
1123   return ret;
1124 }
1125
1126
1127 int LoadMacForCookieFromWorkDb(char* cookie, char* macAddress){
1128   int ret;
1129   if(debug>1) err_msg("DEBUG:=>loadMacForCookieFromWorkDb(%s)", cookie);
1130   ret = loadMacForCookieFromWorkDb(cookie,macAddress);
1131   if(debug>1) err_msg("DEBUG:(%d)<=loadMacForCookieFromWorkDb(%s)", ret, macAddress);
1132   return ret;
1133 }
1134
1135 int IsActiveSessionFoundInOpengateSessionTable(char* macAddress){
1136   int ret;
1137   if(debug>1) err_msg("DEBUG:=>isActiveSessionFoundInOpengateSessionTable(%s)", macAddress);
1138   ret = isActiveSessionFoundInOpengateSessionTable(macAddress);
1139   if(debug>1) err_msg("DEBUG:(%d)<=isActiveSessionFoundInOpengateSessionTable( )", ret);
1140   return ret;
1141 }