示例#1
0
/**
 * Run Worker
 *
 * @param nr id of worker which will be launched
 * @return 0 when success, otherwise error number
 */
int WorkerRun( Worker *wrk )
{
	if( wrk == NULL )
	{
		FERROR("[WorkerRun] Cannot run worker, worker is NULL\n");
		return 1;
	}
	
	clock_t start, end;

	start = clock();
	
	size_t stacksize = 16777216; //16 * 1024 * 1024;
	pthread_attr_t attr;
	pthread_attr_init( &attr );
	pthread_attr_setstacksize( &attr, stacksize );

	wrk->w_Thread = ThreadNew( WorkerThread, wrk, TRUE, &attr );
	if( wrk->w_Thread == NULL )
	{
		FERROR("[WorkerRun] Cannot create thread!\n");
		WorkerDelete( wrk );
		return -1;
	}
	
	end = clock();
    wrk->w_WorkMicros = end - start;
    wrk->w_WorkSeconds = wrk->w_WorkMicros / 1000000;
	
	return 0;
}
示例#2
0
char* StringDuplicateEOL( const char* str )
{
	int len = 0;
	char *newStr;
	char *p = (char *)str;
	if( str == NULL )
	{
		FERROR("Cannot duplicate string in size 0\n");
		return NULL;
	}
	
	while( *p != 0 )
	{
		if( *p == '\n' || *p == '\r' )
		{
			break;
		}
		//printf("%c\n", *p );
		
		len++;
		p++;
	}
	
	newStr = FMallocAlign( len + 1 );
	if( newStr == NULL )
	{
		FERROR("Cannot allocate memory in StringDuplicateN\n");
		return NULL;
	}
	memcpy( newStr, str, len );
	newStr[ len ] = 0;
	
	return newStr;
}
示例#3
0
char* StringDuplicateN( char* str, int len )
{
	if( !str )
	{
		DEBUG("Cannot duplicate string in size 0\n");
		return NULL;
	}
	
	char* copy;
	if( len <= 0 )
	{
		FERROR("Cannot duplicate string in size 0\n");
		return NULL;
	}
	//copy = FMallocAlign( len + 1 );
	copy = FCallocAlign( len + 1, 1 );
	if( copy == NULL )
	{
		FERROR("Cannot allocate memory in StringDuplicateN\n");
		return NULL;
	}
	memcpy( copy, str, len );
	copy[ len ] = 0;
	return copy;
}
示例#4
0
FILE * CommandRun( char *command, char *type, int *pid )
{
	int child_pid;
	int fd[2];
	if (pipe(fd) != 0)
	{
		FERROR("pipe call failed");
		exit(5);
	}

	if( ( child_pid = fork() ) == -1 )
	{
		FERROR( "Fork error" );
		return NULL;
	}

	// child process 
	if( child_pid == 0 )
	{
		if( type[0] == 'r' )
		{
			close( fd[ READ ]  );    //Close the READ end of the pipe since the child's fd is write-only
			dup2( fd[ WRITE ], 1 ); //Redirect stdout to pipe
		}
		else
		{
			close( fd[ WRITE ] );    //Close the WRITE end of the pipe since the child's fd is read-only
			dup2( fd [ READ ], 0 );   //Redirect stdin to pipe
		}
		
		execl("/bin/sh", "/bin/sh", "-c", command, NULL);
		exit(0);
	}
	else
	{
		if( type[0] == 'r' )
		{
			close( fd[ WRITE ] ); //Close the WRITE end of the pipe since parent's fd is read-only
		}
		else
		{
			close( fd[ READ ] ); //Close the READ end of the pipe since parent's fd is write-only
		}
	}

	*pid = child_pid;

	if( type[0] == 'r' )
	{
		return  fdopen( fd[ READ ], "r" );
	}

	return fdopen( fd[ WRITE ], "w" );
}
示例#5
0
文件: dictionary.c 项目: hww3/pexts
/*
 * Duplicate names are OK. It's just for reference.
 */
