1 /**************************************************
2 OpengateM - MAC address authentication system
3 module for Communication through CGI
5 Copyright (C) 2011 Opengate Project Team
6 Written by Yoshiaki Watanabe
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.
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.
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.
22 Email: watanaby@is.saga-u.ac.jp
24 Programmed by Yoshiaki WATANABE
25 **************************************************/
27 #include "opengatemmng.h"
29 /* convert one-char-hex "a" to one-number 0Xa */
30 #define hex2num(x) ((x)>='A' ? ((x) & 0XDF) - 'A' +10 : ((x) - '0'))
32 void split(char content[], char *name[], char *value[], char *next[]);
33 void decode(char *string);
35 char macAddress[ADDRMAXLN]="";
37 /********************************************/
38 /* get Post data from the client */
39 /********************************************/
40 int getPostData(char *content, int contentMaxLength)
44 /* get content sent from web input */
45 if(isNull(getenv("CONTENT_LENGTH"))) return FALSE;
46 contentLen=atoi(getenv("CONTENT_LENGTH"));
47 contentLen++; /* for terminate ch */
49 /* if larger than buffer, cut off */
50 if(contentLen > contentMaxLength) contentLen=contentMaxLength;
51 if(fgets(content, contentLen, stdin) == NULL){
58 /********************************************/
59 /* get language form query string (in url lang=ja) */
60 /********************************************/
61 int getLangFromQueryString(char* language){
64 char queryStr[BUFFMAXLN];
70 /* get default language at the top of lang list */
71 sscanf(GetConfValue("HtmlLangs"), "%s", language);
73 /* if no string, return default */
74 if(isNull(getenv("QUERY_STRING"))) return FALSE;
76 /* get html access parameter string */
77 strlcpy(queryStr, getenv("QUERY_STRING"), BUFFMAXLN);
79 /* split language in string [....&lang=ja&.....] */
82 split(ptr, name, value, next);
83 if(strstr(name[0], "lang")!=NULL){
84 if(!isNull(value[0])) strlcpy(language, value[0], WORDMAXLN);
92 /********************************************/
93 /* get redirected url form query string */
94 /********************************************/
95 int getRedirectedUrlFromQueryString(char* redirectedUrl){
98 char queryStr[BUFFMAXLN];
104 /* default is null */
105 redirectedUrl[0]='\0';
107 /* if no string, return default */
108 if(isNull(getenv("QUERY_STRING"))) return FALSE;
110 /* get html access parameter string */
111 strlcpy(queryStr, getenv("QUERY_STRING"), BUFFMAXLN);
113 /* split language in string [....&redirectedurl=xxxx&.....] */
116 split(ptr, name, value, next);
117 if(strstr(name[0], "redirectedurl")!=NULL){
118 if(!isNull(value[0])) strlcpy(redirectedUrl, value[0], BUFFMAXLN);
126 /********************************************/
127 /* get mac address form query string (in url lang=ja) */
128 /********************************************/
129 int getMacAddrFromQueryString(char* macAddress){
132 char queryStr[BUFFMAXLN];
141 /* if no string returns, return default */
142 if(isNull(getenv("QUERY_STRING"))) return FALSE;
144 /* get html access parameter string */
145 strlcpy(queryStr, getenv("QUERY_STRING"), BUFFMAXLN);
147 /* split in string [....&macaddr=xxxxx&.....] */
150 split(ptr, name, value, next);
151 if(strstr(name[0], "macaddr")!=NULL){
152 strlcpy(macAddress, value[0], WORDMAXLN);
162 /********************************************/
163 /* get userid from environment variable */
164 /* long userid: "userid@extraid" is set */
165 /********************************************/
166 int getUserIdFromEnv(char *userid){
171 /* if shibboleth or httpbasic, get uid from environment var */
173 if(strcmp(GetConfValue("AuthServer/Protocol"), "shibboleth")==0){
175 /* get data from env-variables for uid and org attribute */
176 pEnv=getenvEx(GetConfValue("AuthServer/UidAttribute"),TRUE,TRUE);
178 strlcpy(userid, pEnv, USERMAXLN);
180 /* if orp string can be get from env var, concatenate it as uid@org */
181 pEnv=getenvEx(GetConfValue("AuthServer/OrgAttribute"),TRUE,TRUE);
183 strlcat(userid, GetConfValue("UserIdSeparator"), USERMAXLN);
184 strlcat(userid, pEnv, USERMAXLN);
189 /* get from env-variable for EPPN(edu person principal name) attribute */
191 pEnv=getenvEx(GetConfValue("AuthServer/EppnAttribute"),TRUE,FALSE);
193 strlcat(userid, pEnv, USERMAXLN);
199 err_msg("ERR at %s#%d: Cannot get user info from shibboleth",__FILE__,__LINE__);
200 PutMessageToClient("Cannot get user info from shibboleth<br>Check shibboleth setting in .htaccess, conf and others");
206 else if(strcmp(GetConfValue("AuthServer/Protocol"), "httpbasic")==0){
207 if(!isNull(getenv("REMOTE_USER"))){
208 strlcpy(userid,getenv("REMOTE_USER"),USERMAXLN);
211 err_msg("ERR at %s#%d: Cannot get user info from httpbasic",__FILE__,__LINE__);
213 PutMessageToClient("Cannot get user info from http basic<br>Check http basic setting in .htaccess and other");
220 /*******************************
221 get userid and password from post string
222 *******************************/
223 int getUserIdFromPostData(char* requestStr, char* userid, char* password){
230 char content[BUFFMAXLN];
232 /* if null string, return */
233 if(isNull(requestStr)) return FALSE;
235 /* copy it to work area */
236 strlcpy(content, requestStr, BUFFMAXLN);
238 /* split request item and execute the request */
242 /* pick up next item */
243 split(ptr, name, value, next);
246 if(strcmp(name[0], "userid")==0){
247 strlcpy(userid, value[0], USERMAXLN);
251 else if(strcmp(name[0], "password")==0){
252 strlcpy(password, value[0], USERMAXLN);
256 /* shift pointer to next item */
260 /* if password is found in request string, clear the string */
261 if(!isNull(password)) requestStr[0]='\0';
266 /********************************************/
267 /* analyze request for checking */
268 /********************************************/
269 int analyzeCheckRequest(char *content, int* status, char* macAddress)
280 /* split request item and execute the request */
284 /* pick up next item */
285 split(ptr, name, value, next);
287 /* if item =status */
288 if(strcmp(name[0], "status")==0){
289 if(strcmp(value[0], "open")==0) *status=OPEN;
290 if(strcmp(value[0], "close")==0) *status=CLOSE;
293 /* if item = macaddr */
294 else if(strcmp(name[0], "macaddr")==0){
295 strlcpy(macAddress, value[0], ADDRMAXLN);
299 /* shift pointer to next item */
306 /********************************************/
307 /* analyze request and execute request for registering */
308 /********************************************/
309 int analyzeRegisterRequest(char *content, char* macAddress, char* deviceName, char* mailAddress)
321 /* split request item and execute the request */
325 /* pick up next item */
326 split(ptr, name, value, next);
328 /* if item = macaddr */
329 if(strcmp(name[0], "macaddr")==0){
330 strlcpy(macAddress, value[0], ADDRMAXLN);
334 else if(strcmp(name[0], "device")==0){
335 strlcpy(deviceName, value[0], WORDMAXLN);
338 else if(strcmp(name[0], "mailaddr")==0){
339 strlcpy(mailAddress, value[0], BUFFMAXLN);
343 /* shift pointer to next item */
347 /* if illegal device name, return */
348 if(*deviceName=='\0'){
349 SetMessage(EmptyDeviceName);
352 if(!IsSafeString(deviceName, WORDMAXLN)){
353 SetMessage(IllegalCharInDevice);
357 /* if illegal mail address, return */
358 if(*mailAddress!='\0'){
359 if(!IsSafeString(mailAddress, BUFFMAXLN)){
360 SetMessage(IllegalCharInMailAddr);
365 /* if illegal mac address, return */
366 if(!ConvertMacAddr(macAddress)) return FALSE;
368 /* if already registered in db, return */
369 if(IsMacAddrFoundInMngDb(macAddress)){
370 SetMessage(ExistentMacAddr);
377 /******************************
378 convert mac address to regular format
380 ******************************/
381 int convertMacAddr(char* macAddr){
383 int m[6]; /* mac address sequence */
386 /* normal form is hex:hex:hex:hex:hex:hex */
387 /* or hex-hex-hex-hex-hex-hex */
389 if((sscanf(macAddr, "%x:%x:%x:%x:%x:%x",
390 &m[0],&m[1],&m[2],&m[3],&m[4],&m[5])!=6)
391 && (sscanf(macAddr, "%x-%x-%x-%x-%x-%x",
392 &m[0],&m[1],&m[2],&m[3],&m[4],&m[5])!=6)){
393 SetMessage(IllegalMacAddrForm);
398 SetMessage(IllegalMacAddr);
403 /* format to [01:23:45:67:89:0a] */
404 snprintf(macAddr, ADDRMAXLN, "%02x:%02x:%02x:%02x:%02x:%02x",
405 m[0],m[1],m[2],m[3],m[4],m[5]);
410 /******************************
411 check safe characters string
412 ******************************/
413 int isSafeString(char* str, int length){
414 char allowableChar[]=" !#$&*+,-./:=?[]^_{|}@";
418 /* scan all char in str */
419 for(i=0; i<length; i++){
422 /* if reached to the end of string, return true */
425 /* if alpha or numeric is found, goto next char */
426 if(isalnum(ch)) continue;
428 /* if control or non ascii is found, return false */
429 if( (unsigned)ch < 0x20|| 0x7f < (unsigned)ch) return FALSE;
431 /* if one of above list is found, goto next char */
432 if(strchr(allowableChar, ch)==NULL) return FALSE;
438 /*********************************************/
439 /* put auth request page to client */
440 /*********************************************/
441 int putAuthRequestPageToClient(char *language, char* cgiName, char* docName, char* redirectedUrl)
443 char authdoc[BUFFMAXLN];
445 char buff[BUFFMAXLN];
447 /* make read in path to the retry document */
448 snprintf(authdoc, BUFFMAXLN, "%s%s/%s/%s",GetConfValue("DocumentRoot"),
449 GetConfValue("OpengateDir"),language,docName);
451 /* replace keyword and send out the file */
452 printf("Content-type: text/html\r\n\r\n");
454 if((fp=fopen(authdoc, "r"))==NULL){
455 err_msg("ERR at %s#%d: cannot find file %s",__FILE__,__LINE__, authdoc);
459 while(fgets(buff,BUFFMAXLN,fp)!=NULL){
460 HtmlReplace(buff, "%%CGINAME%%", cgiName);
461 HtmlReplace(buff, "%%REDIRECTEDURL%%", redirectedUrl);
462 if(strstr(buff, "%%ERRORLIST%%")!=NULL){
463 InsertMessageToPage(language);
472 /*********************************************/
473 /* deny message to the client */
474 /*********************************************/
475 int putDenyToClient(char *language){
476 char denydoc[BUFFMAXLN];
478 char buff[BUFFMAXLN];
480 /* make read in path to the retry document */
481 snprintf(denydoc, BUFFMAXLN, "%s%s/%s/%s",GetConfValue("DocumentRoot"),
482 GetConfValue("OpengateDir"),language,GetConfValue("DenyDoc"));
484 /* replace keyword and send out the file */
485 printf("Content-type: text/html\r\n\r\n");
487 if((fp=fopen(denydoc, "r"))==NULL){
488 err_msg("ERR at %s#%d: cannot find file %s",__FILE__,__LINE__, denydoc);
492 while(fgets(buff,BUFFMAXLN,fp)!=NULL){
493 if(strstr(buff, "%%ERRORLIST%%")!=NULL){
494 InsertMessageToPage(language);
503 /*********************************************/
504 /* put response to client for check request */
505 /*********************************************/
506 int putCheckPageToClient(char *language, char* userId, char* extraId)
508 char responsedoc[BUFFMAXLN];
510 char buff[BUFFMAXLN];
511 char cookie[SIDMAXLN];
512 char* chkCgi=GetConfValue("CheckCgi");
513 char* regCgi=GetConfValue("RegisterCgi");
514 char* timeout=GetConfValue("OpenTimeout");
516 /* make read in path to the document */
517 snprintf(responsedoc, BUFFMAXLN, "%s%s/%s/%s",GetConfValue("DocumentRoot"),
518 GetConfValue("OpengateDir"),language,GetConfValue("CheckDoc"));
521 printf("Content-type: text/html\r\n");
523 /* if no cookie, make, send, and save cookie */
524 if(!GetHttpCookie(cookie,GetConfValue("AuthAdminCookie"))){
525 CreateCookie(cookie);
526 printf("Set-Cookie: %s=%s;path=/;\r\n", GetConfValue("AuthAdminCookie"), cookie);
527 SaveCookieToWorkDb(cookie,userId, extraId, ADMINUSER);
530 /* end of http header */
533 /* replace keyword and send out the file */
534 if((fp=fopen(responsedoc, "r"))==NULL){
535 err_msg("ERR at %s#%d: cannot find file %s",__FILE__,__LINE__, responsedoc);
540 while(fgets(buff,BUFFMAXLN,fp)!=NULL){
541 HtmlReplace(buff, "%%CHECKCGI%%", chkCgi);
542 HtmlReplace(buff, "%%REGISTERCGI%%", regCgi);
543 HtmlReplace(buff, "%%TIMEOUT%%", timeout);
544 HtmlReplace(buff, "%%USERID%%", userId);
546 if(strstr(buff, "%%MACCHECKLIST%%")!=NULL){
547 PutMacCheckListToClient();
549 else if(strstr(buff, "%%ERRORLIST%%")!=NULL){
550 InsertMessageToPage(language);
560 /*********************************************/
561 /* put response to client for register request */
562 /* ownReg:1=the page is controlled by owner, 0=under admin */
563 /*********************************************/
564 int putRegisterPageToClient(char *language, char* macAddress, char* deviceName, char* mailAddress, char* userId, char* extraId, int ownReg, char* redirectedUrl)
566 char responsedoc[BUFFMAXLN];
568 char buff[BUFFMAXLN];
569 char cookie[SIDMAXLN];
574 /* get Maximum count of devices for an user from conf file */
575 maxDevicesStr=GetConfValue("MaxDevices");
577 /* setup cgi and doc */
579 regCgi=GetConfValue("OwnCgi");
580 regDoc=GetConfValue("OwnRegisterDoc");
582 regCgi=GetConfValue("RegisterCgi");
583 regDoc=GetConfValue("RegisterDoc");
585 if(isNull(regCgi) || isNull(regDoc)){
586 err_msg("ERR at %s#%d: cannot find cgi/doc for reg in conf",__FILE__,__LINE__);
590 /* make read in path to the document */
591 snprintf(responsedoc, BUFFMAXLN, "%s%s/%s/%s",GetConfValue("DocumentRoot"),
592 GetConfValue("OpengateDir"),language,regDoc);
595 printf("Content-type: text/html\r\n");
597 /* if no cookie, make, send, and save cookie */
598 if(!GetHttpCookie(cookie, GetConfValue("AuthUserCookie"))){
599 CreateCookie(cookie);
600 printf("Set-Cookie: %s=%s;path=/;\r\n", GetConfValue("AuthUserCookie"), cookie);
601 SaveCookieToWorkDb(cookie, userId, extraId, NORMALUSER);
602 SaveMailDefalutForCookieToWorkDb(cookie, mailAddress);
605 /* end of http header */
608 if((fp=fopen(responsedoc, "r"))==NULL){
609 err_msg("ERR at %s#%d: cannot find file %s",__FILE__,__LINE__, responsedoc);
613 while(fgets(buff,BUFFMAXLN,fp)!=NULL){
614 HtmlReplace(buff, "%%REGISTERCGI%%", regCgi);
615 HtmlReplace(buff, "%%MACADDR%%", macAddress);
616 HtmlReplace(buff, "%%DEVICE%%", deviceName);
617 HtmlReplace(buff, "%%MAILADDR%%", mailAddress);
618 HtmlReplace(buff, "%%USERID%%", userId);
619 HtmlReplace(buff, "%%REDIRECTEDURL%%", redirectedUrl);
620 HtmlReplace(buff, "%%MAXDEVICES%%", maxDevicesStr);
622 if(strstr(buff, "%%MACREGLIST%%")!=NULL){
623 PutMacRegListToClient(userId, extraId);
625 else if(strstr(buff, "%%ERRORLIST%%")!=NULL){
626 InsertMessageToPage(language);
636 /*********************************************/
637 /* put mac list in mac check table to the client */
638 /*********************************************/
639 void putMacCheckListToClient(void){
641 char macAddress[ADDRMAXLN];
642 char vendor[WORDMAXLN];
643 char ipv4[ADDRMAXLN];
644 char ipv6[ADDRMAXLN];
649 /* get mac list from db and insert into html table */
650 while(GetNextRowInMacCheckTable(macAddress, ipv4, ipv6)){
652 /* get nic vendor from management db */
653 GetNicVendorFromMngDb(macAddress, vendor, WORDMAXLN);
655 /* is the terminal in use */
656 if(IsSessionFoundInSessionTable(macAddress) ||
657 IsActiveSessionFoundInOpengateSessionTable(macAddress)) inUse=TRUE;
660 /* is the terminal's MAC is registered in DB */
661 foundOnDb = IsMacAddrFoundInMngDb(macAddress);
663 /* print out table row */
664 /* the row is colored, if it is a candidate for registering */
665 /* the terminals inUse/foundInDb may be not the candidate */
666 if(inUse || foundOnDb){
667 printf("<tr align=middle>\n");
669 printf("<tr style='background-color: rgb(255,255,204);' align=middle>\n");
672 /* check radio button in first row */
674 printf("<td><input type='radio' name='macaddr' value='%s' checked></td>\n", macAddress);
677 printf("<td><input type='radio' name='macaddr' value='%s'></td>\n", macAddress);
680 /* show macAddress, vendor, ipv4,ipv6 */
681 printf("<td>%s</td>\n", macAddress);
682 printf("<td>%s</td>\n",vendor);
683 printf("<td>%s</td>\n",ipv4);
684 printf("<td>%s</td>\n",ipv6);
686 /* show flags for inUse/foundInDb */
687 if(inUse) printf("<td>*</td>\n");
688 else printf("<td><br></td>\n");
689 if(foundOnDb) printf("<td>*</td>\n");
690 else printf("<td><br></td>\n");
695 /*********************************************/
696 /* put mac regsitered list the client */
697 /*********************************************/
698 void putMacRegListToClient(char* userId, char* extraId){
700 char deviceName[WORDMAXLN]="";
701 char entryDate[WORDMAXLN]="";
702 char limitDate[WORDMAXLN]="";
703 char status[WORDMAXLN]="";
704 char macAddress[ADDRMAXLN]="";
705 char mailAddress[BUFFMAXLN]="";
707 /* get registered mac list form db and insert */
708 while(GetNextMacAddrFromMngDb(userId,extraId,macAddress,deviceName,
709 entryDate,limitDate,status,mailAddress)){
712 printf("<tr align=middle>\n");
713 printf("<td>%s</td>\n", macAddress);
714 printf("<td>%s</td>\n",deviceName);
715 printf("<td>%s</td>\n",entryDate);
716 printf("<td>%s</td>\n",limitDate);
717 printf("<td>%s</td>\n",status);
718 printf("<td>%s</td>\n",mailAddress);
723 /*********************************************/
724 /* put some message to the client */
725 /*********************************************/
726 void putMessageToClient(char *message)
728 printf("Content-type: text/html\r\n\r\n");
729 printf("<HTML><HEAD><TITLE>OpengateMsg</TITLE></HEAD> \r\n");
730 printf("<BODY>\r\n");
731 printf("%s\r\n", message);
732 printf("</BODY></HTML> \r\n\r\n");
735 /************************************************/
736 /* send page for returning to the previous page */
737 /************************************************/
738 void returnToRedirectedPage(char* redirectedUrl, char* language){
740 char returndoc[BUFFMAXLN];
742 char buff[BUFFMAXLN];
745 /* make read in path to the document */
746 snprintf(returndoc, BUFFMAXLN, "%s%s/%s/%s",GetConfValue("DocumentRoot"),
747 GetConfValue("OpengateDir"),language,GetConfValue("ReturnDoc"));
750 printf("Content-type: text/html\r\n\r\n");
752 if((fp=fopen(returndoc, "r"))==NULL){
753 err_msg("ERR at %s#%d: cannot find file %s",__FILE__,__LINE__, returndoc);
754 printf("Error! \r\n\r\n");
758 if(!isNull(GetConfValue("ReturnWaitTime"))){
759 waitTime=GetConfValue("ReturnWaitTime");
761 while(fgets(buff,BUFFMAXLN,fp)!=NULL){
762 HtmlReplace(buff, "%%WAITTIME%%", waitTime);
763 HtmlReplace(buff, "%%REDIRECTEDURL%%", redirectedUrl);
769 /************************************/
770 /* split value for indicated name */
771 /* in content "name=value&..." */
772 /************************************/
773 void split(char content[], char *name[], char *value[], char *next[])
779 value[0]=content+strlen(content);
783 if((pstr=strchr(name[0],(int)'='))==NULL){
789 /* set value start */
794 if((pstr=strchr(value[0],'&'))==NULL){
807 /**********************************/
808 /* decode text coding in web post */
809 /**********************************/
810 void decode(char *string)
812 char *pcheck, *pinsert;
814 pcheck=pinsert=string;
815 while(*pcheck != '\0'){
818 }else if(*pcheck == '%'){
819 *pinsert=(char)(hex2num(*(pcheck+1))*16 + hex2num(*(pcheck+2)));
831 /*****************************************************/
832 /* replace beforeStr to afterStr in string in buff */
833 /*****************************************************/
834 int htmlReplace(char* buff,char *beforeStr,char *afterStr)
836 char *pBuff , *pNext;
837 char tempBuff[BUFFMAXLN];
839 if(buff==NULL) return 1;
841 strlcpy(tempBuff, buff, BUFFMAXLN);
842 strlcpy(buff,"",BUFFMAXLN);
844 for(pBuff = tempBuff;
845 (pNext=StrSplit(pBuff, beforeStr)) != NULL;
847 strlcat(buff,pBuff,BUFFMAXLN);
848 strlcat(buff,afterStr,BUFFMAXLN);
850 strlcat(buff,pBuff,BUFFMAXLN);
855 /*****************************************************/
856 /* split a str at delimStr and return the point */
857 /*****************************************************/
858 char* strSplit(char* str,const char* delimStr)
860 char* delimPoint = strstr(str,delimStr);
861 const size_t delimLen = strlen(delimStr);
863 if(delimPoint == NULL) return NULL;
866 delimPoint += delimLen;
872 /**********************/
873 /* get HTTP-Cookie */
874 /**********************/
875 /* cookie string examples
876 "OpengateMmng=de..ac1&Userid=user1"
877 "OpengateMmng=de..ac1&Userid=user1; xxx=..; yyy=.."
878 "xxx=..; yyy=..; OpengateMmng=de..ac1&Userid=user1"
880 int getHttpCookie(char *cookie, char* cookieName){
881 char content[BUFFMAXLN];
891 /* if exist cookie, copy it to work area */
892 if(isNull(getenv("HTTP_COOKIE"))) return FALSE;
893 strlcpy(content, getenv("HTTP_COOKIE"), BUFFMAXLN);
896 /* search 'OpengateMmng' cookie string (terminated by ; or \0) */
898 if((ptrNext=strstr(ptr, "; "))==NULL) break; /* search "; " */
899 *ptrNext='\0'; /* overwrite string end */
900 ptrNext++; /* pointer to next string */
901 while(!isNull(ptrNext)&&*ptrNext==' ') ptrNext++; /* skip spaces */
902 if(strstr(ptr, cookieName)==ptr) break; /* exit at matching */
903 ptr=ptrNext; /* check next string */
906 /* get valuses of cookie from "OpengateMmng=de..ac1" */
908 split(ptr, name, value, next);
910 if(strstr(name[0], cookieName)!=NULL){
911 strlcpy(cookie, value[0], SIDMAXLN);
916 if(isNull(cookie)) return FALSE;
920 /*************************************
921 compare received cookie to previously saved one
922 *************************************/
923 int isCorrectCookie(char* cookie, int userType){
924 char userId[USERMAXLN];
925 char extraId[USERMAXLN];
927 /* compare http received cookie and DB readin cookie */
930 GetHttpCookie(cookie, GetConfValue("AuthUserCookie"));
931 if(IsCookieFoundInWorkDb(cookie,userId,extraId,NORMALUSER)) return TRUE;
934 GetHttpCookie(cookie, GetConfValue("AuthAdminCookie"));
935 if(IsCookieFoundInWorkDb(cookie,userId,extraId,ADMINUSER)) return TRUE;
941 /********************************************/
942 /* analyze update request and execute request */
943 /********************************************/
944 int analyzeUpdateRequestAndExecute(char *requestStr, char* userId, char* extraId)
950 char macAddr[ADDRMAXLN];
951 int modified=FALSE; /* database modification is executed */
953 char content[BUFFMAXLN];
954 char deviceName[WORDMAXLN]="";
955 char mailAddress[BUFFMAXLN]="";
957 /* if null string, return */
958 if(isNull(requestStr)) return FALSE;
960 /* copy request string to work area */
961 strlcpy(content, requestStr, BUFFMAXLN);
963 /* split request item and execute the request */
964 /* <input type=radio name=11:22:33:44:55:66 value=extend> */
965 /* <input type=radio name=11:22:33:44:55:66 value=pause> */
966 /* <input type=radio name=11:22:33:44:55:66 value=delete> */
967 /* <input type=hidden name=11:22:33:44:55:66 value=mail:wata@foo.bar> */
968 /* <input type=hidden name=11:22:33:44:55:66 value=name:iPhone01> */
973 /* pick up next item */
974 split(ptr, name, value, next);
976 /* if item=delete, execute delete */
977 if(strcmp(value[0], "delete")==0){
978 strlcpy(macAddr, name[0], ADDRMAXLN);
980 if(ConvertMacAddr(macAddr)){
981 ret=DelMacAddrFromMngDb(macAddr);
984 PutMacModifyLogToMngDb(userId, extraId, macAddr, 'D');
985 PutMacAddressToServers(macAddr);
990 /* if item = extend, execute extend */
991 else if(strcmp(value[0], "extend")==0){
992 strlcpy(macAddr, name[0], ADDRMAXLN);
994 if(ConvertMacAddr(macAddr)){
995 ret=RenewMacAddrInMngDb(macAddr);
998 PutMacModifyLogToMngDb(userId, extraId, macAddr, 'E');
999 PutMacAddressToServers(macAddr);
1004 /* if item = pause, execute pause */
1005 else if(strcmp(value[0], "pause")==0){
1006 strlcpy(macAddr, name[0], ADDRMAXLN);
1008 if(ConvertMacAddr(macAddr)){
1009 ret=PauseMacAddrInMngDb(macAddr);
1012 PutMacModifyLogToMngDb(userId, extraId, macAddr, 'P');
1013 PutMacAddressToServers(macAddr);
1018 /* if item = name xxxx, execute renaming the device name */
1019 else if(strstr(value[0], "name+")==value[0]){
1020 strlcpy(macAddr, name[0], ADDRMAXLN);
1022 if(ConvertMacAddr(macAddr)){
1024 /* when value=name xxxx, rename device-name to xxxx */
1025 /* copy limitted length and decode */
1026 strlcpy(deviceName, value[0]+5, WORDMAXLN);
1029 /* if illegal device name, return */
1030 if(*deviceName=='\0'){
1031 SetMessage(EmptyDeviceName);
1034 if(!IsSafeString(deviceName, WORDMAXLN)){
1035 SetMessage(IllegalCharInDevice);
1039 /* update the device name in db */
1040 RenameDeviceNameInMngDb(macAddr, deviceName);
1044 /* if item = mail xxxx, execute renaming the mail address */
1045 else if(strstr(value[0], "mail+")==value[0]){
1046 strlcpy(macAddr, name[0], ADDRMAXLN);
1048 if(ConvertMacAddr(macAddr)){
1050 /* when value=mail xxxx, rename mail-address to xxxx */
1051 /* copy limitted length and decode */
1052 strlcpy(mailAddress, value[0]+5, BUFFMAXLN);
1053 decode(mailAddress);
1055 /* if illegal mail address, return */
1056 if(*mailAddress!='\0'){
1057 if(!IsSafeString(mailAddress, BUFFMAXLN)){
1058 SetMessage(IllegalCharInMailAddr);
1063 /* update the device name in db */
1064 RenameMailAddressInMngDb(macAddr, mailAddress);
1068 /* shift pointer to next item */
1075 /*********************************************/
1076 /* put response to client */
1077 /* ownUpdate:1=page is controlled by owner, 0=under admin */
1078 /*********************************************/
1079 int putUpdatePageToClient(char *language, char* userId, char* extraId, int ownUpdate, char* redirectedUrl)
1081 char responsedoc[BUFFMAXLN];
1083 char buff[BUFFMAXLN];
1084 char cookie[SIDMAXLN];
1087 char mailDefault[BUFFMAXLN];
1089 /* select update page for owner or administrator */
1091 updateCgi=GetConfValue("OwnCgi");
1092 updateDoc=GetConfValue("OwnUpdateDoc");
1094 updateCgi=GetConfValue("UpdateCgi");
1095 updateDoc=GetConfValue("UpdateDoc");
1097 if(isNull(updateCgi) || isNull(updateDoc)){
1098 err_msg("ERR at %s#%d: cannot find cgi/doc for update in conf",__FILE__,__LINE__);
1102 /* make read in path to the retry document */
1103 snprintf(responsedoc, BUFFMAXLN, "%s%s/%s/%s",GetConfValue("DocumentRoot"),
1104 GetConfValue("OpengateDir"),language,updateDoc);
1107 printf("Content-type: text/html\r\n");
1109 /* if no cookie, make, send, and save cookie */
1110 if(!GetHttpCookie(cookie, GetConfValue("AuthUserCookie"))){
1111 CreateCookie(cookie);
1112 printf("Set-Cookie: %s=%s;path=/;\r\n", GetConfValue("AuthUserCookie"), cookie);
1113 SaveCookieToWorkDb(cookie,userId, extraId, NORMALUSER);
1114 MakeMailDefault(userId, extraId, mailDefault);
1115 SaveMailDefalutForCookieToWorkDb(cookie, mailDefault);
1118 /* end of http header */
1121 if((fp=fopen(responsedoc, "r"))==NULL){
1122 err_msg("ERR at %s#%d: cannot find file %s",__FILE__,__LINE__, responsedoc);
1126 while(fgets(buff,BUFFMAXLN,fp)!=NULL){
1128 HtmlReplace(buff, "%%CGINAME%%", updateCgi);
1129 HtmlReplace(buff, "%%USERID%%", userId);
1130 HtmlReplace(buff, "%%REDIRECTEDURL%%", redirectedUrl);
1132 if(strstr(buff, "%%MACLIST%%")!=NULL){
1133 PutMacListToClient(userId,extraId);
1135 else if(strstr(buff, "%%USAGELOG%%")!=NULL){
1136 PutUsageLogToClient(userId, extraId, language);
1138 else if(strstr(buff, "%%ERRORLIST%%")!=NULL){
1139 InsertMessageToPage(language);
1149 /*********************************************/
1150 /* put mac list the client */
1151 /*********************************************/
1152 void putMacListToClient(char* userId, char* extraId){
1154 char deviceName[WORDMAXLN];
1155 char entryDate[WORDMAXLN];
1156 char limitDate[WORDMAXLN];
1157 char status[WORDMAXLN];
1158 char macAddr[ADDRMAXLN];
1159 char mailAddress[BUFFMAXLN];
1161 /* make rows for deletion and extending */
1162 /* get registered mac list form db and insert */
1163 while(GetNextMacAddrFromMngDb(userId,extraId,macAddr,deviceName,
1164 entryDate,limitDate,status,mailAddress)){
1165 printf("<tr align=middle>\n");
1166 if((status[0]=='A')||(status[0]=='P')){
1167 printf("<td><input type=radio name=%s value=extend checked></td>\n",
1169 printf("<td><input type=radio name=%s value=pause></td>\n",macAddr);
1170 printf("<td><input type=radio name=%s value=delete></td>\n",macAddr);
1172 printf("<td>-</td>\n");
1173 printf("<td>-</td>\n");
1174 printf("<td>-</td>\n");
1176 printf("<td>%s</td>\n", macAddr);
1177 printf("<td onclick=\"editstring('%s','name',this)\">%s</td>\n",
1178 macAddr,deviceName);
1179 printf("<td onclick=\"editstring('%s','mail',this)\">%s</td>\n",
1180 macAddr,mailAddress);
1181 printf("<td>%s</td>\n",entryDate);
1182 printf("<td>%s</td>\n",limitDate);
1183 printf("<td>%s</td>\n",status);
1188 /*********************************************/
1189 /* put usage log to the client */
1190 /*********************************************/
1191 void putUsageLogToClient(char *userId, char* extraId, char* language){
1193 char macAddr[ADDRMAXLN]="";
1194 char deviceName[WORDMAXLN]="";
1195 char openTime[WORDMAXLN]="";
1196 char closeTime[WORDMAXLN]="";
1197 char gatewayName[WORDMAXLN]="";
1198 char beginTime[WORDMAXLN]="";
1199 char endTime[WORDMAXLN]="";
1204 /* get usage log from db and insert as JSON format */
1205 while(GetNextUsageLogFromMngDb(userId,extraId,macAddr,deviceName,
1206 openTime,closeTime,gatewayName)){
1208 /* split hostname only */
1209 if((p=strchr(gatewayName,'.'))!=NULL) *p='\0';
1211 /* put out table row */
1212 printf("\t %d:{\n", count);
1213 printf("\t\t macAddress: '%s',\n", macAddr);
1214 printf("\t\t device: '%s',\n",deviceName);
1215 printf("\t\t openTime: '%s',\n",openTime);
1216 printf("\t\t closeTime: '%s',\n",closeTime);
1217 printf("\t\t gateway: '%s'\n",gatewayName);
1220 /* increment log item counter */
1224 /* put out informations for the list */
1225 GetTimeRangeToShowLog(beginTime, endTime, &dateCount);
1226 printf("\t info:{\n");
1227 printf("\t\t beginTime: '%s',\n", beginTime);
1228 printf("\t\t endTime: '%s',\n", endTime);
1229 printf("\t\t listCount: %d,\n", count);
1230 printf("\t\t dateCount: %d\n", dateCount);
1234 /**********************************************/
1235 /* check allowable http-agent defined in conf */
1236 /**********************************************/
1237 int isAccessedFromAllowableAgent(void){
1240 char* pRegExPattern=NULL;
1243 /* get agent string. if not, return false */
1244 if( isNull(pAgent=getenv("HTTP_USER_AGENT")) ) return FALSE;
1246 /* get first reg expression in conf. if not, return true(not define=allow all) */
1247 if(isNull(pRegExPattern=GetFirstConfValue("AllowableAgentPattern"))){
1251 /* loop for patterns in conf */
1252 while(!isNull(pRegExPattern)){
1254 /* if agent is matched to reg ex, return true. */
1255 /* last-arg 1 means case sensitive */
1256 if(RegExMatch(pAgent, pRegExPattern, 1)){
1261 /* get next reg expression in conf */
1262 pRegExPattern=GetNextConfValue();
1265 /* if fail, print message */
1267 err_msg("ERR at %s#%d: http-agent[%s] is not allowed in conf file",__FILE__,__LINE__, pAgent);
1273 /*******************************/
1274 /*******************************/
1276 int GetPostData(char *content, int contentMaxLength){
1278 if(debug>1) err_msg("DEBUG:=>getPostData(%d)", contentMaxLength);
1279 ret=getPostData(content, contentMaxLength);
1280 if(debug>1) err_msg("DEBUG:%d<=getPostData(..)",ret);
1284 int GetLangFromQueryString(char* language){
1286 if(debug>1) err_msg("DEBUG:=>getLangFromQueryString( )");
1287 ret=getLangFromQueryString(language);
1288 if(debug>1) err_msg("DEBUG:%d<=getLangFromQueryString(%s)",ret,language);
1292 int GetRedirectedUrlFromQueryString(char* redirectedUrl){
1294 if(debug>1) err_msg("DEBUG:=>getRedirectedUrlFromQueryString( )");
1295 ret=getRedirectedUrlFromQueryString(redirectedUrl);
1296 if(debug>1) err_msg("DEBUG:%d<=getRedirectedUrlFromQueryString(%s)",ret,redirectedUrl);
1300 int GetMacAddrFromQueryString(char* macAddress){
1302 if(debug>1) err_msg("DEBUG:=>getMacAddrFromQueryString( )");
1303 ret=getMacAddrFromQueryString(macAddress);
1304 if(debug>1) err_msg("DEBUG:%d<=getMacAddrFromQueryString(%s)",ret,macAddress);
1308 int AnalyzeCheckRequest(char *content, int* status, char* macAddress){
1310 if(debug>1) err_msg("DEBUG:=>analyzeCheckRequest(%s)", content);
1311 ret=analyzeCheckRequest(content, status, macAddress);
1312 if(debug>1) err_msg("DEBUG:%d<=analyzeCheckRequest(%d,%s)",ret,*status, macAddress);
1316 int AnalyzeRegisterRequest(char *content, char* macAddress, char* deviceName, char* mailAddress){
1318 if(debug>1) err_msg("DEBUG:=>analyzeRegisterRequest(%s)", content);
1319 ret=analyzeRegisterRequest(content, macAddress, deviceName, mailAddress);
1320 if(debug>1) err_msg("DEBUG:%d<=analyzeRegisterRequest(%s,%s,%s)",ret, macAddress, deviceName, mailAddress);
1324 int PutDenyToClient(char *language){
1326 if(debug>1) err_msg("DEBUG:=>putDenyToClient(%s)",language);
1327 ret=putDenyToClient(language);
1328 if(debug>1) err_msg("DEBUG:(%d)<=putDenyToClient( )",ret);
1332 int PutCheckPageToClient(char *language, char* userId, char* extraId){
1334 if(debug>1) err_msg("DEBUG:=>putCheckPageToClient(%s,%s,%s)",
1335 language,userId,extraId);
1336 ret=putCheckPageToClient(language,userId,extraId);
1337 if(debug>1) err_msg("DEBUG:(%d)<=putCheckPageToClient( )",ret);
1341 int PutRegisterPageToClient(char *language, char* macAddress, char* deviceName, char* mailAddress, char* userId, char* extraId, int ownReg, char* redirectedUrl){
1343 if(debug>1) err_msg("DEBUG:=>putRegisterPageToClient(%s,%s,%s,%s,%s,%s,%d,%s)", language,macAddress,deviceName,mailAddress,userId,extraId,ownReg, redirectedUrl);
1344 ret=putRegisterPageToClient(language, macAddress, deviceName, mailAddress, userId, extraId, ownReg, redirectedUrl);
1345 if(debug>1) err_msg("DEBUG:(%d)<=putRegisterPageToClient( )",ret);
1349 void PutMacCheckListToClient(void){
1350 if(debug>1) err_msg("DEBUG:=>putMacCheckListToClient( )");
1351 putMacCheckListToClient();
1352 if(debug>1) err_msg("DEBUG:<=putMacCheckListToClient( )");
1355 void PutMacRegListToClient(char* userId, char* extraId){
1356 if(debug>1) err_msg("DEBUG:=>putMacRegListToClient( )");
1357 putMacRegListToClient(userId, extraId);
1358 if(debug>1) err_msg("DEBUG:<=putMacRegListToClient( )");
1361 void PutMessageToClient(char *message){
1362 if(debug>1) err_msg("DEBUG:=>putMessageToClient(%s)",message);
1363 putMessageToClient(message);
1364 if(debug>1) err_msg("DEBUG:<=putMessageToClient( )");
1367 void ReturnToRedirectedPage(char* redirectedUrl, char* language){
1368 if(debug>1) err_msg("DEBUG:=>returnToRedirectedPage(%s,%s)",redirectedUrl,language);
1369 returnToRedirectedPage(redirectedUrl, language);
1370 if(debug>1) err_msg("DEBUG:<=returnToRedirectedPage( )");
1373 int ConvertMacAddr(char* macAddr){
1375 if(debug>1) err_msg("DEBUG:=>convertMacAddr(%s)", macAddr);
1376 ret=convertMacAddr(macAddr);
1377 if(debug>1) err_msg("DEBUG:(%d)<=convertMacAddr(%s)",ret,macAddr);
1381 int IsSafeString(char* str, int length){
1383 if(debug>1) err_msg("DEBUG:=>isSafeString(%s,%d)",str,length);
1384 ret=isSafeString(str,length);
1385 if(debug>1) err_msg("DEBUG:(%d)<=isSafeString( )",ret);
1389 int HtmlReplace(char* buff,char *beforeStr,char *afterStr){
1391 if(debug>2) err_msg("DEBUG:=>htmlReplace(%s,%s,%s)",buff,beforeStr,afterStr);
1392 ret = htmlReplace(buff, beforeStr, afterStr);
1393 if(debug>2) err_msg("DEBUG:(%d)<=htmlReplace( )",ret);
1397 char* StrSplit(char* str,const char* delimStr){
1399 if(debug>2) err_msg("DEBUG:=>strSplit(%s,%s)",str,delimStr);
1400 ret = strSplit(str, delimStr);
1401 if(debug>2) err_msg("DEBUG:(%s)<=strSplit( )",ret);
1405 int GetHttpCookie(char *cookie, char* cookieName){
1407 if(debug>1) err_msg("DEBUG:=>getHttpCookie(%s)", cookieName);
1408 ret = getHttpCookie(cookie, cookieName);
1409 if(debug>1) err_msg("DEBUG:(%d)<=getHttpCookie(%s)",ret, cookie);
1413 int IsCorrectCookie(char* cookie, int userType){
1415 if(debug>1) err_msg("DEBUG:=> isCorrectCookie(%d)", userType);
1416 ret = isCorrectCookie(cookie,userType);
1417 if(debug>1) err_msg("DEBUG:(%d)<= isCorrectCookie(%s)",ret,cookie);
1421 int GetUserIdFromEnv(char *userid){
1423 if(debug>1) err_msg("DEBUG:=>getUserIdFromEnv(%s)",userid);
1424 ret = getUserIdFromEnv(userid);
1425 if(debug>1) err_msg("DEBUG:(%d)<=getUserIdFromEnv( )",ret);
1429 int GetUserIdFromPostData(char* requestStr, char* userid, char* password){
1431 if(debug>1) err_msg("DEBUG:=>getUserIdFromPostData(..)");
1432 ret = getUserIdFromPostData(requestStr,userid,password);
1433 if(debug>1) err_msg("DEBUG:(%d)<=getUserIdFromPostData(,%s,password)",ret,userid);
1437 int PutAuthRequestPageToClient(char *language, char* cgiName, char* docName, char* redirectedUrl){
1439 if(debug>1) err_msg("DEBUG:=>putAuthRequestPageToClient(%s,%s,%s)",language,cgiName, docName, redirectedUrl);
1440 ret=putAuthRequestPageToClient(language,cgiName, docName, redirectedUrl);
1441 if(debug>1) err_msg("DEBUG:(%d)<=putAuthRequestPageToClient( )",ret);
1445 int AnalyzeUpdateRequestAndExecute(char *content, char* userId, char* extraId){
1448 if(debug>1) err_msg("DEBUG:=>analyzeUpdateRequestAndExecute(%s,%s,%s)", content,userId,extraId);
1449 ret=analyzeUpdateRequestAndExecute(content,userId,extraId);
1450 if(debug>1) err_msg("DEBUG:%d<=analyzeUpdateRequestAndExecute( )",ret);
1454 int PutUpdatePageToClient(char *language, char* userId, char* extraId, int ownUpdate, char* redirectedUrl){
1456 if(debug>1) err_msg("DEBUG:=>putUpdatePageToClient(%s,%s,%s,%d,%s)",
1457 language,userId,extraId,ownUpdate,redirectedUrl);
1458 ret=putUpdatePageToClient(language,userId,extraId,ownUpdate,redirectedUrl);
1459 if(debug>1) err_msg("DEBUG:(%d)<=putUpdatePageToClient( )",ret);
1463 void PutMacListToClient(char *userId, char* extraId){
1464 if(debug>1) err_msg("DEBUG:=>putMacListToClient(%s,%s)",userId,extraId);
1465 putMacListToClient(userId,extraId);
1466 if(debug>1) err_msg("DEBUG:<=putMacListToClient( )");
1469 void PutUsageLogToClient(char *userId, char* extraId, char* language){
1470 if(debug>1) err_msg("DEBUG:=>putUsageLogToClient(%s,%s,%s)",userId,extraId,language);
1471 putUsageLogToClient(userId,extraId,language);
1472 if(debug>1) err_msg("DEBUG:<=putUsageLogToClient( )");
1475 int IsAccessedFromAllowableAgent(void){
1477 if(debug>1) err_msg("DEBUG:=>isAccessedFromAllowableAgent( )");
1478 ret=isAccessedFromAllowableAgent();
1479 if(debug>1) err_msg("DEBUG:(%d)<=isAccessedFromAllowableAgent( )",ret);