void getUsers()
{	
		char buf[256];
		FILE* file = fopen("Authentication.txt", "r");
		int count = 0, initial = 0;
		
		while (fgets(buf, sizeof(buf), file))
		{
			if (initial == 0)
			{
				initial++;
			} else {					
					
					char *username = (char *)malloc(sizeof(10));
					strcpy(username, strtok(buf, "\t"));
					username = trimwhitespace(username);
					char *pw = (char *)malloc(sizeof(10));
					strcpy(pw, strtok(NULL, "\t"));
					pw = trimwhitespace(pw);
					userpw_t* user = (userpw_t*)malloc(sizeof(userpw_t));
					user->username = username;
					user->password = pw;
					int* gamesPlayed = (int*)malloc(sizeof(int));
					int* gamesWon = (int*)malloc(sizeof(int));
					*gamesPlayed = 0;
					*gamesWon = 0;
					user->gamesPlayed = gamesPlayed;
					user->gamesWon = gamesWon;
					userHolder[count] = user;
				
					count++;
			}
		}	
		fclose(file);
}
Esempio n. 2
0
int main(int argc, char *argv[])
{
	char **split;
	char delim[] = ",\n";
	
	char *s;
	lex("target.txt", "key.txt", "mapped.txt");
	s = targetFile_read("mapped.txt");
	split = splitByDelim(s, delim);

	char *pattern = "((?:[a-z][a-z0-9_]*))(\\s*)(\\()(\\s*)(.*)(\\s*)(\\))";
	char *stub = targetFile_read("./stub/stub.c");
	int count = 0;

	for (; count < tokenized; count++) {
		split[count] = trimwhitespace(split[count]);
		regexStr restr = regexMatch(pattern, trimwhitespace(split[count]));
		strcat(stub, restr.substr[METHOD]);
		strcat(stub, "(");
	        strcat(stub, restr.substr[PARAM]);
	        strcat(stub, ");\n");
	}

	strcat(stub, "return 0;\n}");

	targetFile_write("gen.c", stub);
	system("gcc gen.c -o obj/gen helpers.h");
	system("obj/gen");
	
	return 0;
}
void getWords()
{
		char buf[256];
		FILE* file = fopen("hangman_text.txt", "r");
		int count = 0;
		
		while (fgets(buf, sizeof(buf), file))
		{							
					
					char *objectName = (char *)malloc(sizeof(10));
					strcpy(objectName, strtok(buf, ","));
					objectName = trimwhitespace(objectName);
					char *objectType = (char *)malloc(sizeof(10));
					strcpy(objectType, strtok(NULL, ","));
					objectType = trimwhitespace(objectType);
					word_t* Word = (word_t*)malloc(sizeof(word_t));	
					Word->object = objectName;
					Word->objectType = objectType;

					wordHolder[count] = Word;					
					
					count++;
		}		
		fclose(file);
		//return head;
	
}
Esempio n. 4
0
int main ( )
{
    char *command = malloc(1000*sizeof(char));
    char *user = getenv("USER");
    char hostname[1000];
    gethostname(hostname,1000);
    while (1)
    {
        char *home = malloc(1000*sizeof(char));
    	strcpy(home,"/home/");
    	home = strcat(home,user); 
    	char cwd[1000];
    	char *curr_dir = getcwd(cwd, sizeof(cwd));
    	char *display = malloc(1000*sizeof(char));
    	strcpy(display,user);
    	display = strcat(display,"@");
    	display = strcat(display,hostname);
    	display = strcat(display,":");
    	display = strcat(display,curr_dir);
        display = strcat(display,"$ ");
        printf("%s",display);
        readLine(command);
        while (command[0] == '\0')
        {
            printf("%s",display);
            readLine(command);
        }
        command = replace_str(command,"~",home);
        if( check_semicolon ){
        	command = trimwhitespace(command);
        	char *pch = strtok( command , ";" );
        	while( pch != NULL ){
        		ampercent = 0;
        		ampercent = check_ampercent(pch);
        		pch = replace_str(pch,"&"," ");
        		pch = trimwhitespace(pch);
        		if (strncmp (pch , "quit" , 4) == 0)
            		return 0;
        		if (strncmp (pch , "exit" , 4) == 0)
            		return 0;
        		parseCommandLine(pch);
        		pch = strtok( NULL , ";" );
        	}
        	continue;
        }
        if (strncmp (command , "quit" , 4) == 0)
            return 0;
        if (strncmp (command , "exit" , 4) == 0)
            return 0;
        parseCommandLine(command);
    }
    return 0;
}
Esempio n. 5
0
File: main.c Progetto: orls/Tigger
int listTasks(){
	/*This function does the following:
	 -open up the .tigger file
	 -print out all of the tasks in the .tigger file
	 -close the .tigger file
	 */
	char line[255];
	int count = 0;
	if(!tiggerExists()){
		return 0;
	}
	FILE *file = fopen(".tigger", "rt");
	if (COLOR_FLAG)
                fprintf_white(stdout, "\nLoading tasks from tigger...\n-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-\n");
        else
                printf("\nLoading tasks from tigger...\n-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-\n");
	while(fgets(line, 255, file) != NULL){
		if(!protectedText(line)){
			count += 1;
                        if (COLOR_FLAG) {
                                fprintf_yellow(stdout, "Task ");
        		        fprintf(stdout, "%d", count);
                                fprintf_yellow(stdout, ": \n");
		                fprintf_green(stdout, trimwhitespace(line));
                        } else {
			        printf("Task %d: \n", count);
			        printf("%s", trimwhitespace(line));
                        }
			printf("\n");

		}
	}
	if (count > 0){
		if (COLOR_FLAG) {
                        fprintf_blue(stdout, "You have ");
                        fprintf(stdout, "%d", count);
                        fprintf_blue(stdout, " tasks waiting to be completed.\n");
		        fprintf_white(stdout, "-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-\n");
                } else {
                        printf("You have %d tasks waiting to be completed.\n", count);
                        printf("-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-\n");
               }

	}else{
		if (COLOR_FLAG)
                        fprintf_blue(stdout, "Yay! You have no tasks remaining. Go have a beer.\n");
                else 
                        printf("Yay! You have no tasks remaining. Go have a beer.\n");
	}
	fclose(file);
	return 1;
}    
Esempio n. 6
0
void GFread(FILE *file,GF2n&m, FUNCTION&ff, GF2n&a,GF2n&b,GF2n&Px,GF2n&Py,GF2n&n,GF2n&Qx,GF2n&Qy)
{
	if(!file)
	{
		printf("error file status\n");
		return;
	}
	int i=0;
	char*input=new char[1000];
	char*left=new char[1000];
	char*right=new char[1000];char*tmp=new char[1000];
	size_t len = 1000;
	while(fgets(input,1000,file))
	{
		input=trimwhitespace(input);
		int pos=getFlagPos(input,'=');
		memset(left,0,1000);
		memset(right,0,1000);
		strncpy(left,input,pos);
		strncpy(right,input+pos+1,strlen(input)-pos-1);
		left=trimwhitespace(left);
		right=trimwhitespace(right);
		if(!strcmp(left,"m"))
			getFromStr(right,m);		
		else if(!strcmp(left,"f"))
		{
			memset(tmp,0,1000);
			strncpy(tmp,right+1,strlen(right)-2);
			int len=0;
			char**result=str_split(tmp,len);
			ff.f=(GF2n*)malloc(sizeof(GF2n)*len);ff.num=len;
			for(int i=0;i<len;i++)
				getFromStr(trimwhitespace(result[i]),ff.f[i]);
		}
		else if(!strcmp(left,"a"))
			getFromStrConvertHexToDec(right,a);
		else if(!strcmp(left,"b"))
			getFromStrConvertHexToDec(right,b);
		else if(!strcmp(left,"P_x"))
			getFromStrConvertHexToDec(right,Px);
		else if(!strcmp(left,"P_y"))
			getFromStrConvertHexToDec(right,Py);
		else if(!strcmp(left,"n"))
			getFromStrConvertHexToDec(right,n);
		else if(!strcmp(left,"Q_x"))
			getFromStrConvertHexToDec(right,Qx);
		else if(!strcmp(left,"Q_y"))
			getFromStrConvertHexToDec(right,Qy);
	}
}
Esempio n. 7
0
static int
get_file_type (FILE* infile)
{
    char metadata[100];

    if ((fgets (metadata, 100, infile)) == NULL)
        return -1;

    if (strcmp (trimwhitespace (metadata), VARNAM_WORDS_EXPORT_METADATA) == 0)
        return _WORDS_IMPORT;
    else if (strcmp (trimwhitespace (metadata), VARNAM_PATTERNS_EXPORT_METADATA) == 0)
        return _PATTERNS_IMPORT;

    return -1;
}
Esempio n. 8
0
__declspec( dllexport ) void get_table_strings(HMODULE oleAccModule, HWND controlHwnd, void **tableStrings, long *numberOfRowsOut, long *numberOfColumnsOut) {
	// * to *[] to *[] to * string
	IAccessible *pAccessible ;
	LPFNACCESSIBLEOBJECTFROMWINDOW lpfnAccessibleObjectFromWindow ;

	lpfnAccessibleObjectFromWindow = (LPFNACCESSIBLEOBJECTFROMWINDOW)GetProcAddress(oleAccModule, "AccessibleObjectFromWindow");

	if (HRESULT hResult = lpfnAccessibleObjectFromWindow(controlHwnd, OBJID_CLIENT, IID_IAccessible, (void**)&pAccessible) == S_OK) {
		int numberOfRows = get_number_of_rows(pAccessible) ;   // including the header
		long numberOfColumns = 3 ;
		char ***table_rows ;
		char **pHeaderNames ;

		find_column_headers(pAccessible, &pHeaderNames, &numberOfColumns) ;
		
		table_rows = (char ***)malloc(sizeof(char*) * numberOfRows) ;
		table_rows[0] = pHeaderNames ;

		for (int row = 1; row < numberOfRows; row++) {
			char **table_row = (char **)malloc(sizeof(char*) * numberOfColumns) ;

			char *mainItem = (char *)malloc(sizeof(char) * BUFFER_SIZE) ;
			get_name(row, pAccessible, mainItem) ;

			char *description = (char *)malloc(sizeof(char) * 2048) ;
			get_description(row, pAccessible, description) ;

			char *token ;
			if (strlen(description) > 0)
				token = strtok(description, ",") ;
			else
				token = NULL ;

			for (int column = 0; column < numberOfColumns; column++) {
				if (column == 0)
					table_row[column] = mainItem ;
				else {
					char *item = (char *)malloc(sizeof(char) * BUFFER_SIZE) ;

					if (token != NULL) {
						strcpy(item, token) ;
						token = strtok(NULL, ",") ;
					} else
						strcpy(item, "\0") ;

					table_row[column] = remove_column_header_name(pHeaderNames[column], trimwhitespace(item)) ;
				}
			}

			table_rows[row] = table_row ;
		}

		*tableStrings = table_rows ;
		*numberOfRowsOut = numberOfRows ;
		*numberOfColumnsOut = numberOfColumns ;
	} else {
		*numberOfRowsOut = 0 ;
		*numberOfColumnsOut = 0 ;
	}
}
Esempio n. 9
0
void *thread_read_serial(void *arg) {
    while(1) {
        // serial
        int n;
        #ifdef SERIAL_IS_A_FILE
        n = fread((serialbuf + serialbufpos), 1, MAXBUFLEN - (serialbufpos + 1), serialfd);
        #else
        n = read (serialfd, (serialbuf + serialbufpos), MAXBUFLEN - (serialbufpos + 1));
        printf("[SERIAL READING] %d bytes\n", n);
        #endif
        if(n > 0) {
            printf("[SERIAL] %s\n", serialbuf);

            int i = 0;
            for(i = 0; i < n; i++) if(serialbuf[serialbufpos + i] == '\n') break;
            serialbufpos += n;

            if(i < n) {
                // found breakline
                serialbuf[serialbufpos - 1] = '\0';
                trimwhitespace(serialbuf);
                serialbufpos = 0;
                
                do_serial(serialbuf);
            }
        }
    }
}
Esempio n. 10
0
void moreMatch(char *line)
{
	line=trimwhitespace(line);
	
	if(line[strlen(line)-1]!=';')	//not a function declaration
		return;

	if(strstr("if(",line)==NULL && strstr("for(",line)==NULL && strstr("while(",line)==NULL  )	//not if while for
		funcCount++;

}
Esempio n. 11
0
/**
* A general purpose function for ensuring the current token is of a valid
* register type. Note, the token is rejected if the register is not exactly 3
* characters or does not start with a '$'.
*
* @param prog Used for error reporting
* @param suppress suppresses error messages if 1
* @return 0 on failure, otherwise the register string that was
* parsed.
*/
char *read_reg(struct program *prog, short suppress){
	char * tok = strtok(0, ", \t");
	trimwhitespace(tok);

	// should only be 3 characters (may change, but sufficient for now)
	if(strlen(tok) != 3 || tok[0] != '$'){
		print_expected_ident(tok, "$", prog);
		tok = 0;
	}
	return tok;
}
Esempio n. 12
0
File: main.c Progetto: orls/Tigger
int deleteTask(char * task){ 
	char line[255];
	const char *TIGGER_FILE_NAME = ".tigger";
	const char *TIGGER_TEMP = ".tigger_temp";
	int found = 0;
	if(task == NULL){
		if (COLOR_FLAG)
                        fprintf_red(stdout, "Can't delete a null task.\n");
                else
                        printf("Can't delete a null task.\n");
		return 0;
	}     
	FILE *file = fopen(TIGGER_FILE_NAME, "r");
	FILE *temp = fopen(TIGGER_TEMP, "w");
	while(fgets(line, 255, file) != NULL){
		if(strcmp(trimwhitespace(line), trimwhitespace(task)) != 0){
                        fprintf(temp, "%s",line);
			fprintf(temp, "\n");  
		}else{
			found = 1;
		}
	}
	fclose(file);
	fclose(temp);
	if(found){
		if (COLOR_FLAG)
                        fprintf_blue(stdout, "We found your task and deleted it.\n");
                else
                        printf("We found your task and deleted it.\n");
		system("rm .tigger");
		rename(TIGGER_TEMP, TIGGER_FILE_NAME);  
		return 1;
	}else{
		system("rm .tigger_temp");
		if (COLOR_FLAG)
                        fprintf_red(stdout, "Sorry we couldn't find the task to delete.\n");
                else
                        printf("Sorry we couldn't find the task to delete.\n");
		return 0;
	}
}
Esempio n. 13
0
void runExclamationCommand(char *args[100],char paths[100],int args_len,char history[1000][1000],char *choice,char *args_temp,int *history_index){
	// run the command with ! followed either by the name of command or by the number of the command
	char temp4[1000];
	memset(temp4, ' ', 1000);
	//printf("%s\n","run exclamation" );
	char command[100];
	char cmd[100];
	sscanf(args[0] ,"!%s ", command);
	//printf("%s\n", command);
	if(isdigit(command[0])){								// integer
		int num = atoi(command);
		printf("%d\n", num);
		for(int k=0;k<*history_index;k++){
			printf("%d\n",k );
			if(num==*history_index){
				//printf("Number found%d\n",num );
				PreArgsProcessing(args,paths,&args_len,choice,args_temp);
				return;
			}
		}
		//args[0]=historyChecking(history);
		forkMethod(args,paths,args_len);
	}
	else if(isalpha(command[0])){								//string
		//printf("%s\n", command);
		args[0]=command;
		for(int k=0;k<*history_index;k++){
			if(choice==history[*history_index]){
				PreArgsProcessing(args,paths,&args_len,choice,args_temp);
				return;
			}
		}
		//printf("%s\n",args[0]);
		strcpy(temp4,args[0]);
		strcat(temp4," ");
		//printf("%d\n",args_len);
		//printf("%s\n",temp4);
		for(int o=1;o<args_len-2;o++){
			strcat(temp4,args[o]);
			strcat(temp4," ");
			//printf("in loop%s\n",temp4);
		}
		if(args_len>2){
			strcat(temp4,args[args_len-2]);
		}
		
		//printf("out of the loop%s\n",temp4);
		strcpy(choice,temp4);
		choice=trimwhitespace(choice);
		// /printf("Exclamation args is %s\n",args[] );
		//forkMethod(args,paths,args_len);
	}	
}
Esempio n. 14
0
static int analyze_pattern (FILE *ap_file, char *ap_str, keyval_t **app_last_kv,
                            tiz_rcfile_t *ap_tiz_rcfile)
{
  if (strstr (ap_str, "#"))
    {
      char *str = trimcommenting (trimwhitespace (ap_str));
      TIZ_LOG (TIZ_PRIORITY_TRACE, "Comment : [%s]", trimwhitespace (str));
      (void)str;
    }
  else if ('[' == ap_str[0] && ']' == ap_str[strlen (ap_str) - 1])
    {
      char *str = trimsectioning (ap_str);
      TIZ_LOG (TIZ_PRIORITY_TRACE, "Section : [%s]", str);
      (void)str;
    }
  else if (strstr (ap_str, "="))
    {
      TIZ_LOG (TIZ_PRIORITY_TRACE, "key-value pair : [%s]", ap_str);
      return extractkeyval (ap_file, ap_str, app_last_kv, ap_tiz_rcfile);
    }

  return 0;
}
Esempio n. 15
0
void loadsounds()
{
	//printf("loadsound\n");
        sfzreg* r=regions;
	printf("\n");
	int x=0;
        while(r!=NULL)
        {
		//TODO evita i duplicati
                if(r->sample!=NULL) r->sound=addsound(trimwhitespace(r->sample));
                r=(sfzreg*)r->next;
		loadBar(x,nregions,BARRESOLUTION,BARWIDTH);
		x++;
        }
	printf("\n");
}
Esempio n. 16
0
/**
 * fprintf-like helper function for logging debug
 * messages.
 */