DICT*
dict_create(char *fn, char *name)
{
    DICT      *tmp;

    INFUN();
    
    if (!dictionaries) {
        dictionaries = (DICT**)calloc(sizeof(DICT*), INIT_DICTIONARIES);
        if (!dictionaries) {
            OUTFUN();
            FERROR(fn, "Failed to allocate memory for dictionaries (%d bytes)",
                   INIT_DICTIONARIES * sizeof(DICT*));
        }
        
        dictmax = INIT_DICTIONARIES;
    } else if(dictcount >= dictmax)  {
        dictionaries = (DICT**)realloc(dictionaries, (dictcount << 1) * sizeof(DICT*));
        if (!dictionaries) {
            OUTFUN();
            FERROR(fn, "Failed to enlarge memory for dictionaries (by %d bytes)",
                   INIT_DICTIONARIES * sizeof(DICT*));
        }
        
        dictmax = dictcount << 1;
    }
    
    tmp = dictionaries[dictcount] = (DICT*)calloc(sizeof(DICT), 1);
    if (!dictionaries[dictcount]) {
        OUTFUN();
        FERROR(fn, "Failed to allocate memory for dictionary (%d bytes)",
               sizeof(DICT));
    }

    dictcount++;
    tmp->dict = allocate_mapping(INIT_DICT_SIZE);
    tmp->used = 0;
    tmp->insert = dict_insert;
    tmp->lookup = dict_lookup;
    tmp->foreach = dict_foreach;
    
    if (name)
        tmp->name = strdup(name);
    else
        tmp->name = NULL;

    OUTFUN();
    
    return tmp;
}
示例#6
0
 Node *Graph::get_node(int i){
     if(i > capacity){
         FERROR("%s: element is out of bounds", __FUNCTION__);
         throw GraphException("element is out of bounds\n");
     }
     return &nodes[i];
 }
示例#7
0
int main(int argc, char **argv){
    #ifdef HAS_PARMETIS
    int size, rank, rc;
    char lfname[100];
    char efname[100];
    testcount = 0;
    rc = MPI_Init(&argc, &argv);
    if(rc != MPI_SUCCESS){
        FERROR("MPI Initialization error\n");
        MPI_Abort(MPI_COMM_WORLD, rc);
    }
    rank = 0;
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    sprintf(lfname, "parmetislog.%04d", rank);
    //0: debug, 5: critical
    LOG_INIT(lfname, NULL, 0);

    parmetis_with_amd();
    parmetis_only();
    parmetis_with_metmmd();

    MPI_Finalize();
    LOG_CLOSE();
    #else // ifdef HAS_PARMETIS
    cout << "Enable HAS_PARMETIS flag and recompile to test parmetis functions" << endl;
    #endif // HAS_PARMETIS
    return 0;
} // main
示例#8
0
void HashedString ( char **str )
{
	unsigned char temp[SHA_DIGEST_LENGTH];
	memset( temp, 0x0, SHA_DIGEST_LENGTH );
	
	//char *buf = FMallocAlign( ( SHIFT_LEFT( SHA_DIGEST_LENGTH, 1) ) + 1 );
	char *buf = FCallocAlign( ( SHIFT_LEFT( SHA_DIGEST_LENGTH, 1) ) + 1, 1 );
	//char *buf = FCalloc( ( SHIFT_LEFT( SHA_DIGEST_LENGTH, 1) ) + 1, sizeof( char ) );

	if( buf != NULL )
	{
		SHA1( ( unsigned char *)*str, strlen( *str ), temp);

		int i = 0;
		for ( ; i < SHA_DIGEST_LENGTH; i++ )
		{
			sprintf( (char*)&(buf[ SHIFT_LEFT( i, 1) ]), "%02x", temp[i] );
		}

		if ( *str ) 
		{
			FFree ( *str );
		}
		DEBUG ( "[HashedString] Hashing\n" );
		*str = buf;
		DEBUG ( "[HashedString] Hashed\n" );
	}
	else
	{
		FERROR("Cannot allocate memory for hashed string\n");
	}
}
示例#9
0
/**
 * Worker thread
 *
 * @param w pointer to Worker FThread
 */
