Following are my code :
#include "stdio.h"
#include "time.h"
#include "string.h"
#include "cJSON.h"
#include "stdlib.h"
int checkUserRole(char *cmd);
int main(){
char *cmd = "zwr ^A(\"A\")"; //string: zwr ^A("A")
int v = checkUserRole(cmd);
printf("%d",v);
return 0;
}
int checkUserRole(char *cmd)
{
const char *u ;
u = getenv("USER");
char *token;
char *cmd_w_g;
char *limiter ;
if(strstr(cmd,"(") != NULL){
limiter = "(";
token = strtok(cmd,limiter);
cmd_w_g = token;
}
char *cmd_qualifier;
limiter = " ^";
cmd_qualifier = strtok(cmd_w_g,limiter);
char *cmd_q;
cmd_q = cmd_qualifier;
char *gbl ;
gbl = strtok(NULL,limiter);
char *fileName = "roles.cfg";
char buff[512];
FILE *file = fopen(fileName, "rt");
char fileContent[1000000];
while(fgets(buff, sizeof buff, file) != NULL){
sprintf(fileContent,"%s%s",fileContent,buff);
}
cJSON *root = cJSON_Parse(fileContent);
cJSON *gbl_json = cJSON_GetObjectItem(root,gbl);
cJSON *user_json = cJSON_GetObjectItem(gbl_json,u);
cJSON *cmd_json = cJSON_GetObjectItem(user_json,cmd_q);
char *role = cmd_json->valuestring;
if(strstr(role,"true") != NULL){
return 1;
} else {
return 0;
}
}
and json file 'roles.cfg' using in code:
{
"A": {
"root": {
"set": "true",
"kill": "true",
"zwrite": "true"
},
"abc": {
"set": "true",
"kill": "false",
"zwrite": "true"
}
},
"B": {
"root": {
"set": "false",
"kill": "false",
"zwrite": "true"
},
"abc": {
"set": "true",
"kill": "true",
"zwrite": "true"
}
}
}
I used strok
to split some text , but I get Segmentation fault.
error when execute
Following are debug output:
Reading symbols from ./test2...done.
(gdb) b 1
Breakpoint 1 at 0x400b55: file test2.c, line 1.
(gdb) r
Starting program: /home/insight/test2
Breakpoint 1, main () at test2.c:9
9 char *cmd = "zwr ^A(\"A\")";
(gdb) n
10 int v = checkUserRole(cmd);
(gdb) s
checkUserRole (cmd=0x4046c4 "zwr ^A(\"A\")") at test2.c:15
15 {
(gdb) n
17 u = getenv("USER");
(gdb) n
21 if(strstr(cmd,"(") != NULL){
(gdb) n
22 limiter = "(";
(gdb) n
23 token = strtok(cmd,limiter);
(gdb) n
Program received signal SIGSEGV, Segmentation fault.
strtok () at ../sysdeps/x86_64/strtok.S:186
186 ../sysdeps/x86_64/strtok.S: No such file or directory.
(gdb)
I have no idea why it get error at that line ,I check all paramter to strtok
, seem it have no problem
//Update : have no warning when compiling:
insight@insight-ubuntu64:~$ gcc -g -o test2 test2.c cJSON.c -lm
insight@insight-ubuntu64:~$