void
MHD_DLOG (const struct MHD_Daemon *daemon, const char *format, ...) {
  va_list va;
  char sbuf[512];

va_start(va, format);
vsnprintf(sbuf, 512, format, va);
va_end(va);

  if ((daemon->options & MHD_USE_DEBUG) == 0)
    return;
  //va_start (va, format);
  //daemon->custom_error_log (daemon->custom_error_log_cls, format, va);
  loghandle(LOG_ERR, FALSE, "%s", trimwhitespace(sbuf) );
  //va_end (va);
}
Esempio n. 17
0
void load_string_list(char *fname, struct list_head *string_list)
{
	char s[256];
	FILE *fptr;
	struct string_item *item;

	INIT_LIST_HEAD(string_list);

	if ((fptr = fopen(fname, "r"))) {
		while (fgets(s, 256*sizeof(char), fptr)){
			if (s[0] == '#') continue;
			item = malloc(sizeof(struct string_item));
			item->info = malloc((1+strlen(s))*sizeof(char));
			strcpy(item->info, s);
			item->info = trimwhitespace(item->info);
			list_add_tail(&item->string_list, string_list);
		}
	}
}
Esempio n. 18
0
//Read from pipe file... command execution latter to come...
void svPipeScan(int pipefileid){
	int num, stop;
	char buffer[128] = {0}, bufferstrip[128] = {0};

if(pipefileid < 0 )
return;

num = read(pipefileid, buffer, sizeof(buffer));
buffer[num] = '\0';
stop = 0;
sprintf(bufferstrip,"%s",trimwhitespace(buffer));
sprintf(buffer,"%s",bufferstrip);

if ( ( num > 0 ) && strlen(buffer) ) {
	if( !(strcmp(buffer,"stop") ) ) {
		sysconfig.shutdown = true;
		stop = 1;
	}
	#if IRCBOT_SUPPORT
	 else if( !( strncmp(buffer, "bot", 3) ) ) {
		if( !ircbot_command(buffer) ) {
			loghandle(LOG_INFO, false, "Bot subfunction reported error with command: \"%s\"", buffer);
			svPipeSend(0, "Bot subfunction reported error with command: \"%s\"\n",buffer );
		}
	}
	#endif
	 else {
		loghandle(LOG_INFO, false, "Piping Error Unrecognized command size \"%d\" line \"%s\"", num, buffer);
	}
}

if( stop ) {
	svPipeSend(0,"Server is shutting down as requested..");
	info( "Shutdown command recived from Pipe." );
}

if ( num > 0 ) {
	svPipeSend(0,"<<<END>>>");
}

return;
}
Esempio n. 19
0
void interactive(int sockfd, char* remaddr, int port)
{
  // Initializing remote address!?
  struct sockaddr_in serv_addr;
  int slen=sizeof(serv_addr);
  struct sockaddr_in rem_addr;
  socklen_t addrlen = sizeof(rem_addr);
  bzero(&serv_addr, sizeof(serv_addr));
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_port = htons(port);
  if (inet_aton(remaddr, &serv_addr.sin_addr)==0) //just converting ip to bin
    err("invalid address failed\n");

  int recvlen;
  char buf[BUFLEN];
  int i;
  for (i=0; i<BUFLEN;i++)
    buf[i] = ' ';
  while(1)
  {
    printf(">");
    scanf("%[^\n]",buf); // here we block :<, need to use threads or something
    getchar();
    if(strcmp(buf,"exit") == 0)
      exit(0);

    char msg[BUFLEN];
    int msglen = trimwhitespace(&msg, BUFLEN, buf);
    printf("trying to send \"%s\", %d bytes\n", msg,msglen);
    //send our message
    if (sendto(sockfd, msg, msglen, 0, (struct sockaddr*)&serv_addr, slen)==-1)
      err("sendto() failed");
    //listen to what server send us... is this blocking!? lets expect that its not
    recvlen = recvfrom(sockfd, buf, BUFLEN, 0, (struct sockaddr *)&rem_addr, &addrlen);
    if (recvlen > 0) {
      buf[recvlen] = 0;
      printf("server sent %d bytes: \"%s\"\n",recvlen, buf);
    }
  }

  close(sockfd);
}
Esempio n. 20
0
// this method is for the checking the paramntere defined and if the command is ther , it will return the path of the file to be exected
// otherwise return something to distinguish that it is an error.
char* checkingParamter(char *args[100],char paths[100],int args_len,char *path[100],DIR * dir[100],int path_len, struct dirent * file,char *newpath){
	for(int i=0;i<path_len;i++){
		dir[i] = opendir( path[i] );
		while ( ( file = readdir( dir [i]) ) != NULL )
		{
			if(strlen(file->d_name)==strlen(args[0])){
				if(strncmp(file->d_name,args[0],strlen(args[0]))==0){	
		    		break;
	   			} 	
			}    
		}
		if(file==NULL){
	    	for(int i=0; i<args_len; i++){
					if(args[i]!=NULL){
						args[i] = trimwhitespace(args[i]);
					}
				} 	
	    	
	    	newpath=NULL;  	
		}
		else{
			//checking various commands in /bin folder
			//printf( "found %s\n", file->d_name );
			strcpy(paths,path[i]);
			strcat(paths,"/");
			strcat(paths,file->d_name);
			//printf( "returned path%s", paths);	
			newpath=paths;
			break;
		}

	} 
	if(newpath==NULL){
		printf("ERROR: command %s not found\n", args[0]);
	}
	else {

	}
	
	return newpath;
}
Esempio n. 21
0
int populate_blacklist (char *blacklist)
{
	FILE *file = fopen ( blacklist, "r" );
	total_user = 0;

	if (file != NULL) {
		pthread_mutex_lock(&lock);
		char line [1000];
		while(fgets(line,sizeof line,file)!= NULL) {
			blacklist_users[total_user++] = trimwhitespace(strdup(line));
		}

		fclose(file);
		pthread_mutex_unlock(&lock);
	}
	else {
		perror(blacklist);
		return -1;
	}
	print_user();
	return 0;
}
Esempio n. 22
0
void forkMethod(char *args[100],char paths[100],int args_len){
	pid_t pid;  
		// printf( "abc");	  
		pid = fork(); 																	//forking a process
		if(pid<0){
			printf("error !!");
		}	
		if(pid == 0){
			//printf("HCild\n");
			for(int i=0; i<args_len; i++){
				if(args[i]!=NULL){
					args[i] = trimwhitespace(args[i]);
				}
			}
			execv(paths, args);
		}
		else{
			//printf("parent\n");
			int status;
			int termChild = wait(&status);
			//printf("terminated");
		}		 		 
}
Esempio n. 23
0
TypGraphe* parse(FILE* f)
{
    char buf[PARSER_LINE_BUFFER_SIZE];
    char* read;
    size_t line = 0;
    long int sommet, sommetParent, poids;

    bool orienter;
    TypGraphe* res = NULL;
    errorcode err;
    if (f)
    {
        //read #
        line += 1;
        read = fgets(buf, sizeof (buf), f);
        if (read)
        {
            read = trimwhitespace(buf);
            if (!read || *read != '#')
            {
                printf("erreur parsage line %u; '%s' attendu, on a : '%s'", line,
                       "#", read ? read : "EOF");
                return NULL;
            }
        }
        else
        {
            printf("erreur parsage line %u; EOF", line);
            return NULL;
        }

        //read nombre maximum de sommets
        line += 1;
        read = fgets(buf, sizeof (buf), f);
        if (read)
        {
            read = trimwhitespace(buf);
            sommet = strtol(read, NULL, 0);
            if (!sommet)
            {
                printf("erreur parsage line %u; '%s' attendu, on a : '%s'", line,
                       "CHIFFRE", read ? read : "EOF");
                return NULL;
            }
        }
        else
        {
            printf("erreur parsage line %u; EOF", line);
            return NULL;
        }

        //read #
        line += 1;
        read = fgets(buf, sizeof (buf), f);
        if (read)
        {
            read = trimwhitespace(buf);
            if (!read || *read != '#')
            {
                printf("erreur parsage line %u; '%s' attendu, on a : '%s'", line,
                       "#", read ? read : "EOF");
                return NULL;
            }
        }
        else
        {
            printf("erreur parsage line %u; EOF", line);
            return NULL;
        }

        //read 'o' ou 'n'
        line += 1;
        read = fgets(buf, sizeof (buf), f);
        if (read)
        {
            read = trimwhitespace(buf);
            if (!read || !(*read == 'o' || *read == 'n'))
            {
                printf("erreur parsage line %u; '%s' attendu, on a : '%s'", line,
                       "o|n", read ? read : "EOF");
                return NULL;
            }
            orienter = *read == 'o';
        }
        else
        {
            printf("erreur parsage line %u; EOF", line);
            return NULL;
        }

        res = newTypGraphe(sommet, orienter);
        if (!res)
        {
            return NULL;
        }

        //read #
        line += 1;
        read = fgets(buf, sizeof (buf), f);
        if (read)
        {
            read = trimwhitespace(buf);
            if (!read || *read != '#')
            {
                printf("erreur parsage line %u; '%s' attendu, on a : '%s'", line,
                       "#", read ? read : "EOF");
                return NULL;
            }
        }
        else
        {
            printf("erreur parsage line %u; EOF", line);
            return NULL;
        }

        //maintenant on parse les sommets et les arretes
        do
        {
            line += 1;
            read = fgets(buf, sizeof (buf), f);
            if (read)
            {
                read = trimwhitespace(buf);
                char* token = strtok(read, ":");
                read = trimwhitespace(token);
                char *endptr;
                sommetParent = strtol(read, &endptr, 0);
                if (read == endptr)
                {
                    printf("erreur parsage line %u; '%s' attendu, on a : '%s'", line,
                           "CHIFFRE", read ? read : "EOF");
                    return NULL;
                }
                err = insertionSommetTypGraphe(res, sommetParent);
                if (err < 0 && err != -2)
                {
                    handle_error_code(err);
                    return NULL;
                }

                token = strtok(NULL, ","); //les arretes
                while (token)
                {
                    int scanfres = sscanf(token, " ( %u / %u ) ", &sommet, &poids);
                    if (scanfres != 2)
                    {
                        printf("erreur parsage line %u; une definition d'arrete est attendue", line);
                    }
                    if (!checkSommetExist(res, sommet))
                    {
                        //crée automatiquement le sommet
                        insertionSommetTypGraphe(res, sommet);
                    }
                    err = insertionAreteTypGraphe(res, sommetParent, sommet, poids);
                    if (err < 0 && !err == -5)
                    {
                        handle_error_code(err);
                        return NULL;
                    }
                    token = strtok(NULL, ",");
                }
            }
        }
        while (read);

    }
    return res;
}
Esempio n. 24
0
/*
 * assemble
 *
 * Calls firstParse to replace symbols.
 *
 * params:  char * String location of assembly file
 * 
 * return:  start location of instructions
 */