void WorkerThread( void *w )
{
	FThread *thread = (FThread *)w;
	Worker *wrk = (Worker *)thread->t_Data;
	wrk->w_State = W_STATE_RUNNING;

	// Run until quit
	while( TRUE )
	{
		if( wrk->w_Quit == TRUE )
		{
			break;
		}

		if( pthread_mutex_lock( &(wrk->w_Mut) ) == 0 )
		{
			wrk->w_State = W_STATE_WAITING;

			pthread_cond_wait( &(wrk->w_Cond), &(wrk->w_Mut) );

			wrk->w_State = W_STATE_COMMAND_CALLED;
			pthread_mutex_unlock( &(wrk->w_Mut) );
			
			if( wrk->w_Function != NULL && wrk->w_Data != NULL )
			{
				wrk->w_Function( wrk->w_Data );

				if( pthread_mutex_lock( &(wrk->w_Mut) ) == 0 )
				{
					wrk->w_Data = NULL;
					wrk->w_Function = NULL;
					
					pthread_mutex_unlock( &(wrk->w_Mut) );				
				}
			}
			else
			{
				//FERROR("Function is not set\n");
			}
		}
		else
		{
			FERROR("[WorkerThread] Cannot lock!\n");
		}

		if( wrk->w_Quit == TRUE ) 
		{
			break;
		}

		// Let others come to..
		usleep( 100 );
	}
	
	wrk->w_Function = NULL;
	wrk->w_Data = NULL;
	wrk->w_State = W_STATE_TO_REMOVE;
	thread->t_Launched = FALSE;
}
示例#10
0
// read palette files into buffer ---------------------------------------------
//
PRIVATE
void ReadPalettes()
{
	// exit if nothing to read
	if ( NumLoadedPalettes == 0 )
		PANIC( "no palette defined." );

	if ( ( PaletteMem = (char *) ALLOCMEM( PALETTE_SIZE * NumLoadedPalettes ) ) == NULL )
		OUTOFMEM( no_palette_mem );

	if ( display_info ) {
		MSGPUT( "Loading palettes" );
		if ( show_palettes_loaded ) {
			MSGOUT( ":\n" );
		} else {
			MSGPUT( "..." );
		}
	}

	// load all palettes
	size_t readofs = 0;
	for ( int pid = 0; pid < NumLoadedPalettes; pid++ ) {

		if ( display_info && !show_palettes_loaded )
			MSGPUT( "." );

		FILE *fp = SYS_fopen( palette_fnames[ pid ], "rb" );
		if ( fp == NULL )
			FERROR( palette_not_found, palette_fnames[ pid ] );

		if ( display_info && show_palettes_loaded ) {
			MSGOUT( "loading \"%s\" (palette)\n", palette_fnames[ pid ] );
		}

		size_t bytesread = SYS_fread( PaletteMem + readofs, 1, PALETTE_SIZE, fp );
		if ( bytesread != PALETTE_SIZE )
			FERROR( palette_readerror, palette_fnames[ pid ] );
		readofs += PALETTE_SIZE;

		SYS_fclose( fp );
	}

	if ( display_info ) {
		MSGOUT( "done.\n" );
	}
}
示例#11
0
文件: io_bmp.c 项目: robwink/davinci
int loadBMP1(FILE* fp, unsigned char* data, int w, int h, int band, unsigned char* red,
             unsigned char* blue, unsigned char* green)
{
	int i, j, c, bitnum, padw;
	unsigned char* pp;

	c    = 0;
	padw = ((w + 31) / 32) * 32;

	// printf("Width: %d, Height: %d, padded Width: %d\n", w, h, padw);
	for (i = h - 1; i >= 0; i--) {
		pp = data + (i * w * band);
		for (j = bitnum = 0; j < padw; j++, bitnum++) {
			if ((bitnum & 7) == 0) { /* read the next unsigned char */
				c      = getc(fp);
				bitnum = 0;
			}
			if (j < w) {
				/* this is where I can put in the rgb values easily */
				int s = (c & 0x80) ? 1 : 0;
				*pp   = red[s];
				pp++;
				if (band == 3) {
					*pp = green[s];
					pp++;
					*pp = blue[s];
					pp++;
					// pp-=3;
					// printf("blue: %02x ", (*pp));
					// pp++;
					// printf("green: %02x ", (*pp));
					// pp++;
				}
				// printf("red: %02x ", (*pp));
				// pp++;

				c <<= 1;
			}
		}
		if (FERROR(fp)) break;
	}
	return (FERROR(fp));
}
示例#12
0
    /**
     * Subdivides the edge (u,v) by placing a new vertex, numbered w
     * in the graph, deleting (u,v) and adding (u,w) and (w,v).
     * WARNING: If w is a current vertex, this function will remove
     * all its current edges, and may have unpredictable behavior.
     *
     */
    int Graph::edge_subdivision(int u, int v, int w){
        if((nodes[u].label == -1) || (nodes[v].label == -1) ){
            fatal_error(
                "%s: Cannot remove edge (%d, %d) as one of its vertices is undefined!\n",
                __FUNCTION__, u, v);
        }
        list<int>::iterator it;

        // check that v is a neighbour of u
        bool foundv = false;
        for(it = nodes[u].nbrs.begin(); it != nodes[u].nbrs.end(); ++it){
            if(*it == v){
                foundv = true;
            }
        }
        if(foundv == false){
            return false;
        }

        // if w provided, check that it is in bounds
        if(w >= capacity){
            nodes.resize(2 * capacity);
            capacity *= 2;
        }

        nodes[w].nbrs.clear();
        if(!nodes[w].nbrs.empty()){
            FERROR("%s: node is not empty", __FUNCTION__);
            throw GraphException("node is not empty\n");
        }
        else {
            nodes[w].label = w;
            degree[w] = 2;
            nodes[w].nbrs.push_back(u);
            nodes[w].nbrs.push_back(v);

            // remove u from v's nbrs list and vice versa
            for(it = nodes[u].nbrs.begin(); it != nodes[u].nbrs.end(); it++){
                if(*it == v){
                    *it = w;
                    break;
                }
            }
            for(it = nodes[v].nbrs.begin(); it != nodes[v].nbrs.end(); it++){
                if(*it == u){
                    *it = w;
                    break;
                }
            }
        }
        num_edges++;
        next_label++;
        num_nodes++;
        return w;
    } // Graph::edge_subdivision
示例#13
0
FLONG Delete( struct File *s, const char *path )
{
	DEBUG("Delete!\n");
	FLONG deleted = 0;
	
	int error = 0;
	SpecialData *srd = (SpecialData *) s->f_SpecialData;
	INRAMFile *dir =INRAMFileGetLastPath( srd->root,path, &error );
	if( dir != NULL )
	{
		INRAMFile *pdir = dir->nf_Parent;
		
		DEBUG("Delete parent ptr %p %s\n", pdir, pdir->nf_Name );
		if( pdir != NULL )
		{
			dir = INRAMFileRemoveChild( pdir, dir );
			deleted += INRAMFileDeleteAll( dir );
			if( dir->nf_Type != INRAM_ROOT )
			{
				deleted += INRAMFileDelete( dir );
			}
			DEBUG("Delete entries deleted\n");
		}
		else
		{
			FERROR("Parent entry is null\n");
			return -1;
		}
	}
	else
	{
		FERROR("Path not found %s\n", path );
		return -2;
	}
	DEBUG("Delete END\n");
	
	return deleted;
}
示例#14
0
char* StringShellEscapeSize( const char* str, int *len )
{
	unsigned int strLen = str ? strlen( str ) : 0;
	unsigned int estrLen = 0;

	// We must escape \'s and "'s from the args!
	for( unsigned int i = 0; i < strLen; i++ )
	{
		if(str[i] == '\\')
		{
			estrLen += 2;
		}
		else if(str[i] == '"')
		{
			estrLen += 2;
		}
		else
		{
			estrLen++;
		}
	}
	//char* estr = FMallocAlign( estrLen + 1 );
	char* estr = FCallocAlign( estrLen + 1, 1 );
	//char* estr = calloc( estrLen + 1, sizeof(char) );
	if( estr == NULL )
	{
		FERROR("Cannot allocate memory in StringShellEscape\n");
		return NULL;
	}
	unsigned int j = 0;
	for( unsigned int i = 0; i < strLen; i++ )
	{
		if(str[i] == '\\')
		{
			estr[j++] = '\\';
			estr[j++] = str[i];
		}
		else if(str[i] == '"')
		{
			estr[j++] = '\\';
			estr[j++] = str[i];
		}
		else
			estr[j++] = str[i];
	}
	estr[ estrLen ] = 0;
	*len = estrLen;

	return estr;
}
示例#15
0
/**
 * Create new LocFile structure and read file data from BufString
 *
 * @param path pointer to char table with path
 * @param bs pointer to BufString with file data
 * @return pointer to new LocFile when success, otherwise NULL
 */