unsigned int assemble (char * loc_assem_file, unsigned int * instructions_array) {
    
    FILE * rfp; //read file pointer
//    FILE * wfp;
    int line_buffer_size = sizeof(char) * 100;
    unsigned int start_loc;
    unsigned int opcode;
    int line_num = 0;
    char * loc_object_file;
    char * line_ptr = malloc(line_buffer_size);
    char * line_ptr_copy;
    char * line_malloc_loc = line_ptr;
    char * token;
    char * token2;
    ssize_t num_char_read;
    unsigned int token_in_bits; //uint32_t token_in_bits;
    unsigned int bit_instruct_32; //uint32_t bit_instruct_32;
    map_t map_clone;
    
    
    //open assembly source
    rfp = fopen(loc_assem_file, "r");
    if (rfp == NULL)
        exit(EXIT_FAILURE);
    
    //create file name for output object file
    loc_object_file = malloc(sizeof(char) * 100);
    strcpy(loc_object_file, strtok(loc_assem_file, "."));
    strcat(loc_object_file, ".object");
    
    //open object file to write to
//    wfp = fopen("./test.object", "w");
//    if (wfp == NULL)
//        exit(EXIT_FAILURE);
    
    ASSEMBLER_STR_p this = ASSEMBLER_constructor();
    
    //first parse (for labels)
    firstParse(this, rfp);
    
    
    while (fgets(line_ptr, line_buffer_size, rfp)) {
        line_ptr = trimwhitespace(line_ptr);
        
        //if contains label, remove label
        if (strstr(line_ptr, ":") != '\0') {
            strsep(&line_ptr, ":");
            //if instructions follow ":", don't use "continue"
            line_ptr = trimwhitespace(line_ptr);
            if (line_ptr == '\0' || line_ptr[0] == ';') {
                continue;
            }
        }
        
        //skip directives and comments
        if (line_ptr[0] == '.' || line_ptr[0] == ';' || line_ptr[0] == '\0') {
            continue;
        }
        
        line_ptr_copy = line_ptr;
        bit_instruct_32 = 0;
        token = strsep(&line_ptr_copy, " ");
        stringToLowerCase(token);
        line_ptr = line_ptr_copy;
        
        //take opcode, put it in bit form
        map_clone = this->operations_map; 
        hashmap_get(map_clone, token, &token_in_bits); 
        
        //bitshift to appropriate position in 32 bit bitcode
        opcode = token_in_bits;
        bit_instruct_32 = token_in_bits << 28; //bits 0-3
        
        line_ptr_copy = line_ptr;

        int bitshift = 24; 
        while (line_ptr_copy != NULL) { 
            if (strstr(line_ptr_copy, ",") != NULL) { //if contains comma
                token = strsep(&line_ptr_copy, ","); 
                stringToLowerCase(token); 
                line_ptr_copy = trimwhitespace(line_ptr_copy);
                line_ptr = line_ptr_copy;
            } else { //in the case of last element
                if (strstr(line_ptr_copy, ";") != NULL) { //if contains comment ";"
                    token = strsep(&line_ptr_copy, ";");
                } else {
                    token = line_ptr_copy;
                }
                token = trimwhitespace(token);
                stringToLowerCase(token);
                line_ptr_copy = NULL;
            }

            if (line_ptr_copy == NULL && (opcode == 3 || opcode == 4)) { //lw and sw instructions like lw $a0, 20($a1)
                line_ptr_copy = token;
                line_ptr = line_ptr_copy;
                token = strsep(&line_ptr_copy, "(");
                token2 = strsep(&line_ptr_copy, ")");
                map_clone = this->registers_map;
                hashmap_get(map_clone, token2, &token_in_bits);
                line_ptr_copy = line_ptr;
                bit_instruct_32 = bit_instruct_32 | (token_in_bits << bitshift);
                token_in_bits = atoi(token);
                bit_instruct_32 = bit_instruct_32 | token_in_bits;
                line_ptr_copy = NULL;
            } else if (line_ptr_copy == NULL && opcode == 5) { //if last object is label
                line_ptr = line_ptr_copy;
                int *label_line_offset;
                stringToLowerCase(token);
                map_clone = this->symbol_table_map;
                hashmap_get(map_clone, token, &label_line_offset); //printf("%d\n\n",*label_line_offset);
                line_ptr_copy = line_ptr;
                bit_instruct_32 = bit_instruct_32 | (0x0000FFFF & (*label_line_offset - line_num - 1)); //copy offset from current instruct line num into bit_instruct_32
                line_ptr_copy = NULL;
            } else if (line_ptr_copy == NULL && opcode == 6) { //if instruction is jalr
                line_ptr = line_ptr_copy;
                int *label_line_offset;
                stringToLowerCase(token);
                map_clone = this->registers_map;
                hashmap_get(map_clone, token, &token_in_bits);
                line_ptr_copy = line_ptr;
                bit_instruct_32 = bit_instruct_32 | (0x0F000000 & (token_in_bits << bitshift));
                line_ptr_copy = NULL;
            }else if (token[0] != '$') { //if immediate value
                line_ptr = line_ptr_copy;
                token_in_bits = atoi(token); 
                //write 16 bit number into last 32 bits of bit_instruct_32
                token_in_bits = token_in_bits & 0x0000FFFF;
                bit_instruct_32 = bit_instruct_32 | token_in_bits;
                line_ptr_copy = line_ptr;
            } else { // else if register
                line_ptr = line_ptr_copy;
                stringToLowerCase(token);
                map_clone = this->registers_map; 
                hashmap_get(map_clone, token, &token_in_bits); 
                bit_instruct_32 = bit_instruct_32 | (token_in_bits << bitshift); 
                line_ptr_copy = line_ptr;
            }
            
            bitshift -= 4; //printf("%d\n", this->start_loc);
        }

        //write bitcode to object file
//        fprintf(wfp, "%08x", bit_instruct_32); 
//        printf("%08x\n", bit_instruct_32);
        instructions_array[line_num] = bit_instruct_32;
        
        
        line_num += 1;
        line_ptr = line_malloc_loc;
    }
    
    start_loc = this->start_loc;
    
    fclose(rfp);
//    fclose(wfp);
    //free(line_ptr);
    //free(loc_object_file);
    
    ASSEMBLER_destructor(this);
    //print_keyset(this->operations_map);
    //print_keyset(this->symbol_table_map);
    //print_keyset(this->registers_map);
    
    return start_loc;
}
Esempio n. 25
0
int
init_acl(const char *path)
{
    // initialize ipset
    ipset_init_library();

    ipset_init(&white_list_ipv4);
    ipset_init(&white_list_ipv6);
    ipset_init(&black_list_ipv4);
    ipset_init(&black_list_ipv6);
    ipset_init(&outbound_block_list_ipv4);
    ipset_init(&outbound_block_list_ipv6);

    cork_dllist_init(&black_list_rules);
    cork_dllist_init(&white_list_rules);
    cork_dllist_init(&outbound_block_list_rules);

    struct ip_set *list_ipv4  = &black_list_ipv4;
    struct ip_set *list_ipv6  = &black_list_ipv6;
    struct cork_dllist *rules = &black_list_rules;

    FILE *f = fopen(path, "r");
    if (f == NULL) {
        LOGE("Invalid acl path.");
        return -1;
    }

    char buf[257];
    while (!feof(f))
        if (fgets(buf, 256, f)) {
            // Trim the newline
            int len = strlen(buf);
            if (len > 0 && buf[len - 1] == '\n') {
                buf[len - 1] = '\0';
            }

            char *comment = strchr(buf, '#');
            if (comment) {
                *comment = '\0';
            }

            char *line = trimwhitespace(buf);
            if (strlen(line) == 0) {
                continue;
            }

            if (strcmp(line, "[outbound_block_list]") == 0) {
                list_ipv4 = &outbound_block_list_ipv4;
                list_ipv6 = &outbound_block_list_ipv6;
                rules     = &outbound_block_list_rules;
                continue;
            } else if (strcmp(line, "[black_list]") == 0
                       || strcmp(line, "[bypass_list]") == 0) {
                list_ipv4 = &black_list_ipv4;
                list_ipv6 = &black_list_ipv6;
                rules     = &black_list_rules;
                continue;
            } else if (strcmp(line, "[white_list]") == 0
                       || strcmp(line, "[proxy_list]") == 0) {
                list_ipv4 = &white_list_ipv4;
                list_ipv6 = &white_list_ipv6;
                rules     = &white_list_rules;
                continue;
            } else if (strcmp(line, "[reject_all]") == 0
                       || strcmp(line, "[bypass_all]") == 0) {
                acl_mode = WHITE_LIST;
                continue;
            } else if (strcmp(line, "[accept_all]") == 0
                       || strcmp(line, "[proxy_all]") == 0) {
                acl_mode = BLACK_LIST;
                continue;
            } else if (strcmp(line, "[remote_dns]") == 0) {
                continue;
            }

            char host[257];
            int cidr;
            parse_addr_cidr(line, host, &cidr);

            struct cork_ip addr;
            int err = cork_ip_init(&addr, host);
            if (!err) {
                if (addr.version == 4) {
                    if (cidr >= 0) {
                        ipset_ipv4_add_network(list_ipv4, &(addr.ip.v4), cidr);
                    } else {
                        ipset_ipv4_add(list_ipv4, &(addr.ip.v4));
                    }
                } else if (addr.version == 6) {
                    if (cidr >= 0) {
                        ipset_ipv6_add_network(list_ipv6, &(addr.ip.v6), cidr);
                    } else {
                        ipset_ipv6_add(list_ipv6, &(addr.ip.v6));
                    }
                }
            } else {
                rule_t *rule = new_rule();
                accept_rule_arg(rule, line);
                init_rule(rule);
                add_rule(rules, rule);
            }
        }

    fclose(f);

    return 0;
}
Esempio n. 26
0
File: settings.c Progetto: ihbar/fpp
int loadSettings(const char *filename)
{
	if (!FileExists(filename)) {
		LogWarn(VB_SETTING,
			"Attempted to load settings file %s which does not exist!", filename);
		return -1;
	}

	FILE *file = fopen(filename, "r");

	if (file != NULL)
	{
		char * line = NULL;
		size_t len = 0;
		ssize_t read;
		int sIndex = 0;

		while ((read = getline(&line, &len, file)) != -1)
		{
			if (( ! line ) || ( ! read ) || ( read == 1 ))
				continue;

			char *key = NULL, *value = NULL;	// These are values we're looking for and will
												// run through trimwhitespace which means they
												// must be freed before we are done.

			char *token = strtok(line, "=");
			if ( ! token )
				continue;

			key = trimwhitespace(token);
			if ( !strlen(key) )
			{
				free(key);
				continue;
			}

			token = strtok(NULL, "=");
			if ( !token )
			{
				fprintf(stderr, "Error tokenizing value for %s setting\n", key);
				free(key);
				continue;
			}
			value = trimwhitespace(token);

			parseSetting(key, value);

            settings.keyVal[key] = strdup(value);

			if ( key )
			{
				free(key);
				key = NULL;
			}

			if ( value )
			{
				free(value);
				value = NULL;
			}
		}

		if (line)
			free(line);
	
		fclose(file);
	}
	else
	{
		LogWarn(VB_SETTING, "Warning: couldn't open settings file: '%s'!\n", filename);
		return -1;
	}

	if (getDaemonize())
		SetLogFile(getLogFile());
	else
		SetLogFile("");

	return 0;
}
Esempio n. 27
0
void parents(char *parentFunction, char *childFunction, char *parentPath, char *childPath) {
    
    //printf("parentFunction:: %s, childFunction:: %s, parentPath:: %s, childPath:: %s\n", parentFunction, childFunction, parentPath, childPath );
    
    char buff[256];
    char flist[1124];
    sprintf(flist,"%s","");
    //printf("FLIST:%s\n", flist);
    
    const char space[2] = " ";
    int add = 0; //indicator
    
    //Write the PARENT > CHILD file
    //=============================
    char *function = concat(parentPath, parentFunction);
    
    FILE *f = fopen(function, "r");
    if (f == NULL)
    {
        //printf("File %s does not exist!\n", function);
        //exit(1);
    }
    
    //-----------------------------------------------------------------------
    if (f != NULL) {
        while ((fgets(buff, sizeof(buff), f)) != NULL) {
            trimwhitespace(buff);
            //printf("BUFF:  %s\n", buff);
            sprintf(flist,"%s %s",flist, buff);
        }
    }
    fclose(f);
    
    if (f != NULL) {
        //printf("PARENT: %s\n", flist);
        char *token = strtok(flist, space);
        while (token != NULL) {
            if (strcmp(token, childFunction) == 0) {
                add = 1;
            }
            token = strtok(NULL, space);
        }
    }
    else {
        add = 0;
    }

    
    f = fopen(function, "a");
    //fprintf(f, "%s\n", childFunction);
    if (add == 0) {
        fprintf(f, "%s\n", childFunction);
    }
    fclose(f);
    
    
    //Write the CHILD > PARENT File
    //=============================
    function = concat(childPath, childFunction);
    
    FILE *g = fopen(function, "a");
    if (g == NULL)
    {
        printf("parents -> File %s could not be opened!\n", function);
        asl_log(NULL, NULL, ASL_LEVEL_ERR, "CodeMap parents -> File %s could not be opened!\n", function);
        //exit(1);
    }
    
    if (g != NULL) {
        while ((fgets(buff, sizeof(buff), g)) != NULL) {
            trimwhitespace(buff);
            //printf("BUFF:  %s\n", buff);
            sprintf(flist,"%s %s",flist, buff);
        }
    }
    //fclose(f);
    
    if (g != NULL) {
        //printf("child: %s\n", flist);
        char *token = strtok(flist, space);
        while (token != NULL) {
            if (strcmp(token, childFunction) == 0) {
                add = 1;
            }
            token = strtok(NULL, space);
        }
    }
    else {
        add = 0;
    }
    
    g = fopen(function, "a");
    //fprintf(f, "%s\n", childFunction);
    if (add == 0) {
        fprintf(g, "%s\n", parentFunction);
    }
    
    fclose(g);

    
}
Esempio n. 28
0
/*
 * This function will configure on the fly the php like php.ini will do
 */