LocFile* LocFileNewFromBuf( char* path, BufString *bs )
{
	if( path == NULL )
	{
		FERROR("File path is null\n");
		return NULL;
	}
	if( bs == NULL )
	{
		FERROR("BufString is NULL\n" );
		return NULL;
	}
	
	LocFile* fo = (LocFile*) FCalloc( 1, sizeof(LocFile) );
	if( fo != NULL )
	{
		fo->lf_PathLength = strlen( path );
		fo->lf_Path = StringDuplicateN( path, fo->lf_PathLength );
		//fo->lf_Filename = StringDuplicateN( path, fo->lf_PathLength );//StringDuplicate( GetFileNamePtr( path, len ) );
		MURMURHASH3( fo->lf_Path, fo->lf_PathLength, fo->hash );
		
		DEBUG("PATH: %s \n", fo->lf_Path );

		fo->lf_FileSize = bs->bs_Size;
		
		if( ( fo->lf_Buffer = FMalloc( fo->lf_FileSize ) ) != NULL )
		{
			memcpy( fo->lf_Buffer, bs->bs_Buffer, fo->lf_FileSize );
		}
	}
	else
	{
		FERROR("Cannot allocate memory for LocFile\n");
	}
	
	return fo;
}
示例#16
0
/**
 * Reload content from file
 *
 * @param file pointer to LocFile structure 
 * @param path pointer to path from which data will be reloaded
 * @return 0 when success, otherwise error number
 */
int LocFileReload( LocFile *file, char *path )
{
	DEBUG("File %s will be reloaded\n", path );
	
	if( file->lf_Buffer )
	{
		FFree( file->lf_Buffer );
		file->lf_Buffer = NULL;
	}
	
	FILE* fp = fopen( path, "rb" );
	if( fp == NULL )
	{
		FERROR("Cannot open file %s (file does not exist?)..\n", path );
		return -1;
	}
	
	struct stat st;
	if( stat( path, &st ) < 0 )
	{
		FERROR("Cannot run stat on file: %s!\n", path);
		return -2;
	}
	memcpy(  &(file->lf_Info),  &st, sizeof(stat) );
	
	fseek( fp, 0, SEEK_END );
	long fsize = ftell( fp );
	fseek( fp, 0, SEEK_SET );  //same as rewind(f);
	file->lf_FileSize = fsize;

	LocFileRead( file, fp, 0, file->lf_FileSize );
	
	fclose( fp );
	
	return 0;
}
示例#17
0
void AppSessionThread( void *args )
{
	struct FThread *ft = (FThread *)args;
	AppSession *as =  (AppSession  *)ft->t_Data;
	
	struct timeval timeout;
	fd_set fds;
	
	while( ft->t_Quit != TRUE )
	{
		FD_ZERO( &fds );
		FD_SET( as->as_WritePipe, &fds );
						
		timeout.tv_sec = 5000;
		timeout.tv_usec = 0;
						
		int err = select( as->as_WritePipe+1, &fds, NULL, NULL, &timeout );
		
		if( err  < 0 )
		{
			FERROR("Problem\n");
		}
		else if(  err  ==  0  )
		{
			DEBUG("Timeout\n");
		}
		else
		{
#define BUFFER_SIZE 2048
			char buffer[ BUFFER_SIZE ];
			BufString *bs  =  BufStringNew();

			int  size = -1;
			
			while(  size != 0 )//!feof( (FILE *) as->as_WritePipe ) )
			{
				// Make a new buffer and read
				size = read( as->as_WritePipe, buffer, BUFFER_SIZE );
				//int  size = fread( buffer, sizeof(char), BUFFER_SIZE, (FILE *)as->as_WritePipe );
				BufStringAddSize( bs, buffer, size );
			}
			
			BufStringDelete( bs );
		}
	}
	
	ft->t_Launched = FALSE;
}
示例#18
0
文件: fcdb.c 项目: eloekset/friendup
/**
 * Initialize authmodule
 *
 * @param l pointer to AuthMod
 * @param sb pointer to SystemBase
 * @return 0 when success, otherwise error number
 */
int libInit( AuthMod *l, void *sb )
{
	DEBUG("[FCDB] libinit\n");

	if( ( l->SpecialData = FCalloc( 1, sizeof( struct SpecialData ) ) ) == NULL )
	{
		FERROR("Cannot allocate memory for authmodule\n");
		return 1;
	}

	l->am_Name = LIB_NAME;
	l->am_Version = LIB_VERSION;
	l->sb = sb;

	return 0;
}
示例#19
0
/**
 * Prints a fatal error message to stderr and exits.
 */
void fatal_error(const char *format, ...){
    fprintf(stderr,"Fatal Error!\n");
    char buffer[1024];
    va_list args;

    va_start(args, format);
    vfprintf(stderr, format, args);
    sprintf(buffer, format, args);
    va_end(args);

    fprintf(stderr,"Exiting\n");

    FERROR("%s", buffer);
    const std::string desc(buffer);
    throw Graph::GraphException(desc);
}
示例#20
0
/*VARARGS1*/
int
printf(const char *format, ...)
{
	ssize_t count;
	rmutex_t *lk;
	va_list ap;

	va_start(ap, format);

	/* Use F*LOCKFILE() macros because printf() is not async-safe. */
	FLOCKFILE(lk, stdout);

	_SET_ORIENTATION_BYTE(stdout);

	if (!(stdout->_flag & _IOWRT)) {
		/* if no write flag */
		if (stdout->_flag & _IORW) {
			/* if ok, cause read-write */
			stdout->_flag |= _IOWRT;
		} else {
			/* else error */
			FUNLOCKFILE(lk);
			errno = EBADF;
			return (EOF);
		}
	}
	count = _ndoprnt(format, ap, stdout, 0);
	va_end(ap);

	/* check for errors or EOF */
	if (FERROR(stdout) || count ==  EOF) {
		FUNLOCKFILE(lk);
		return (EOF);
	}

	FUNLOCKFILE(lk);

	/* check for overflow */
	if ((size_t)count > MAXINT) {
		errno = EOVERFLOW;
		return (EOF);
	} else {
		return ((int)count);
	}
}
示例#21
0
char* StringAppend( const char* str1, const char* str2 )
{
	unsigned int len1 = strlen( str1 );
	unsigned int len2 = strlen( str2 );
	char* combined = FMallocAlign( len1 + len2 + 1 );

	// Out of memory?
	if( !combined )
	{
		FERROR("Cannot allocate memory in StringAppend\n");
		return NULL;
	}

	strcpy( combined, str1 );
	strcpy( combined + len1, str2 );
	combined[ len1 + len2 ] = 0;
	return combined;
}
示例#22
0
/**
 * Main Websockets thread
 *
 * @param data pointer to Websockets thread
 * @return 0 when success, otherwise error number
 */