static void vhx_php_config(request_rec * r, vhx_config_rec * vhr, char *path, char *phpoptstr)
{
	/*
	 * Some Basic PHP stuff, thank to Igor Popov module
	 */
	apr_table_set(r->subprocess_env, "PHP_DOCUMENT_ROOT", path);
	//zend_alter_ini_entry("doc_root", sizeof("doc_root"), path, strlen(path), 4, 1);
	zend_alter_ini_entry("doc_root", sizeof("doc_root"), path, strlen(path), ZEND_INI_SYSTEM, ZEND_INI_STAGE_ACTIVATE);

	/*
	 * vhx_PHPopt_fromdb
	 */
	if (vhr->phpopt_fromdb) {
		VH_AP_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r, "vhx_php_config: PHP from DB engaged");
		char           *retval;
		char           *state;
		char           *myphpoptions;

		myphpoptions = apr_pstrdup(r->pool, phpoptstr);
		if(myphpoptions != NULL) {
			VH_AP_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r, "vhx_php_config: DB => %s", myphpoptions);

			if ((ap_strchr(myphpoptions, '=') != NULL)) {
				/* Getting values for PHP there so we can proceed */

				retval = apr_strtok(myphpoptions, ";", &state);
				while (retval != NULL) {
					char           *key = NULL;
					char           *val = NULL;
					char           *strtokstate = NULL;

					key = apr_strtok(retval, "=", &strtokstate);
					val = apr_strtok(NULL, "=", &strtokstate);

					if(key != NULL && val != NULL) {
						key = trimwhitespace(key);
						val = trimwhitespace(val);
						VH_AP_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r, "vhx_php_config: Zend PHP option => %s => %s", key, val);
						//zend_alter_ini_entry(key, strlen(key) + 1, val, strlen(val), 4, 16);
						zend_alter_ini_entry(key, strlen(key) + 1, val, strlen(val), ZEND_INI_SYSTEM, ZEND_INI_STAGE_RUNTIME);

						if(apr_strnatcasecmp(key, "display_errors") == 0) {
							vhr->display_errors = atoi(val);
						}

					} else if( key != NULL && val == NULL) {
						VH_AP_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r, "vhx_php_config: PHP option key '%s' had empty value, skipping...", key);
					}

					retval = apr_strtok(NULL, ";", &state);
				}
			}
		}
		else {
			VH_AP_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r, "vhx_php_config: no PHP options found in DB");
		}
	}

	/*
	 * vhx_PHPopen_baserdir    \ vhx_append_open_basedir |  support
	 * vhx_open_basedir_path   /
	 */
	if (vhr->open_basedir) {
		if (vhr->append_basedir && vhr->openbdir_path) {
			/*
			 * There is a default open_basedir path and
			 * configuration allow appending them
			 */
			char *obasedir_path;

			if (vhr->path_prefix) {
				obasedir_path = apr_pstrcat(r->pool, vhr->openbdir_path, ":", vhr->path_prefix, path, NULL);
			} else {
				obasedir_path = apr_pstrcat(r->pool, vhr->openbdir_path, ":", path, NULL);
			}
			//zend_alter_ini_entry("open_basedir", 13, obasedir_path, strlen(obasedir_path), 4, 16);
			zend_alter_ini_entry("open_basedir", 13, obasedir_path, strlen(obasedir_path), ZEND_INI_SYSTEM, ZEND_INI_STAGE_RUNTIME);
			VH_AP_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r, "vhx_php_config: PHP open_basedir set to %s (appending mode)", obasedir_path);
		} else {
			//zend_alter_ini_entry("open_basedir", 13, path, strlen(path), 4, 16);
			zend_alter_ini_entry("open_basedir", 13, path, strlen(path), ZEND_INI_SYSTEM, ZEND_INI_STAGE_RUNTIME);
			VH_AP_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r, "vhx_php_config: PHP open_basedir set to %s", path);
		}
	} else {
		VH_AP_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r, "vhx_php_config: PHP open_basedir inactive defaulting to php.ini values");
	}

	/*
	 * vhx_PHPdisplay_errors support
	 */
	if (vhr->display_errors) {
		VH_AP_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r, "vhx_php_config: PHP display_errors engaged");
		//zend_alter_ini_entry("display_errors", 10, "1", 1, 4, 16);
		zend_alter_ini_entry("display_errors", 10, "1", 1, ZEND_INI_SYSTEM, ZEND_INI_STAGE_RUNTIME);
	} else {
		VH_AP_LOG_RERROR(APLOG_MARK, APLOG_DEBUG, 0, r, "vhx_php_config: PHP display_errors inactive defaulting to php.ini values");
	}

}
Esempio n. 29
0
int
varnam_learn_from_file(varnam *handle,
                       const char *filepath,
                       vlearn_status *status,
                       void (*callback)(varnam *handle, const char *word, int status_code, void *object),
                       void *object)
{
    int rc;
    FILE *infile;
    char line_buffer[10000];
    strbuf *word;
    varray *word_parts;
    int confidence;
    int parts;

    infile = fopen(filepath, "r");
    if (!infile) {
        set_last_error (handle, "Couldn't open file '%s' for reading.\n", filepath);
        return VARNAM_ERROR;
    }

    if (status != NULL)
    {
        status->total_words = 0;
        status->failed = 0;
    }

    rc = vwt_optimize_for_huge_transaction(handle);
    if (rc) {
        fclose (infile);
        return rc;
    }

    /* Learning from file will be mostly new words. Optimizing for that */
    v_->_config_mostly_learning_new_words = 1;

    varnam_log (handle, "Starting to learn from %s", filepath);
    rc = vwt_start_changes (handle);
    if (rc) {
        vwt_turn_off_optimization_for_huge_transaction(handle);
        fclose (infile);
        return rc;
    }

    while (fgets(line_buffer, sizeof(line_buffer), infile))
    {
        reset_pool (handle);

        word = get_pooled_string (handle);
        strbuf_add (word, trimwhitespace (line_buffer));
        word_parts = strbuf_split (word, handle, ' ');
        parts = varray_length (word_parts);
        if (parts > 0 && parts <= 2)
        {
            confidence = 1;
            if (parts == 2) {
                word = varray_get (word_parts, 1);
                confidence = atoi (strbuf_to_s (word));
            }

            word = varray_get (word_parts, 0);
            rc = varnam_learn_internal (handle, strbuf_to_s (word), confidence);
            if (rc) {
                if (status != NULL) status->failed++;
            }
        }
        else {
            rc = VARNAM_ERROR;
            if (status != NULL) status->failed++;
        }

        if (status   != NULL) status->total_words++;
        if (callback != NULL) callback (handle, strbuf_to_s (word), rc, object);
    }

    varnam_log (handle, "Writing changes to disk");
    rc = vwt_end_changes (handle);
    if (rc) {
        varnam_log (handle, "Writing changes to disk failed");
    }

    varnam_log (handle, "Ensuring file integrity");
    rc = vwt_turn_off_optimization_for_huge_transaction(handle);
    if (rc) {
        varnam_log (handle, "Failed to check file integrity");
    }

    varnam_log (handle, "Compacting file");
    rc = vwt_compact_file (handle);
    if (rc) return rc;

    fclose (infile);
    return rc;
}
Esempio n. 30
0
static void
response_proces(struct https_client_ctx *ctx)
{
  mxml_node_t *tree;
  mxml_node_t *s_node;
  mxml_node_t *e_node;
  char *body;
  char *errmsg;
  char *sk;

  // NULL-terminate the buffer
  evbuffer_add(ctx->data, "", 1);

  body = (char *)evbuffer_pullup(ctx->data, -1);
  if (!body || (strlen(body) == 0))
    {
      DPRINTF(E_LOG, L_LASTFM, "Empty response\n");
      return;
    }

  DPRINTF(E_SPAM, L_LASTFM, "LastFM response:\n%s\n", body);

  tree = mxmlLoadString(NULL, body, MXML_OPAQUE_CALLBACK);
  if (!tree)
    return;

  // Look for errors
  e_node = mxmlFindElement(tree, tree, "error", NULL, NULL, MXML_DESCEND);
  if (e_node)
    {
      errmsg = trimwhitespace(mxmlGetOpaque(e_node));
      DPRINTF(E_LOG, L_LASTFM, "Request to LastFM failed: %s\n", errmsg);

      if (errmsg)
	free(errmsg);
      mxmlDelete(tree);
      return;
    }

  // Was it a scrobble request? Then do nothing. TODO: Check for error messages
  s_node = mxmlFindElement(tree, tree, "scrobbles", NULL, NULL, MXML_DESCEND);
  if (s_node)
    {
      DPRINTF(E_DBG, L_LASTFM, "Scrobble callback\n");
      mxmlDelete(tree);
      return;
    }

  // Otherwise an auth request, so get the session key
  s_node = mxmlFindElement(tree, tree, "key", NULL, NULL, MXML_DESCEND);
  if (!s_node)
    {
      DPRINTF(E_LOG, L_LASTFM, "Session key not found\n");
      mxmlDelete(tree);
      return;
    }

  sk = trimwhitespace(mxmlGetOpaque(s_node));
  if (sk)
    {
      DPRINTF(E_LOG, L_LASTFM, "Got session key from LastFM: %s\n", sk);
      db_admin_add("lastfm_sk", sk);

      if (lastfm_session_key)
	free(lastfm_session_key);

      lastfm_session_key = sk;
    }

  mxmlDelete(tree);
}