int WebsocketThread( FThread *data )
{
	int cnt = 0;
	WebSocket *ws = (WebSocket *)data->t_Data;
	if( ws->ws_Context == NULL )
	{
		FERROR("WsContext is empty\n");
		return 0;
	}
	
	DEBUG1("[WS] Websocket thread started\n");
	
	//signal( SIGPIPE, SIG_IGN );
	//signal( SIGPIPE, hand );

	//lws_set_log_level( LLL_ERR | LLL_WARN | LLL_NOTICE | LLL_INFO | LLL_DEBUG , NULL );
	
	Log( FLOG_INFO, "[WS] Service will be started now\n" );

	while( TRUE )
	{
		int n = lws_service( ws->ws_Context, 500 );
		
		if( ws->ws_Quit == TRUE && WSThreadNum <= 0 )
		{
			break;
		}
		else if( ws->ws_Quit == TRUE )
		{
			cnt++;
			
			if( cnt > 500 )
			{
				Log( FLOG_INFO, "[WS] Service stopping threads: %d\n", WSThreadNum );
				cnt = 0;
			}
		}
	}
	Log( FLOG_INFO, "[WS] Service stopped\n" );

done:
	data->t_Launched = FALSE;
	return 0;
}
示例#23
0
char *UrlDecodeToMem( const char* src )
{
	if( src == NULL )
	{
		return NULL;
	}
	int size = strlen( src );
	//char *dst = FMallocAlign( size + 1);
	char *dst = FCallocAlign( size + 1, 1 );
	if( dst == NULL )
	{
		FERROR("Cannot alloc memory for decoded url\n");
		return NULL;
	}
	char* org_dst = dst;
	char ch, a, b;
	do 
	{
		ch = *src++;
		// Interpreting + as spaces!
		if( ch == '+' )
		{
			ch = ' ';
		}
		else if( ch == '%' && isxdigit( a = src[0] ) && isxdigit( b = src[1] ) ) 
		{
			if( a < 'A' ) a -= '0';
			else if( a < 'a' ) a -= 'A' - 10;
			else a -= 'a' - 10;
			if ( b < 'A' ) b -= '0';
			else if( b < 'a' ) b -= 'A' - 10;
			else b -= 'a' - 10;
			ch = 16 * a + b;
			src += 2;
		}
		*dst++ = ch;
	} 
	while( ch );
	
	//*dst = 0;
	
	return org_dst;
}
示例#24
0
char* StringDuplicate( const char* str )
{
	int len;
	char *newStr;
	if( !str )
	{
		DEBUG("Cannot duplicate string in size 0\n");
		return NULL;
	}
	len = strlen( str );
	newStr = FMallocAlign( len + 1 );
	//newStr = FCallocAlign( len + 1, 1 );
	if( !newStr )
	{
		FERROR("Cannot allocate memory in StringDuplicateN\n");
		return NULL;
	}
	memcpy( newStr, str, len+1 );
	return newStr;
}
示例#25
0
int Rename( struct File *s, const char *path, const char *nname )
{
	DEBUG("Rename!\n");
	int res = 0;
	
	int error = 0;
	SpecialData *srd = (SpecialData *) s->f_SpecialData;
	INRAMFile *dir =INRAMFileGetLastPath( srd->root, path, &error );
	if( dir != NULL )
	{
		free( dir->nf_Name );
		free( dir->nf_Path );
		dir->nf_Name = StringDup( nname );
		
		int len = strlen( path );
		char *temp = calloc( len+512, sizeof(char) );
		if( temp != NULL )
		{
			int i = len;
			strcpy( temp, path );
			
			for( ; i >= 0 ; i-- )
			{
				if( temp[ i ] == '/' )
				{
					temp[ i+1 ] =  0;
				}
			}
			
			strcat( temp, nname );
			
			dir->nf_Path = temp;
		}
		else
		{
			FERROR("Cannot allocate memory\n");
		}
	}
	
	return res;
}
示例#26
0
文件: io_bmp.c 项目: robwink/davinci
int loadBMP4(FILE* fp, unsigned char* data, int w, int h, int band, int comp, unsigned char* red,
             unsigned char* blue, unsigned char* green)
{
	int i, j, c, c1, x, y, nybnum, rv, padw;
	unsigned char* pp;

	rv = 0;
	c = c1 = 0;

	/* read uncompressed data */
	if (comp == BI_RGB) {
		/* 'w' padded to a multiple of 8pix (32 bits) */
		padw = ((w + 7) / 8) * 8;

		for (i = h - 1; i >= 0; i--) {
			pp = data + (i * w * band);

			for (j = nybnum = 0; j < padw; j++, nybnum++) {
				/* read next unsigned char */
				if ((nybnum & 1) == 0) {
					c      = getc(fp);
					nybnum = 0;
				}

				if (j < w) {
					int s = (c & 0xf0) >> 4;
					*pp   = red[s];
					pp++;
					if (band == 3) {

						*pp = green[s];
						pp++;
						*pp = blue[s];
						pp++;
					}
					c <<= 4;
				}
			}
			if (FERROR(fp)) break;
		}
示例#27
0
/**
 * Delete LocFile structure
 *
 * @param file pointer to LocFile which will be deleted
 */
void LocFileDelete( LocFile* file )
{
	if( file == NULL )
	{
		FERROR("Cannot free file which doesnt exist\n");
	}
	
	if( file->lf_Filename != NULL )
	{
		FFree( file->lf_Filename );
	}
	/*
	if( file->lf_Fp )
	{
		fclose( file->lf_Fp );
		file->lf_Fp = NULL;
	}
	*/
	if( file->lf_Path )
	{
		FFree( file->lf_Path );
		file->lf_Path = NULL;
	}
	if( file->lf_Buffer )
	{
#if LOCFILE_USE_MMAP == 0
		FFree( file->lf_Buffer );
#else
		munmap(file->lf_Buffer, file->lf_FileSize);
#endif
		file->lf_Buffer = NULL;
	}
	if( file->lf_Mime != NULL )
	{
		FFree( file->lf_Mime );
		file->lf_Mime = NULL;
	}

	FFree( file );	
}
示例#28
0
AppSession *AppSessionNew( void *sb, const char *authid, FUQUAD appid, UserSession *owner )
{
	AppSession *las = NULL;
	DEBUG("[AppSession] Create app session\n");
	
	if( ( las = FCalloc( 1, sizeof( AppSession ) ) ) != NULL )
	{
		strcpy( las->as_AuthID, authid );
		las->as_AppID = appid;
		
		DEBUG("[AppSession] AppSessionCreated, authid %s\n", authid );
		
		SASUList *ali =  FCalloc( 1, sizeof( SASUList ) );
		if( ali != NULL )
		{
			ali->ID = las->as_NumberGenerator++;
			ali->status = SASID_US_STATUS_NEW;
			ali->usersession = owner;
			strcpy( ali->authid, authid );
			DEBUG("[AppSession] ASN set %s pointer %p\n", ali->authid, ali );
			las->as_UserSessionList = ali;
			
			las->as_SASID = (FUQUAD)ali;//( rand() % ULLONG_MAX );
			las->as_Timer = time( NULL );
			
			las->as_UserNumber++;
			las->as_VariablesNumGenerator = 100;
			las->as_SB = sb;
			
			pthread_mutex_init( &las->as_SessionsMut, NULL );
			pthread_mutex_init( &las->as_VariablesMut, NULL );
		}
	}
	else
	{
		FERROR("Cannot allocate memory for AppSession\n");
	}
	
	return las;
}
示例#29
0
int AppSessionSendOwnerMessage( AppSession *as, UserSession *sender, char *msg, int length )
{
	int msgsndsize = 0;
	if( as == NULL )
	{
		DEBUG("[AppSession] AppSession parameter is empty\n");
		return -1;
	}
	
	time_t ntime = time( NULL );
	DEBUG("[AppSession] OLD TIME %lld NEW TIME %lld\n", (long long)as->as_Timer, (long long)ntime );
	if( ( ntime - as->as_Timer ) > TIMEOUT_APP_SESSION )
	{
		as->as_Obsolete = TRUE;
	}
	as->as_Timer = ntime;

	DEBUG("[AppSession] Send message %s\n", msg );
	
	char *newmsg = NULL;
	
	if( ( newmsg = FCalloc( length+256, sizeof(char) ) ) != NULL )
	{
		User *usend = sender->us_User;
		DEBUG("[AppSession] AS POINTER %p SENDER %p\n", as, usend );
		int newmsgsize = sprintf( newmsg, WS_MESSAGE_TEMPLATE_USER, as->as_AuthID, as->as_SASID, usend->u_Name, msg );
		
		msgsndsize += WebSocketSendMessageInt( as->as_UserSessionList->usersession, newmsg, newmsgsize );
		DEBUG("[AppSession] FROM %s  TO %s  MESSAGE SIZE %d\n", usend->u_Name, as->as_UserSessionList->usersession->us_User->u_Name, msgsndsize );

		FFree( newmsg );
	}
	else
	{
		FERROR("Cannot allocate memory for message\n");
	}
	
	return msgsndsize;
}
示例#30
0
/**
 * Create new worker
 *
 * @param nr id of new worker
 * @return pointer to new Worker structure when success, otherwise NULL
 */
Worker *WorkerNew( int nr )
{
	Worker *wrk = ( Worker *)FCalloc( 1, sizeof( Worker ) );
	
	if( wrk != NULL )
	{
		DEBUG("[WorkerThread] Worker CREATED %d\n", nr );
		
		wrk->w_State = W_STATE_CREATED;
		wrk->w_Nr = nr;
		
		pthread_mutex_init( &(wrk->w_Mut), NULL );
		pthread_cond_init( &(wrk->w_Cond), NULL );
	}
	else
	{
		FERROR("Cannot allocate memory for worker\n");
		return NULL;
	}

	return wrk;
}