PmReturn_t global_init(void) { PmReturn_t retval; uint8_t *codestr = (uint8_t *)"code"; uint8_t *pchunk; pPmObj_t pobj; #ifdef HAVE_CLASSES uint8_t const *initstr = (uint8_t const *)"__init__"; #endif /* HAVE_CLASSES */ #ifdef HAVE_GENERATORS uint8_t const *genstr = (uint8_t const *)"Generator"; uint8_t const *nextstr = (uint8_t const *)"next"; #endif /* HAVE_GENERATORS */ #ifdef HAVE_ASSERT uint8_t const *exnstr = (uint8_t const *)"Exception"; #endif /* HAVE_ASSERT */ #ifdef HAVE_BYTEARRAY uint8_t const *pbastr = (uint8_t const *)"bytearray"; #endif /* HAVE_BYTEARRAY */ /* Clear the global struct */ sli_memset((uint8_t *)&gVmGlobal, '\0', sizeof(PmVmGlobal_t)); /* Set the PyMite release num (for debug and post mortem) */ gVmGlobal.errVmRelease = PM_RELEASE; /* Init zero */ retval = heap_getChunk(sizeof(PmInt_t), &pchunk); PM_RETURN_IF_ERROR(retval); pobj = (pPmObj_t)pchunk; OBJ_SET_TYPE(pobj, OBJ_TYPE_INT); ((pPmInt_t)pobj)->val = (int32_t)0; gVmGlobal.pzero = (pPmInt_t)pobj; /* Init one */ retval = heap_getChunk(sizeof(PmInt_t), &pchunk); PM_RETURN_IF_ERROR(retval); pobj = (pPmObj_t)pchunk; OBJ_SET_TYPE(pobj, OBJ_TYPE_INT); ((pPmInt_t)pobj)->val = (int32_t)1; gVmGlobal.pone = (pPmInt_t)pobj; /* Init negone */ retval = heap_getChunk(sizeof(PmInt_t), &pchunk); PM_RETURN_IF_ERROR(retval); pobj = (pPmObj_t)pchunk; OBJ_SET_TYPE(pobj, OBJ_TYPE_INT); ((pPmInt_t)pobj)->val = (int32_t)-1; gVmGlobal.pnegone = (pPmInt_t)pobj; /* Init False */ retval = heap_getChunk(sizeof(PmBoolean_t), &pchunk); PM_RETURN_IF_ERROR(retval); pobj = (pPmObj_t)pchunk; OBJ_SET_TYPE(pobj, OBJ_TYPE_BOOL); ((pPmBoolean_t) pobj)->val = (int32_t)C_FALSE; gVmGlobal.pfalse = (pPmInt_t)pobj; /* Init True */ retval = heap_getChunk(sizeof(PmBoolean_t), &pchunk); PM_RETURN_IF_ERROR(retval); pobj = (pPmObj_t)pchunk; OBJ_SET_TYPE(pobj, OBJ_TYPE_BOOL); ((pPmBoolean_t) pobj)->val = (int32_t)C_TRUE; gVmGlobal.ptrue = (pPmInt_t)pobj; /* Init None */ retval = heap_getChunk(sizeof(PmObj_t), &pchunk); PM_RETURN_IF_ERROR(retval); pobj = (pPmObj_t)pchunk; OBJ_SET_TYPE(pobj, OBJ_TYPE_NON); gVmGlobal.pnone = pobj; /* Init "code" string obj */ retval = string_new((uint8_t const **)&codestr, &pobj); PM_RETURN_IF_ERROR(retval); gVmGlobal.pcodeStr = (pPmString_t)pobj; #ifdef HAVE_CLASSES /* Init "__init__" string obj */ retval = string_new((uint8_t const **)&initstr, &pobj); PM_RETURN_IF_ERROR(retval); gVmGlobal.pinitStr = (pPmString_t)pobj; #endif /* HAVE_CLASSES */ #ifdef HAVE_GENERATORS /* Init "Generator" string obj */ retval = string_new((uint8_t const **)&genstr, &pobj); PM_RETURN_IF_ERROR(retval); gVmGlobal.pgenStr = (pPmString_t)pobj; /* Init "next" string obj */ retval = string_new((uint8_t const **)&nextstr, &pobj); PM_RETURN_IF_ERROR(retval); gVmGlobal.pnextStr = (pPmString_t)pobj; #endif /* HAVE_GENERATORS */ #ifdef HAVE_ASSERT /* Init "Exception" string obj */ retval = string_new((uint8_t const **)&exnstr, &pobj); PM_RETURN_IF_ERROR(retval); gVmGlobal.pexnStr = (pPmString_t)pobj; #endif /* HAVE_ASSERT */ #ifdef HAVE_BYTEARRAY /* Init "bytearray" string obj */ retval = string_new((uint8_t const **)&pbastr, &pobj); PM_RETURN_IF_ERROR(retval); gVmGlobal.pbaStr = (pPmString_t)pobj; #endif /* HAVE_BYTEARRAY */ /* Init empty builtins */ gVmGlobal.builtins = C_NULL; /* Init native frame */ OBJ_SET_SIZE(&gVmGlobal.nativeframe, sizeof(PmNativeFrame_t)); OBJ_SET_TYPE(&gVmGlobal.nativeframe, OBJ_TYPE_NFM); gVmGlobal.nativeframe.nf_func = C_NULL; gVmGlobal.nativeframe.nf_stack = C_NULL; gVmGlobal.nativeframe.nf_active = C_FALSE; gVmGlobal.nativeframe.nf_numlocals = 0; /* Create empty threadList */ retval = list_new(&pobj); gVmGlobal.threadList = (pPmList_t)pobj; /* Init the PmImgPaths with std image info */ gVmGlobal.imgPaths.memspace[0] = MEMSPACE_PROG; gVmGlobal.imgPaths.pimg[0] = (uint8_t *)&stdlib_img; gVmGlobal.imgPaths.pathcount = 1; #ifdef HAVE_PRINT gVmGlobal.needSoftSpace = C_FALSE; gVmGlobal.somethingPrinted = C_FALSE; #endif /* HAVE_PRINT */ return retval; }
int main( int argc, char *argv[] ) { time_t curtime; struct tm *loctime; int value, code; char * d, *d1; char * sourcefile = 0; char basepathname[__MAX_PATH] = ""; char dcbname[__MAX_PATH] = ""; char stubname[__MAX_PATH] = ""; char importname[__MAX_PATH] = ""; char compilerimport[__MAX_PATH] = ""; int i, j; char *ptr; /* get my executable name */ ptr = argv[0] + strlen( argv[0] ); while ( ptr > argv[0] && ptr[-1] != '\\' && ptr[-1] != '/' ) ptr-- ; appexename = strdup( ptr ); /* get executable full pathname */ appexefullpath = getfullpath( argv[0] ); if ( ( !strchr( argv[0], '\\' ) && !strchr( argv[0], '/' ) ) && !file_exists( appexefullpath ) ) { char *p = whereis( appexename ); if ( p ) { char * tmp = calloc( 1, strlen( p ) + strlen( appexename ) + 2 ); free( appexefullpath ); sprintf( tmp, "%s/%s", p, appexename ); appexefullpath = getfullpath( tmp ); free( tmp ); } } /* get pathname of executable */ ptr = strstr( appexefullpath, appexename ); appexepath = calloc( 1, ptr - appexefullpath + 1 ); strncpy( appexepath, appexefullpath, ptr - appexefullpath ); printf( BGDC_VERSION "\n" "Bennu Game Development Compiler\n" "\n" "Copyright (c) 2006-2016 SplinterGU (Fenix/BennuGD)\n" "Copyright (c) 2002-2006 Fenix Team (Fenix)\n" "Copyright (c) 1999-2002 José Luis Cebrián Pagüe (Fenix)\n" "\n" ); /* Default lang to EN */ strcpy( langinfo, "EN" ); /* LANG detect */ #ifdef WIN32 GetLocaleInfo( LOCALE_USER_DEFAULT, LOCALE_SABBREVCTRYNAME, langinfo, 64 ); strlwr( langinfo ); #else if ( getenv( "LANG" ) != NULL && strlen( getenv( "LANG" ) ) >= 2 ) strcpy( langinfo, getenv( "LANG" ) ); #endif langinfo[2] = 0; srand( time( NULL ) ); /* build error messages list */ err_buildErrorTable(); init_c_type(); identifier_init(); constants_init(); string_init(); compile_init(); mainproc = procdef_new( procdef_getid(), identifier_search_or_add( "MAIN" ) ) ; /* Init vars */ char tmp_version[ 32 ]; sprintf( tmp_version, "\"%s\"", VERSION ); add_simple_define( "COMPILER_VERSION", tmp_version ); add_simple_define( "__VERSION__", tmp_version ); curtime = time( NULL ); /* Get the current time. */ loctime = localtime( &curtime ); /* Convert it to local time representation. */ strftime( timebuff, sizeof( timebuff ), "%Y/%m/%d", loctime ); value = string_new( timebuff ); code = identifier_search_or_add( "__DATE__" ) ; constants_add( code, typedef_new( TYPE_STRING ), value ) ; strftime( timebuff, sizeof( timebuff ), "%H:%M:%S", loctime ); value = string_new( timebuff ); code = identifier_search_or_add( "__TIME__" ) ; constants_add( code, typedef_new( TYPE_STRING ), value ) ; /* value = string_new( VERSION ); code = identifier_search_or_add( "__VERSION__" ) ; constants_add( code, typedef_new( TYPE_STRING ), value ) ; code = identifier_search_or_add( "COMPILER_VERSION" ) ; constants_add( code, typedef_new( TYPE_STRING ), value ) ; */ strcpy( _tmp, VERSION ); d = strchr( _tmp, '.' ); *d = '\0'; add_simple_define( "__BGD__", _tmp ); d1 = d + 1; d = strchr( d1, '.' ); *d = '\0'; add_simple_define( "__BGD_MINOR__", d1 ); d1 = d + 1; add_simple_define( "__BGD_PATCHLEVEL__", d1 ); memset( &dcb, 0, sizeof( dcb ) ); core_init(); sysproc_init(); /* Get command line parameters */ for ( i = 1 ; i < argc ; i++ ) { if ( argv[i][0] == '-' ) { if ( !strcmp( argv[i], "--pedantic" ) ) { autodeclare = 0 ; continue; } if ( !strcmp( argv[i], "--libmode" ) ) { libmode = 1 ; continue; } j = 1; while ( argv[i][j] ) { if ( argv[i][j] == 'd' ) { if ( argv[i][j + 1] >= '0' && argv[i][j + 1] <= '9' ) { debug = atoi( &argv[i][j + 1] ); } else { debug = 1; } } if ( argv[i][j] == 'o' ) { if ( argv[i][j + 1] ) strncpy( dcbname, &argv[i][j + 1], sizeof( dcbname ) ); else if ( argv[i + 1] && argv[i + 1][0] != '-' ) strncpy( dcbname, argv[++i], sizeof( dcbname ) ); break; } if ( argv[i][j] == 'c' ) dos_chars = 1; if ( argv[i][j] == 'a' ) autoinclude = 1; if ( argv[i][j] == 'g' ) dcb_options |= DCB_DEBUG; if ( argv[i][j] == 'p' ) autodeclare = 0 ; if ( argv[i][j] == 's' ) { /* -s "stub": Use a stub */ if ( argv[i][j + 1] ) strncpy( stubname, &argv[i][j + 1], __MAX_PATH ); else if ( argv[i + 1] && argv[i + 1][0] != '-' ) strncpy( stubname, argv[++i], __MAX_PATH ); break; } if ( argv[i][j] == 'f' ) { /* -f "file": Embed a file to the DCB */ if ( argv[i][j + 1] ) dcb_add_file( &argv[i][j + 1] ); else while ( argv[i + 1] ) { if ( argv[i + 1][0] == '-' ) break; dcb_add_file( argv[i + 1] ); i++; } break; } if ( argv[i][j] == 'i' ) { /* -i "path": add a file to the path for include files */ if ( argv[i][j + 1] == 0 ) { if ( i == argc - 1 ) { printf( MSG_DIRECTORY_MISSING "\n" ); exit( 1 ); } file_addp( argv[i + 1] ); i++; break; } file_addp( &argv[i][j + 1] ); break; } if ( argv[i][j] == 'l' ) { /* -lLANG: Set the language for errors and messages */ if ( argv[i][j + 1] == 0 ) { if ( i != argc - 1 ) { strcpy( langinfo, argv[i + 1] ); } i++; break; } strcpy( langinfo, &argv[i][j + 1] ); break; } if ( argv[i][j] == 'D' ) { char * macro = NULL ; char * text = NULL ; /* -D<macro>=<text> */ if ( argv[i][j + 1] ) { macro = strdup( &argv[i][j + 1] ); } else { if ( argv[i + 1][0] == '-' ) break; macro = strdup( argv[i + 1] ); i++; } if (( text = strchr( macro, '=' ) ) ) { * text = '\0'; text++; } else { text = ""; } add_simple_define( macro, text ); free( macro ); break; } if ( argv[i][j] == 'C' ) { if ( argv[i][j + 1] == 'a' ) autodeclare = 1 ; break; } if ( argv[i][j] == 'L' ) { int r = 1; char * f; if ( argv[i][j + 1] ) r = dcb_load_lib( ( f = &argv[i][j + 1] ) ); else if ( argv[i + 1] && argv[i + 1][0] != '-' ) { r = dcb_load_lib( ( f = argv[i + 1] ) ); i++; } switch ( r ) { case 0: printf( "ERROR: %s doesn't exist or isn't version DCB compatible\n", f ) ; exit( -1 ); case -1: printf( "ERROR: %s isn't 7.10 DCB version, you need a 7.10 version or greater for use this feature\n", f ) ; exit( -1 ); } break; } j++; } } else { /* if ( sourcefile ) { printf( MSG_TOO_MANY_FILES "\n" ); return 0; } */ char * p, * pathend = NULL; sourcefile = argv[i]; p = main_path = strdup( argv[i] ); while ( p && *p ) { if ( *p == ':' || *p == '\\' || *p == '/' ) pathend = p; p++; } if ( pathend ) { *( pathend + 1 ) = '\0'; file_addp( main_path ); } else { free( main_path ); main_path = getcwd(malloc(__MAX_PATH), __MAX_PATH); strcat(main_path, PATH_SEP); } /* Files names */ strcpy( basepathname, sourcefile ); REMOVE_EXT( basepathname ); /* Default compiler imports */ strcpy( compilerimport, argv[0] ); #ifdef WIN32 REMOVE_EXT( compilerimport ); #endif strcat( compilerimport, ".imp" ); import_files( compilerimport ); strcat( compilerimport, "ort" ); /* name.import */ import_files( compilerimport ); /* Project imports */ strcpy( importname, basepathname ); strcat( importname, ".imp" ); import_files( importname ); strcat( importname, "ort" ); /* name.import */ import_files( importname ); /* Load Main Source File */ load_file( sourcefile ); if ( !dcbname[0] ) { strcpy( dcbname, basepathname ); strcat( dcbname, !libmode ? ".dcb" : ".dcl" ); } } } if ( !sourcefile ) { printf( MSG_USING MSG_OPTION_D MSG_OPTIONS MSG_LICENSE, argv[0] ); return 0; } compile_program(); if ( stubname[0] != 0 ) { if ( !file_exists( stubname ) ) { #ifdef WIN32 char exepath[__MAX_PATH]; GetModuleFileName( NULL, exepath, sizeof( exepath ) ); PathRemoveFileSpec( exepath ); strcat( exepath, "\\" ); memmove( stubname + strlen( exepath ), stubname, strlen( stubname ) + 1 ); memcpy( stubname, exepath, strlen( exepath ) ); #else const char * ptr = argv[0] + strlen( argv[0] ); while ( ptr > argv[0] && *ptr != '\\' && *ptr != '/' ) ptr--; if ( *ptr == '\\' || *ptr == '/' ) ptr++; if ( ptr > argv[0] ) { memmove( stubname + ( ptr - argv[0] ), stubname, strlen( stubname ) + 1 ); memcpy( stubname, argv[0], ptr - argv[0] ); } #endif if ( !file_exists( stubname ) ) { #ifdef WIN32 strcat( stubname, ".exe" ); if ( !file_exists( stubname ) ) { #endif compile_error( "Can't open stub file %s", stubname ); #ifdef WIN32 return -1; } #endif } } REMOVE_EXT( dcbname ); #ifdef WIN32 strcat( dcbname, ".exe" ); #endif dcb_save( dcbname, dcb_options, stubname ); } else { dcb_save( dcbname, dcb_options, NULL ); } /* destroy error messages list */ err_destroyErrorTable(); return 1; }
STRING *ssh_encrypt_rsa1(SSH_SESSION *session, STRING *data, PUBLIC_KEY *key) { STRING *str = NULL; size_t len = string_len(data); size_t size = 0; #ifdef HAVE_LIBGCRYPT const char *tmp = NULL; gcry_sexp_t ret_sexp; gcry_sexp_t data_sexp; if (gcry_sexp_build(&data_sexp, NULL, "(data(flags pkcs1)(value %b))", len, data->string)) { ssh_set_error(session, SSH_FATAL, "RSA1 encrypt: libgcrypt error"); return NULL; } if (gcry_pk_encrypt(&ret_sexp, data_sexp, key->rsa_pub)) { gcry_sexp_release(data_sexp); ssh_set_error(session, SSH_FATAL, "RSA1 encrypt: libgcrypt error"); return NULL; } gcry_sexp_release(data_sexp); data_sexp = gcry_sexp_find_token(ret_sexp, "a", 0); if (data_sexp == NULL) { ssh_set_error(session, SSH_FATAL, "RSA1 encrypt: libgcrypt error"); gcry_sexp_release(ret_sexp); return NULL; } tmp = gcry_sexp_nth_data(data_sexp, 1, &size); if (*tmp == 0) { size--; tmp++; } str = string_new(size); if (str == NULL) { ssh_set_error(session, SSH_FATAL, "Not enough space"); gcry_sexp_release(data_sexp); gcry_sexp_release(ret_sexp); return NULL; } string_fill(str, tmp, size); gcry_sexp_release(data_sexp); gcry_sexp_release(ret_sexp); #elif defined HAVE_LIBCRYPTO size = RSA_size(key->rsa_pub); str = string_new(size); if (str == NULL) { ssh_set_error(session, SSH_FATAL, "Not enough space"); return NULL; } if (RSA_public_encrypt(len, data->string, str->string, key->rsa_pub, RSA_PKCS1_PADDING) < 0) { string_free(str); return NULL; } #endif return str; }
TARGET* search_for_target ( char * name, LIST* search_path ) { PATHNAME f[1]; string buf[1]; LOCATED_TARGET lt, *lta = < time_t time; int found = 0; TARGET* result; string_new( buf ); path_parse( name, f ); f->f_grist.ptr = 0; f->f_grist.len = 0; while( search_path ) { f->f_root.ptr = search_path->string; f->f_root.len = strlen( search_path->string ); string_truncate( buf, 0 ); path_build( f, buf, 1 ); lt.file_name = buf->value ; if (! located_targets ) located_targets = hashinit( sizeof(LOCATED_TARGET), "located targets" ); if ( hashcheck( located_targets, (HASHDATA **)<a ) ) { return lta->target; } timestamp( buf->value, &time ); if (time) { found = 1; break; } search_path = list_next( search_path ); } if ( ! found ) { f->f_root.ptr = 0; f->f_root.len = 0; string_truncate( buf, 0 ); path_build( f, buf, 1 ); timestamp( buf->value, &time ); } result = bindtarget( name ); result->boundname = newstr( buf->value ); result->time = time; result->binding = time ? T_BIND_EXISTS : T_BIND_MISSING; call_bind_rule( result->name, result->boundname ); string_free( buf ); return result; }
int exec_wait() { int i = -1; /* Handle naive make1() which does not know if cmds are running. */ if ( !cmdsrunning ) return 0; /* Wait for a command to complete, while snarfing up any output. */ do { /* Check for a complete command, briefly. */ i = try_wait(500); /* Read in the output of all running commands. */ read_output(); /* Close out pending debug style dialogs. */ close_alerts(); /* Check if a command ran out of time. */ if ( i < 0 ) i = try_kill_one(); } while ( i < 0 ); /* We have a command... process it. */ --cmdsrunning; { timing_info time; int rstat; /* The time data for the command. */ record_times( cmdtab[ i ].pi.hProcess, &time ); /* Clear the temp file. */ if ( cmdtab[ i ].tempfile_bat ) { unlink( cmdtab[ i ].tempfile_bat ); BJAM_FREE( cmdtab[ i ].tempfile_bat ); cmdtab[ i ].tempfile_bat = NULL; } /* Find out the process exit code. */ GetExitCodeProcess( cmdtab[ i ].pi.hProcess, &cmdtab[ i ].exit_code ); /* The dispossition of the command. */ if ( intr ) rstat = EXEC_CMD_INTR; else if ( cmdtab[ i ].exit_code != 0 ) rstat = EXEC_CMD_FAIL; else rstat = EXEC_CMD_OK; /* Output the action block. */ out_action( cmdtab[ i ].action.size > 0 ? cmdtab[ i ].action.value : 0, cmdtab[ i ].target.size > 0 ? cmdtab[ i ].target.value : 0, cmdtab[ i ].command.size > 0 ? cmdtab[ i ].command.value : 0, cmdtab[ i ].buffer_out.size > 0 ? cmdtab[ i ].buffer_out.value : 0, cmdtab[ i ].buffer_err.size > 0 ? cmdtab[ i ].buffer_err.value : 0, cmdtab[ i ].exit_reason ); /* Call the callback, may call back to jam rule land. Assume -p0 in * effect so only pass buffer containing merged output. */ (*cmdtab[ i ].func)( cmdtab[ i ].closure, rstat, &time, cmdtab[ i ].command.value, cmdtab[ i ].buffer_out.value ); /* Clean up the command data, process, etc. */ string_free( &cmdtab[ i ].action ); string_new( &cmdtab[ i ].action ); string_free( &cmdtab[ i ].target ); string_new( &cmdtab[ i ].target ); string_free( &cmdtab[ i ].command ); string_new( &cmdtab[ i ].command ); if ( cmdtab[ i ].pi.hProcess ) { CloseHandle( cmdtab[ i ].pi.hProcess ); cmdtab[ i ].pi.hProcess = 0; } if ( cmdtab[ i ].pi.hThread ) { CloseHandle( cmdtab[ i ].pi.hThread ); cmdtab[ i ].pi.hThread = 0; } if ( cmdtab[ i ].pipe_out[ 0 ] ) { CloseHandle( cmdtab[ i ].pipe_out[ 0 ] ); cmdtab[ i ].pipe_out[ 0 ] = 0; } if ( cmdtab[ i ].pipe_out[ 1 ] ) { CloseHandle( cmdtab[ i ].pipe_out[ 1 ] ); cmdtab[ i ].pipe_out[ 1 ] = 0; } if ( cmdtab[ i ].pipe_err[ 0 ] ) { CloseHandle( cmdtab[ i ].pipe_err[ 0 ] ); cmdtab[ i ].pipe_err[ 0 ] = 0; } if ( cmdtab[ i ].pipe_err[ 1 ] ) { CloseHandle( cmdtab[ i ].pipe_err[ 1 ] ); cmdtab[ i ].pipe_err[ 1 ] = 0; } string_free( &cmdtab[ i ].buffer_out ); string_new( &cmdtab[ i ].buffer_out ); string_free( &cmdtab[ i ].buffer_err ); string_new( &cmdtab[ i ].buffer_err ); cmdtab[ i ].exit_code = 0; cmdtab[ i ].exit_reason = EXIT_OK; } return 1; }
void var_defines( struct module_t * module, char * const * e, int preprocess ) { string buf[1]; string_new( buf ); for ( ; *e; ++e ) { char * val; OBJECT * varname; # ifdef OS_MAC /* On the mac (MPW), the var=val is actually var\0val */ /* Think different. */ if ( ( val = strchr( *e, '=' ) ) || ( val = *e + strlen( *e ) ) ) # else if ( ( val = strchr( *e, '=' ) ) ) # endif { LIST * l = L0; char * pp; char * p; # ifdef OPT_NO_EXTERNAL_VARIABLE_SPLIT char split = '\0'; # else # ifdef OS_MAC char split = ','; # else char split = ' '; # endif # endif size_t len = strlen( val + 1 ); int quoted = ( val[1] == '"' ) && ( val[len] == '"' ) && ( len > 1 ); if ( quoted && preprocess ) { string_append_range( buf, val + 2, val + len ); l = list_push_back( l, object_new( buf->value ) ); string_truncate( buf, 0 ); } else { /* Split *PATH at :'s, not spaces. */ if ( val - 4 >= *e ) { if ( !strncmp( val - 4, "PATH", 4 ) || !strncmp( val - 4, "Path", 4 ) || !strncmp( val - 4, "path", 4 ) ) split = SPLITPATH; } /* Do the split. */ for ( pp = val + 1; preprocess && ( ( p = strchr( pp, split ) ) != 0 ); pp = p + 1 ) { string_append_range( buf, pp, p ); l = list_push_back( l, object_new( buf->value ) ); string_truncate( buf, 0 ); } l = list_push_back( l, object_new( pp ) ); } /* Get name. */ string_append_range( buf, *e, val ); varname = object_new( buf->value ); var_set( module, varname, l, VAR_SET ); object_free( varname ); string_truncate( buf, 0 ); } } string_free( buf ); }
string_t * string_dup(const string_t *in) { return string_new(in->text, in->length); }
UriUriA *create_absolute_uri(const UriUriA *base_uri, const char *url) { UriParserStateA state; UriUriA *abs_dest, rel_source; char *newurl; if (!url || !*url) return NULL; if ((abs_dest = uri_alloc_1()) == NULL) return NULL; if (base_uri) { state.uri = &rel_source; if (uriParseUriA(&state, url) != URI_SUCCESS) { uri_free(abs_dest); uriFreeUriMembersA(&rel_source); return NULL; } if (uriAddBaseUriA(abs_dest, &rel_source, base_uri) != URI_SUCCESS) { uri_free(abs_dest); uriFreeUriMembersA(&rel_source); return NULL; } uriFreeUriMembersA(&rel_source); } else { state.uri = abs_dest; if (uriParseUriA(&state, url) != URI_SUCCESS) { uri_free(abs_dest); return NULL; } } if (uriNormalizeSyntaxA(abs_dest) != URI_SUCCESS) { uri_free(abs_dest); return NULL; } /* http://www.example.com and http://www.example.com/ have to generate the same object */ if (!base_uri && (!abs_dest->pathHead || !abs_dest->pathHead->text.first) && !abs_dest->query.first) { newurl = string_new(url); string_cat(&newurl, "/"); uriFreeUriMembersA(abs_dest); state.uri = abs_dest; if (uriParseUriA(&state, newurl) != URI_SUCCESS) { uri_free(abs_dest); string_free(newurl); return NULL; } if (uriNormalizeSyntaxA(abs_dest) != URI_SUCCESS) { uri_free(abs_dest); string_free(newurl); return NULL; } string_free(newurl); } return abs_dest; }
static void test_string_is_empty() { char *string = string_new(); CU_ASSERT_TRUE(string_is_empty(string)); free(string); }
static char * exprint_constituent_structure(con_context_t *ctxt, Linkage linkage, int numcon_total) { size_t w; int c; bool *leftdone = alloca(numcon_total * sizeof(bool)); bool *rightdone = alloca(numcon_total * sizeof(bool)); int best, bestright, bestleft; char *p; char s[MAX_WORD]; String * cs = string_new(); assert (numcon_total < ctxt->conlen, "Too many constituents (b)"); for (c = 0; c < numcon_total; c++) { leftdone[c] = false; rightdone[c] = false; } if (verbosity >= 2) printf("\n"); /* Skip left wall; don't skip right wall, since it may * have constituent boundaries. */ for (w = 1; w < linkage->num_words; w++) { while (1) { best = -1; bestright = -1; for (c = 0; c < numcon_total; c++) { if ((ctxt->constituent[c].left == w) && (leftdone[c] == false) && ctxt->constituent[c].valid && ((int) ctxt->constituent[c].right >= bestright)) { best = c; bestright = ctxt->constituent[c].right; } } if (best == -1) break; leftdone[best] = true; append_string(cs, "%c%s ", OPEN_BRACKET, ctxt->constituent[best].type); } /* Don't print out right wall */ if (w < linkage->num_words - 1) { char *p; strncpy(s, linkage->word[w], MAX_WORD); s[MAX_WORD-1] = 0; /* Constituent processing will crash if the sentence contains * square brackets, so we have to do something ... replace * them with curly braces ... this is a terrible hack, but * will have to do; for now. A better solution would be to * allow the user to specify some reserved char as the * bracket symbol, e.g. SOH and EOT or something like that. */ p = strchr(s, OPEN_BRACKET); while (p) { *p = '{'; p = strchr(p, OPEN_BRACKET); } p = strchr(s, CLOSE_BRACKET); while (p) { *p = '}'; p = strchr(p, CLOSE_BRACKET); } #if 0 /* firstupper check removed in 0c8107a */ /* Now, if the first character of the word was originally uppercase, we put it back that way */ if (linkage->chosen_disjuncts[w]->word[0]->status & WS_FIRSTUPPER) upcase_utf8_str(s, s, MAX_WORD); #endif append_string(cs, "%s ", s); } while (1) { best = -1; bestleft = -1; for(c = 0; c < numcon_total; c++) { if ((ctxt->constituent[c].right == w) && (rightdone[c] == false) && ctxt->constituent[c].valid && ((int) ctxt->constituent[c].left > bestleft)) { best = c; bestleft = ctxt->constituent[c].left; } } if (best == -1) break; rightdone[best] = true; append_string(cs, "%s%c ", ctxt->constituent[best].type, CLOSE_BRACKET); } } append_string(cs, "\n"); p = string_copy(cs); string_delete(cs); return p; }
int main(int argc, char *argv[]) { string *s = NULL; string *s2 = NULL; string *s3 = NULL; s = string_append(s, "Hello There"); test(s, "Hello There"); s = string_append(s, "123"); test(s, "Hello There123"); s = string_insert(s, 1, "<new>"); test(s, "H<new>ello There123"); s = string_insert(s, 23, "<new>"); test(s, "H<new>ello There123<new>"); s = string_remove(s, 11, 5); test(s, "H<new>ello 123<new>"); s = string_replace(s, "<new>", "<nothing>"); test(s, "H<nothing>ello 123<nothing>"); s = string_remove(s, 0, 30); test(s, ""); s = string_append(s, "H<nothing>ello 123<nothing>"); test(s, "H<nothing>ello 123<nothing>"); s = string_trunc(s); test(s, ""); string_free(&s); s = string_append_int(s, 1); test(s, "1"); s = string_append_int(s, 10); test(s, "110"); s = string_append_int(s, 100); test(s, "110100"); s = string_append_int(s, 1000000000); test(s, "1101001000000000"); s = string_append_int(s, -2); test(s, "1101001000000000-2"); s = string_append_int(s, -345); test(s, "1101001000000000-2-345"); s = string_append_int(s, -3.45); test(s, "1101001000000000-2-345-3"); s = string_trunc(s); test(s,""); s = string_prepend_int(s, 1); test(s, "1"); s = string_prepend_int(s, 10); test(s, "101"); s = string_prepend_int(s, 100); test(s, "100101"); s = string_prepend_int(s, 1000000000); test(s, "1000000000100101"); s = string_prepend_int(s, -2); test(s, "-21000000000100101"); s = string_prepend_int(s, -345); test(s, "-345-21000000000100101"); s = string_prepend_int(s, -3.45); test(s, "-3-345-21000000000100101"); s = string_trunc(s); test(s,""); string_free(&s); s = string_new("\"Quoted String\""); test(s, "\"Quoted String\""); s = string_replace(s, "\"", ""); test(s, "Quoted String"); string_free(&s); s = string_prepend(s, "Nothing"); test(s, "Nothing"); s = string_prepend(s, "12345678901234567890"); test(s, "12345678901234567890Nothing"); s = string_prepend(s, "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"); test(s, "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890Nothing"); string_free(&s); s = string_append(s, "Nothing"); test(s, "Nothing"); s = string_append(s, "12345678901234567890"); test(s, "Nothing12345678901234567890"); s = string_append(s, "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"); test(s, "Nothing12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890"); string_free(&s); s = string_new("printf_append"); test(s, "printf_append"); s = string_printf_append(s, "%8s %3d %10.6f", "string", 20, 3.4); test(s, "printf_append string 20 3.400000"); string_free(&s); s = string_new(""); s = string_printf(s, "%8s %3d %10.6f", "string", 20, 3.4); test(s, " string 20 3.400000"); s2 = string_copy(s); test(s2, " string 20 3.400000"); testi(string_equal_char(s, string_string(s2)), 1); testi(string_equal(s, s2), 1); testi(string_equal_char(s, " string 20 3.40"), 0); s3 = string_new(" string 20 3.40"); testi(string_equal(s, s3), 0); string_free(&s2); string_free(&s3); s = string_remove(s, 100000, 20); test(s, " string 20 3.400000"); s = string_remove(s, 15, 20); test(s, " string 20 "); s = string_remove(s, 13, -1); test(s, " string 20 "); s = string_remove(s, 1, 1); test(s, " string 20 "); s = string_remove(s, 7, 2); test(s, " string20 "); s = string_remove(s, 9, 1); test(s, " string20"); s = string_remove(s, -1, -1); test(s, ""); s = string_insert(s, -1, " string20"); test(s, " string20"); s = string_insert(s, 9, " "); test(s, " string20 "); s = string_insert(s, 7, " "); test(s, " string 20 "); s = string_insert(s, 1, " "); test(s, " string 20 "); s = string_insert(s, 13, " "); test(s, " string 20 "); s = string_insert(s, 15, "3.400000"); test(s, " string 20 3.400000"); s = string_insert(s, 10000, " morestuff"); test(s, " string 20 3.400000 morestuff"); s = string_insert(s, -1, " morestuff"); test(s, " morestuff string 20 3.400000 morestuff"); s2 = string_substr(s, 1, 4); test(s2, "more"); string_free(&s2); s2 = string_substr(s, 5, 7); test(s2, "stuff "); string_free(&s2); string_free(&s); return retval; }
LIST* builtin_system_registry( PARSE *parse, FRAME *frame ) { char const* path = lol_get(frame->args, 0)->string; LIST* result = L0; HKEY key = get_key(&path); if ( key != 0 && ERROR_SUCCESS == RegOpenKeyEx(key, path, 0, KEY_QUERY_VALUE, &key) ) { DWORD type; BYTE data[MAX_REGISTRY_DATA_LENGTH]; DWORD len = sizeof(data); LIST const* const field = lol_get(frame->args, 1); if ( ERROR_SUCCESS == RegQueryValueEx(key, field ? field->string : 0, 0, &type, data, &len) ) { switch (type) { case REG_EXPAND_SZ: { long len; string expanded[1]; string_new(expanded); while ( (len = ExpandEnvironmentStrings( (LPCSTR)data, expanded->value, expanded->capacity)) > expanded->capacity ) string_reserve(expanded, len); expanded->size = len - 1; result = list_new( result, newstr(expanded->value) ); string_free( expanded ); } break; case REG_MULTI_SZ: { char* s; for (s = (char*)data; *s; s += strlen(s) + 1) result = list_new( result, newstr(s) ); } break; case REG_DWORD: { char buf[100]; sprintf( buf, "%u", *(PDWORD)data ); result = list_new( result, newstr(buf) ); } break; case REG_SZ: result = list_new( result, newstr((char*)data) ); break; } } RegCloseKey(key); } return result; }
/* rule transform ( list * : pattern : indices * ) { indices ?= 1 ; local result ; for local e in $(list) { local m = [ MATCH $(pattern) : $(e) ] ; if $(m) { result += $(m[$(indices)]) ; } } return $(result) ; } */ LIST *regex_transform( PARSE *parse, FRAME *frame ) { LIST* l = lol_get( frame->args, 0 ); LIST* pattern = lol_get( frame->args, 1 ); LIST* indices_list = lol_get(frame->args, 2); int* indices = 0; int size; int* p; LIST* result = 0; string buf[1]; string_new(buf); if (indices_list) { size = list_length(indices_list); indices = (int*)malloc(size*sizeof(int)); for(p = indices; indices_list; indices_list = indices_list->next) { *p++ = atoi(indices_list->string); } } else { size = 1; indices = (int*)malloc(sizeof(int)); *indices = 1; } { /* Result is cached and intentionally never freed */ regexp *re = regex_compile( pattern->string ); for(; l; l = l->next) { if( regexec( re, l->string ) ) { int i = 0; for(; i < size; ++i) { int index = indices[i]; /* Skip empty submatches. Not sure it's right in all cases, but surely is right for the case for which this routine is optimized -- header scanning. */ if (re->startp[index] != re->endp[index]) { string_append_range( buf, re->startp[index], re->endp[index] ); result = list_new( result, newstr( buf->value ) ); string_truncate( buf, 0 ); } } } } string_free( buf ); } free(indices); return result; }
char * charToString(char valor){ char * res = string_new(); string_append_with_format(&res, "%c", valor); return res; }
static int translate_path_posix2vms( string * path ) { int translated = 0; string as_dir[ 1 ]; string as_file[ 1 ]; int dir_count; int file_count; unsigned char is_dir; unsigned char is_file; unsigned char is_ambiguous; string_new( as_dir ); string_new( as_file ); m_vmsfilespec = as_dir; /* MATCH 0:do not allow wildcards, 0:allow directories (2:dir only) */ dir_count = decc$to_vms( path->value, copy_vmsfilespec, 0, 2 ); m_vmsfilespec = as_file; /* MATCH 0:do not allow wildcards, 0:allow directories (2:dir only) */ file_count = decc$to_vms( path->value, copy_vmsfilespec, 0, 0 ); m_vmsfilespec = NULL; translated = ( file_count || dir_count ); if ( file_count && dir_count ) { struct stat statbuf; /* use as_file only when exists AND as_dir does not exist * otherwise use as_dir */ if ( stat(as_dir->value, &statbuf ) < 0 && stat(as_file->value, &statbuf ) > 0 && ( statbuf.st_mode & S_IFREG ) ) { string_truncate( path, 0 ); string_append( path, as_file->value ); } else { string_truncate( path, 0 ); string_append( path, as_dir->value ); } } else if ( file_count ) { string_truncate( path, 0 ); string_append( path, as_file->value ); } else if ( dir_count ) { string_truncate( path, 0 ); string_append( path, as_dir->value ); } else { /* error: unable to translate path to native format */ translated = 0; } string_free( as_dir ); string_free( as_file ); return translated; }
static int modtime_ftime( INSTANCE * my, int * params ) { char buffer[128] ; char * format ; struct tm * t ; int ret ; time_t tim ; char * base ; #ifdef _WIN32 /* aux buffer to make all changes... */ char aux[128] ; unsigned char pos ; #endif format = base = strdup( string_get( params[0] ) ) ; string_discard( params[0] ) ; #ifdef _WIN32 /* Addapting win32 strftime formats to linux formats */ /* HEAVY PATCH... :( */ pos = 0 ; while ( *format && pos < 127 ) { switch ( *format ) { case '%': /* MIGHT NEED CONVERSION... */ aux[pos] = *format ; pos++ ; format++ ; switch ( *format ) { case 'e': aux[pos++] = '#' ; aux[pos] = 'd' ; break ; case 'l': aux[pos++] = '#' ; aux[pos] = 'I' ; break ; case 'k': aux[pos++] = '#' ; aux[pos] = 'H' ; break ; case 'P': aux[pos] = 'p' ; break ; case 'C': aux[pos++] = '%' ; aux[pos++] = *format ; aux[pos++] = '%' ; aux[pos] = 'Y' ; break ; case 'u': aux[pos++] = '%' ; aux[pos++] = *format ; aux[pos++] = '%' ; aux[pos] = 'w' ; break ; case '%': //MUST BE %%%% TO KEEP 2 IN POSTPROCESS aux[pos++] = '%' ; aux[pos++] = '%' ; aux[pos] = '%' ; break ; default: aux[pos] = *format ; break ; } break ; default: aux[pos] = *format ; break ; } format++ ; pos++ ; } aux[pos] = 0 ; format = aux ; #endif tim = ( time_t ) params[1] ; t = localtime( &tim ) ; strftime( buffer, sizeof( buffer ), format, t ) ; #ifdef _WIN32 /* win32 postprocess */ aux[0] = '\0' ; format = buffer ; pos = 0 ; while ( *format ) { switch ( *format ) { case '%': format++ ; switch ( *format ) { case 'u': format++ ; if ( *format == '0' ) *format = '7' ; aux[pos] = *format ; break ; case 'C': format++ ; aux[pos++] = *format ; format++ ; aux[pos] = *format ; format++ ; format++ ; break ; default: aux[pos] = *format ; break ; } break ; default: aux[pos] = *format ; break ; } format++ ; pos++; } aux[pos] = '\0' ; strcpy( buffer, aux ) ; #endif ret = string_new( buffer ) ; string_use( ret ) ; free( base ) ; return ret ; }
int var_string( char *in, char *out, int outsize, LOL *lol ) { char *out0 = out; char *oute = out + outsize - 1; while( *in ) { char *lastword; int dollar = 0; /* Copy white space */ while( isspace( *in ) ) { if( out >= oute ) return -1; *out++ = *in++; } lastword = out; /* Copy non-white space, watching for variables */ while( *in && !isspace( *in ) ) { if( out >= oute ) return -1; if( in[0] == '$' && in[1] == '(' ) dollar++; #ifdef OPT_AT_FILES else if ( in[0] == '@' && in[1] == '(' ) { int depth = 1; char *ine = in + 2; char *split = 0; /* Scan the content of the response file @() section. */ while( *ine && depth > 0 ) { switch( *ine ) { case '(': ++depth; break; case ')': --depth; break; case ':': if( depth == 1 && ine[1] == 'E' && ine[2] == '=' ) { split = ine; } break; } ++ine; } if (!split) { /* the @() reference doesn't match the @(foo:E=bar) format. hence we leave it alone by copying directly to output. */ int l = 0; if ( out+2 >= oute ) return -1; *(out++) = '@'; *(out++) = '('; l = var_string(in+2,out,oute-out,lol); if ( l < 0 ) return -1; out += l; if ( out+1 >= oute ) return -1; *(out++) = ')'; in = ine; } else if ( depth == 0 ) { string file_name_v; int file_name_l = 0; const char * file_name_s = 0; /* expand the temporary file name var inline */ #if 0 string_copy(&file_name_v,"$("); string_append_range(&file_name_v,in+2,split); string_push_back(&file_name_v,')'); #else string_new(&file_name_v); string_append_range(&file_name_v,in+2,split); #endif file_name_l = var_string(file_name_v.value,out,oute-out+1,lol); string_free(&file_name_v); if ( file_name_l < 0 ) return -1; file_name_s = out; /* for stdout/stderr we will create a temp file and generate a command that outputs the content as needed. */ if ( strcmp( "STDOUT", out ) == 0 || strcmp( "STDERR", out ) == 0 ) { int err_redir = strcmp( "STDERR", out ) == 0; out[0] = '\0'; file_name_s = path_tmpfile(); file_name_l = strlen(file_name_s); #ifdef OS_NT if ( (out+7+file_name_l+(err_redir?5:0)) >= oute ) return -1; sprintf( out,"type \"%s\"%s", file_name_s, err_redir ? " 1>&2" : "" ); #else if ( (out+6+file_name_l+(err_redir?5:0)) >= oute ) return -1; sprintf( out,"cat \"%s\"%s", file_name_s, err_redir ? " 1>&2" : "" ); #endif /* we also make sure that the temp files created by this get nuked eventually. */ file_remove_atexit( file_name_s ); } /* expand the file value into the file reference */ var_string_to_file( split+3, ine-split-4, file_name_s, lol ); /* continue on with the expansion */ out += strlen(out); } /* and continue with the parsing just past the @() reference */ in = ine; } #endif *out++ = *in++; } /* Add zero to 'out' so that 'lastword' is correctly zero-terminated. */ if (out >= oute) return -1; /* Don't increment, intentionally. */ *out= '\0'; /* If a variable encountered, expand it and and embed the */ /* space-separated members of the list in the output. */ if( dollar ) { LIST *l; l = var_expand( L0, lastword, out, lol, 0 ); out = lastword; while ( l ) { int so = strlen( l->string ); if( out + so >= oute ) return -1; strcpy( out, l->string ); out += so; l = list_next( l ); if ( l ) *out++ = ' '; } list_free( l ); } } if( out >= oute ) return -1; *out++ = '\0'; return out - out0; }
static mulk_type_return_t filter_buffer(int i, int valid_res, const char *base_url, long err_code, long resp_code) { char *newfilename = NULL; char *newmimefilename = NULL; char *subtype = NULL; char *type = NULL; mulk_type_return_t ret = MULK_RET_OK; buffer_t *buffer = buffer_array + i; #ifdef ENABLE_METALINK metalink_file_list_t *metalink = buffer->url->metalink_uri; if (metalink) buffer->url->http_code = 0; else #endif { buffer->url->err_code = err_code; buffer->url->http_code = resp_code; } if (!valid_res) { #ifdef ENABLE_METALINK if (metalink) buffer->url->err_code = METALINK_RES_NO_NORE_RESOURCES; #endif remove(buffer->filename); return MULK_RET_ERR; } #ifdef ENABLE_RECURSION if (is_html_file(buffer->url->mimetype)) parse_urls(buffer->filename, base_url, buffer->url->level); #endif #ifdef ENABLE_METALINK if (option_values.follow_metalink && is_metalink_file(buffer->url->mimetype)) add_new_metalink(buffer->filename, buffer->url->level); if (metalink) { #ifdef ENABLE_CHECKSUM if (verify_metalink_file(metalink->file, buffer->filename) == CS_VERIFY_ERR) { MULK_NOTE((_("The file will be deleted.\n"))); buffer->url->err_code = METALINK_RES_WRONG_CHECKSUM; ret = MULK_RET_ERR; } else #endif /* ENABLE_CHECKSUM */ { string_printf(&newfilename, "%s%s", option_values.file_output_directory, metalink->file->name); buffer->url->err_code = METALINK_RES_OK; } } else #endif /* ENABLE_METALINK */ if (!option_values.disable_save_tree) { UriUriA *uri = create_absolute_uri(NULL, base_url); char *furi_str = uri2filename(uri); if (furi_str) { string_printf(&newfilename, "%s%s", option_values.file_output_directory, furi_str); /* add index.<mime-type> if the filename represents a directory name */ if (newfilename[strlen(newfilename)-1] == *DIR_SEPAR_STR) { string_cat(&newfilename, "index."); if (extract_mime_type(buffer->url->mimetype, NULL, &subtype) == MULK_RET_OK) { string_cat(&newfilename, subtype); string_free(&subtype); } else string_cat(&newfilename, "bin"); } } string_free(&furi_str); uri_free(uri); } if ((is_gif_image(buffer->url->mimetype) && is_valid_gif_image(buffer->filename)) || (is_png_image(buffer->url->mimetype) && is_valid_png_image(buffer->filename)) || (is_jpeg_image(buffer->url->mimetype) && is_valid_jpeg_image(buffer->filename)) || (is_saved_mime_type(buffer->url->mimetype))) { if (extract_mime_type(buffer->url->mimetype, &type, &subtype) == MULK_RET_OK) { string_printf(&newmimefilename, "%s%s%s%s_%05d.%s", option_values.mime_output_directory, type, DIR_SEPAR_STR, subtype, buffer->url->id, subtype); string_free(&type); string_free(&subtype); } } /* save file */ buffer->url->filename = string_new(newfilename); buffer->url->mimefilename = string_new(newmimefilename); if (newfilename && newmimefilename) { if ((ret = save_file_to_outputdir(buffer->filename, newfilename, 1)) == MULK_RET_OK) ret = save_file_to_outputdir(buffer->filename, newmimefilename, 0); } else if (newfilename) ret = save_file_to_outputdir(buffer->filename, newfilename, 0); else if (newmimefilename) ret = save_file_to_outputdir(buffer->filename, newmimefilename, 0); else remove(buffer->filename); string_free(&newmimefilename); string_free(&newfilename); return ret; }
void token_next() { static int i, len; static char buffer[1024]; char * buffer_ptr = buffer; if ( !source_ptr ) { token.type = NOTOKEN; return; } if ( use_saved ) { token = token_saved; line_count = token.line; current_file = token.file; use_saved = 0; return; } token.line = line_count; token.file = current_file; token_prev = token; while ( 1 ) { SKIP_SPACES; if ( !disable_prepro && *source_ptr == '#' ) { int line; const char * old_source_ptr; identifiers_as_strings = 0; /* Comandos de preprocesador */ source_ptr++; line = line_count; SKIP_SPACES_UNTIL_LF_AND_COUNT_LINES; if ( *source_ptr == '\n' ) { token.code = identifier_search_or_add( "#" ); token.type = IDENTIFIER; line_count = line; compile_error( MSG_IDENTIFIER_EXP ); } old_source_ptr = source_ptr; if ( ISWORDFIRST( *source_ptr ) ) { GET_NEXT_TOKEN_IN_TMPBUFFER; /* #include "file.h" */ if ( token.code == identifier_include && !use_saved ) { include_file( 1 ); return; } source_ptr = old_source_ptr; } preprocessor(); buffer_ptr = buffer; *buffer_ptr = '\0'; continue; } if ( !*source_ptr ) { /* Casos de bloques manuales */ if ( current_file == -1 ) { token_endfile(); token.type = NOTOKEN; return; } while ( !*source_ptr ) { if ( sources == 0 ) { token.type = NOTOKEN; return; } token_endfile(); if ( !source_ptr ) { token.type = NOTOKEN; return; } } continue; } /* Ignora comentarios */ SKIP_COMMENTS; if ( !*source_ptr ) { token.type = NOTOKEN; return; } /* Cadenas */ if ( *source_ptr == '"' || *source_ptr == '\'' ) { token.type = STRING; token.code = string_compile( &source_ptr ); token.line = line_count; token.file = current_file; return; } /* Operadores de más de un caracter */ len = 0; if ( *source_ptr == '<' ) { if ( source_ptr[1] == '<' ) { if ( source_ptr[2] == '=' ) len = 3; else len = 2; } else if ( source_ptr[1] == '>' ) len = 2; else if ( source_ptr[1] == '=' ) len = 2; else len = 1; } else if ( *source_ptr == '>' ) { if ( source_ptr[1] == '>' ) { if ( source_ptr[2] == '=' ) len = 3; else len = 2; } else if ( source_ptr[1] == '=' ) len = 2; else if ( source_ptr[1] == '>' ) len = 2; else len = 1; } else if ( *source_ptr == '|' ) { if ( source_ptr[1] == '|' ) { if ( source_ptr[2] == '=' ) len = 3; else len = 2; } else if ( source_ptr[1] == '=' ) len = 2; else len = 1; } else if ( *source_ptr == '=' ) { if ( source_ptr[1] == '=' ) len = 2; else if ( source_ptr[1] == '>' ) len = 2; else if ( source_ptr[1] == '<' ) len = 2; else len = 1; } else if ( *source_ptr == '.' ) { if ( source_ptr[1] == '.' ) len = 2; else len = 1; } else if ( strchr( "!&^%*+-/", *source_ptr ) ) { if ( source_ptr[1] == '=' ) len = 2; else if ( strchr( "+-&^", *source_ptr ) && source_ptr[1] == *source_ptr ) len = 2; else len = 1; } if ( len ) { strncpy( buffer, source_ptr, len ); buffer[len] = 0; source_ptr += len; token.code = identifier_search_or_add( buffer ); token.type = IDENTIFIER; token.line = line_count; token.file = current_file; return; } /* Numbers */ if ( ISNUM( *source_ptr ) ) { const char * ptr; double num = 0, dec; int base = 10; /* Hex/Bin/Octal numbers with the h/b/o sufix */ ptr = source_ptr; while ( ISNUM( *ptr ) || ( *ptr >= 'a' && *ptr <= 'f' ) || ( *ptr >= 'A' && *ptr <= 'F' ) ) ptr++; if ( *ptr != 'h' && *ptr != 'H' && *ptr != 'o' && *ptr != 'O' && ( ptr[-1] == 'b' || ptr[-1] == 'B' ) ) ptr--; if ( *ptr == 'b' || *ptr == 'B' ) base = 2; if ( *ptr == 'h' || *ptr == 'H' ) base = 16; if ( *ptr == 'o' || *ptr == 'O' ) base = 8; token.code = 0 ; /* for ints values */ /* Calculate the number value */ while ( ISNUM( *source_ptr ) || ( base > 10 && ISALNUM( *source_ptr ) ) ) { if ( base == 2 && *source_ptr != '0' && *source_ptr != '1' ) break; if ( base == 8 && ( *source_ptr < '0' || *source_ptr > '7' ) ) break; if ( base == 10 && !ISNUM( *source_ptr ) ) break; if ( base == 16 && !ISNUM( *source_ptr ) && ( TOUPPER( *source_ptr ) < 'A' || TOUPPER( *source_ptr ) > 'F' ) ) break; if ( ISNUM( *source_ptr ) ) { num = num * base + ( *source_ptr - '0' ); token.code = token.code * base + ( *source_ptr - '0' ); source_ptr++; continue; } if ( *source_ptr >= 'a' && *source_ptr <= 'f' && base > 10 ) { num = num * base + ( *source_ptr - 'a' + 10 ); token.code = token.code * base + ( *source_ptr - 'a' + 10 ); source_ptr++; continue; } if ( *source_ptr >= 'A' && *source_ptr <= 'F' && base > 10 ) { num = num * base + ( *source_ptr - 'A' + 10 ); token.code = token.code * base + ( *source_ptr - 'A' + 10 ); source_ptr++; continue; } } token.type = NUMBER; token.value = ( float )num; /* We have the integer part now - convert to int/float */ if ( *source_ptr == '.' && base == 10 ) { source_ptr++; if ( !ISNUM( *source_ptr ) ) source_ptr--; else { dec = 1.0 / ( double )base; while ( ISNUM( *source_ptr ) || ( base > 100 && ISALNUM( *source_ptr ) ) ) { if ( ISNUM( *source_ptr ) ) num = num + dec * ( *source_ptr++ - '0' ); if ( *source_ptr >= 'a' && *source_ptr <= 'f' && base > 10 ) num = num + dec * ( *source_ptr++ - 'a' + 10 ); if ( *source_ptr >= 'A' && *source_ptr <= 'F' && base > 10 ) num = num + dec * ( *source_ptr++ - 'A' + 10 ); dec /= ( double )base; } token.type = FLOAT; token.value = ( float )num; } } /* Skip the base sufix */ if ( base == 16 && ( *source_ptr == 'h' || *source_ptr == 'H' ) ) source_ptr++; if ( base == 8 && ( *source_ptr == 'o' || *source_ptr == 'O' ) ) source_ptr++; if ( base == 2 && ( *source_ptr == 'b' || *source_ptr == 'B' ) ) source_ptr++; token.line = line_count; token.file = current_file; return; } /* Identificadores */ if ( ISWORDFIRST( *source_ptr ) ) { int maybe_label = source_ptr[-1] == '\n'; GET_NEXT_TOKEN_IN_TMPBUFFER; token.line = line_count; token.file = current_file; if ( maybe_label && *source_ptr == ':' ) { source_ptr++; token.code = identifier_search_or_add( buffer ); token.type = LABEL; return; } /* Search for #define constant inclusion at this point */ if ( !disable_expand_defines ) { if ( !strcmp( buffer, "__FILE__" ) ) { token.type = STRING; token.code = string_new(( current_file != -1 && files[current_file] && *files[current_file] ) ? files[current_file] : "N/A" ); token.line = line_count; token.file = current_file; return; } if ( !strcmp( buffer, "__LINE__" ) ) { token.type = NUMBER; token.code = ( int )line_count; token.value = ( float )line_count; token.line = line_count; token.file = current_file; return; } for ( i = 0; i < defines_count; i++ ) { if ( defines[i].code == token.code ) { preprocessor_expand( &defines[i] ); token_next(); token.line = line_count; token.file = current_file; return; } } } /* In a #if, all identifiers are strings */ if ( identifiers_as_strings ) { token.type = STRING; token.code = string_new( buffer ); token.line = line_count; token.file = current_file; return; } /* Include */ if ( !disable_prepro && token.code == identifier_include && !use_saved ) { include_file( 0 ); return; } return; } /* 1-char operator or invalid symbol */ if ( !*source_ptr ) break; if ( *source_ptr > 0 && *source_ptr < 32 ) compile_error( MSG_INVALID_CHAR ); *buffer_ptr++ = *source_ptr++; *buffer_ptr = 0; token.code = identifier_search_or_add( buffer ); token.type = IDENTIFIER; token.line = line_count; token.file = current_file; return; } token.type = NOTOKEN; return; /* End-of-file */ }
//Recibe y procesa un mensaje recibido void receiptMessage(void * arguments) { args_receiptMessage * args = arguments; int numbytes; /* bytes recibidos por cada lectura (0 = desconexion del cliente) */ char buffer[MAXDATASIZE]; /* buffer de lectura */ bool bufferUsed; /* determina si se analizo por lo menos una vez un nuevo set de datos */ unsigned int n = -1; /* cantidad de argumentos del packete que recibo */ int i = 0; /* ayuda a saber la ultima posicion de lectura en el buffer (tambien se usa como i en otros casos) */ int j = 0; /* j de for */ int seps = 0; /* cantidad de separadores ,(coma) contados en el encabezado del paquete */ char * packet_head; /* encabezado del paquete */ char * packet_body; /* cuerpo del paquete */ char * exceeded; /* datos excedidos del final del paquete */ char * str_tmp; /* temporar para operaciones de string */ bool isExceeded = false; /* determina si hay datos excedidos cargados en el buffer */ bool fullHead = false; /* determina si ya fue recibido el encabezado del paquete */ int bytesBody = 0; /* determina los bytes que contendrá el cuerpo del paquete */ char ** head = NULL; /* encabezado divido por n, name y bytes de los args */ char * b; /* utilizado para extraer bytes del buffer */ void (*fn)(); /* utilizado para guardar la funcion que hay que ejecutar del cliente */ char ** packet_args; /* Argumentos que se envian por la funcion */ //loopeo while(1) { //si en la ultima lectura dejo informacion excedida la guardo if(isExceeded) exceeded = string_duplicate(buffer); //Pongo en blanco el buffer buffer[0] = '\0'; //Espero a recibir un mensaje del job, si se produce un error lo informo error y finalizo hilo if ((numbytes=recv(args->connection->socket, buffer, MAXDATASIZE-1, 0)) == -1) { //perror("recv"); break; } //si en la ultima lectura dejo informacion excedida la agrego al inicio del buffer if(isExceeded) { exceeded = string_new(); string_append(&exceeded, buffer); buffer[sizeof(exceeded)] = '\0'; //mejor que memset? strcpy(buffer, exceeded); free(exceeded); } //finalizo el hilo if(numbytes == 0) break; else { //Corta el bufer hasta donde recibe informacion buffer[numbytes] = '\0'; //analizo el buffer si es la primera vez que lo voy a analizar o si queda informacion excedida para seguir analizando //(Analizar significa, buscar paquetes completos y ejecutarlos) bufferUsed = false; while(!bufferUsed || isExceeded) { bufferUsed = true; isExceeded = false; i = 0; //si comienzo a leer un nuevo paquete inicializo el head y el body if(n == -1) { packet_head = string_new(); packet_body = string_new(); } //recorro buffer hasta armar cabezal si no esta armado if(!fullHead) { for(i = 0; i < strlen(buffer); i++) { b = buffer[i]; //primer caracter es [n] (cantidad de args) if(n == -1) n = atoi(&b); //cuento comas else if(b == ',') seps++; //voy completando cabezal string_append(&packet_head, &b); //fianlizo cuando llego al ultimo separador if(n+2 == seps) { fullHead = true; i++; //dejo posicion en el primer byte del cuerpo del paquete break; } } } //cabezal completo if(fullHead) { //si el cabezal no fue explodiado, le doy explode y calculo los bytes del cabezal if(head == NULL) { //hago explode head = string_n_split(packet_head, n+2, ","); for(j = 2; j < n+2; j++) bytesBody += atoi(head[j]); } //Agrego al cuerpo del packete todos los datos str_tmp = string_substring_from(buffer, i); string_append(&packet_body, str_tmp); free(str_tmp); //paquete completo if(bytesBody <= strlen(packet_body)) { //si el paquete esta excedido, corto el paquete en la posicion correspondiente y guardo el excedente sobre el buffer if(bytesBody < strlen(packet_body)) { isExceeded = true; exceeded = string_substring_from(packet_body, bytesBody); str_tmp = string_substring_until(packet_body, bytesBody); free(packet_body); packet_body = str_tmp; buffer[0] = '\0'; strcpy(buffer, exceeded); free(exceeded); } //llamo a la funcion que maneja los mensajes recibidos if(args->fns_receipts != NULL) { i = 0; //armo argumentos en array packet_args = malloc(sizeof(char*)*n); for(j = 2; j < n+2; j++) { char * part = string_substring(packet_body, i, atoi(head[j])); packet_args[j-2] = part; i += atoi(head[j]); } //Si n=0 el split no toma el vacio despues de la coma final.. quito ultima coma if(n==0) head[1][strlen(head[1])-1] = '\0'; //Ejecuto la función solicitada, si no existe la función muestro error fn = dictionary_get(args->fns_receipts, head[1]); if(fn != NULL) fn(args->connection, packet_args); else printf("Cliente SOCK%d(%s:%d) intento ejecutar la función inexistente '%s'.\n", args->connection->socket, args->connection->ip, args->connection->port, head[1]); //libero argumentos for(i = 0; i < n; i++) free(packet_args[i]); free(packet_args); } free(packet_head); free(packet_body); for(i = 0; i < n+3; i++) free(head[i]); free(head); n = -1; seps = 0; fullHead = false; bytesBody = 0; head = NULL; } } } } } //cierro socket close(args->connection->socket); //Informo a la funcion que maneja los cierres (si existe y la estructura de conexion lo permite) if(args->connection->run_fn_connectionClosed && args->fn_connectionClosed != NULL) args->fn_connectionClosed(args->connection); //libero memoria if(isExceeded) free(exceeded); if(n != -1) { free(packet_head); free(packet_body); } free(args); }
string_t * string_fromcharstar(const char *in) { return string_new(in, strlen(in)); }
int main(int argc, char ** argv) { //set up logging //g_log_set_default_handler(log_write, NULL); path_set(".", NULL); const char * prefix = path_resolve(argv[1]); if (prefix == NULL) { return EXIT_FAILURE; } string_t file = string_new("%s/%s", prefix, argv[1]); meta_t * meta = meta_parse(file.string); GHashTableIter itr; List * next; block_t * block; LOG(LOG_INFO, "Module: %s", file.string); LOG(LOG_INFO, "=================================="); LOG(LOG_INFO, "Author:\t %s", meta->author); LOG(LOG_INFO, "Version:\t %s", meta->version); LOG(LOG_INFO, "Pre-Activater:\t %s", meta->preactivate); LOG(LOG_INFO, "Post-Activator: %s", meta->postactivate); LOG(LOG_INFO, "Initializer:\t %s", meta->initialize); LOG(LOG_INFO, "Description:\t %s\n", meta->description); if (list_length(meta->dependencies) > 0) { LOG(LOG_INFO, "Dependencies"); LOG(LOG_INFO, "=================================="); next = meta->dependencies; while (next != NULL) { LOG(LOG_INFO, "%s", (gchar *)next->data); next = next->next; } } if (list_length(meta->cfgentries) > 0) { LOG(LOG_INFO, " "); LOG(LOG_INFO, "Configuration Params"); LOG(LOG_INFO, "=================================="); next = meta->cfgentries; while (next != NULL) { cfgentry_t * cfg = next->data; if (cfg->desc == NULL) LOG(LOG_INFO, "(%c) %s", cfg->type, cfg->name); else LOG(LOG_INFO, "(%c) %s - %s", cfg->type, cfg->name, cfg->desc); next = next->next; } } if (list_length(meta->calentries) > 0) { LOG(LOG_INFO, " "); LOG(LOG_INFO, "Calibration Params"); LOG(LOG_INFO, "=================================="); if (meta->calupdate != NULL) LOG(LOG_INFO, "Update: %s", meta->calupdate); next = meta->calentries; while (next != NULL) { calentry_t * cal = next->data; if (cal->desc == NULL) LOG(LOG_INFO, "(%s)\t%s", cal->sig, cal->name); else LOG(LOG_INFO, "(%s)\t%s - %s", cal->sig, cal->name, cal->desc); next = next->next; } } if (list_length(meta->syscalls) > 0) { LOG(LOG_INFO, " "); LOG(LOG_INFO, "Syscalls"); LOG(LOG_INFO, "=================================="); next = meta->syscalls; while (next != NULL) { syscall_t * syscall = next->data; if (syscall->desc == NULL) LOG(LOG_INFO, "%s(%s)", syscall->name, syscall->sig); else LOG(LOG_INFO, "%s(%s) - %s", syscall->name, syscall->sig, syscall->desc); next = next->next; } } if (g_hash_table_size(meta->blocks) > 0) { LOG(LOG_INFO, " "); LOG(LOG_INFO, "Blocks"); LOG(LOG_INFO, "=================================="); g_hash_table_iter_init(&itr, meta->blocks); while (g_hash_table_iter_next(&itr, NULL, (gpointer *)&block)) { if (block->desc == NULL) LOG(LOG_INFO, "%s", block->name); else LOG(LOG_INFO, "%s - %s", block->name, block->desc); if (block->new_name != NULL) LOG(LOG_INFO, " Constructor: %s(%s)", block->new_name, block->new_sig); if (block->ondestroy_name != NULL) LOG(LOG_INFO, " Destructor: %s()", block->ondestroy_name); LOG(LOG_INFO, " Update: %s", block->onupdate_name); next = block->inputs; while (next != NULL) { bio_t * in = next->data; if (in->desc == NULL) LOG(LOG_INFO, " -> input (%c) %s", in->sig, in->name); else LOG(LOG_INFO, " -> input (%c) %s - %s", in->sig, in->name, in->desc); next = next->next; } next = block->outputs; while (next != NULL) { bio_t * out = next->data; if (out->desc == NULL) LOG(LOG_INFO, " <- output (%c) %s", out->sig, out->name); else LOG(LOG_INFO, " <- output (%c) %s - %s", out->sig, out->name, out->desc); next = next->next; } } } LOG(LOG_INFO, " "); //empty line return 0; }
void exec_cmd ( char * command, void (* func)( void * closure, int status, timing_info *, char * invoked_command, char * command_output ), void * closure, LIST * shell, char * action, char * target ) { int slot; int raw_cmd = 0 ; char * argv_static[ MAXARGC + 1 ]; /* +1 for NULL */ char * * argv = argv_static; char * p; char * command_orig = command; /* Check to see if we need to hack around the line-length limitation. Look * for a JAMSHELL setting of "%", indicating that the command should be * invoked directly. */ if ( shell && !strcmp( shell->string, "%" ) && !list_next( shell ) ) { raw_cmd = 1; shell = 0; } /* Find a slot in the running commands table for this one. */ for ( slot = 0; slot < MAXJOBS; ++slot ) if ( !cmdtab[ slot ].pi.hProcess ) break; if ( slot == MAXJOBS ) { printf( "no slots for child!\n" ); exit( EXITBAD ); } /* Compute the name of a temp batch file, for possible use. */ if ( !cmdtab[ slot ].tempfile_bat ) { char const * tempdir = path_tmpdir(); DWORD procID = GetCurrentProcessId(); /* SVA - allocate 64 bytes extra just to be safe. */ cmdtab[ slot ].tempfile_bat = BJAM_MALLOC_ATOMIC( strlen( tempdir ) + 64 ); sprintf( cmdtab[ slot ].tempfile_bat, "%s\\jam%d-%02d.bat", tempdir, procID, slot ); } /* Trim leading, -ending- white space */ while ( *( command + 1 ) && isspace( *command ) ) ++command; /* Write to .BAT file unless the line would be too long and it meets the * other spawnability criteria. */ if ( raw_cmd && ( can_spawn( command ) >= MAXLINE ) ) { if ( DEBUG_EXECCMD ) printf("Executing raw command directly\n"); } else { FILE * f = 0; int tries = 0; raw_cmd = 0; /* Write command to bat file. For some reason this open can fail * intermitently. But doing some retries works. Most likely this is due * to a previously existing file of the same name that happens to be * opened by an active virus scanner. Pointed out and fixed by Bronek * Kozicki. */ for ( ; !f && ( tries < 4 ); ++tries ) { f = fopen( cmdtab[ slot ].tempfile_bat, "w" ); if ( !f && ( tries < 4 ) ) Sleep( 250 ); } if ( !f ) { printf( "failed to write command file!\n" ); exit( EXITBAD ); } fputs( command, f ); fclose( f ); command = cmdtab[ slot ].tempfile_bat; if ( DEBUG_EXECCMD ) { if ( shell ) printf( "using user-specified shell: %s", shell->string ); else printf( "Executing through .bat file\n" ); } } /* Formulate argv; If shell was defined, be prepared for % and ! subs. * Otherwise, use stock cmd.exe. */ if ( shell ) { int i; char jobno[ 4 ]; int gotpercent = 0; sprintf( jobno, "%d", slot + 1 ); for ( i = 0; shell && ( i < MAXARGC ); ++i, shell = list_next( shell ) ) { switch ( shell->string[ 0 ] ) { case '%': argv[ i ] = command; ++gotpercent; break; case '!': argv[ i ] = jobno; break; default : argv[ i ] = shell->string; } if ( DEBUG_EXECCMD ) printf( "argv[%d] = '%s'\n", i, argv[ i ] ); } if ( !gotpercent ) argv[ i++ ] = command; argv[ i ] = 0; } else if ( raw_cmd ) { argv = string_to_args( command ); } else { argv[ 0 ] = "cmd.exe"; argv[ 1 ] = "/Q/C"; /* anything more is non-portable */ argv[ 2 ] = command; argv[ 3 ] = 0; } /* Catch interrupts whenever commands are running. */ if ( !cmdsrunning++ ) istat = signal( SIGINT, onintr ); /* Start the command. */ { SECURITY_ATTRIBUTES sa = { sizeof( SECURITY_ATTRIBUTES ), 0, 0 }; SECURITY_DESCRIPTOR sd; STARTUPINFO si = { sizeof( STARTUPINFO ), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; string cmd; /* Init the security data. */ InitializeSecurityDescriptor( &sd, SECURITY_DESCRIPTOR_REVISION ); SetSecurityDescriptorDacl( &sd, TRUE, NULL, FALSE ); sa.lpSecurityDescriptor = &sd; sa.bInheritHandle = TRUE; /* Create the stdout, which is also the merged out + err, pipe. */ if ( !CreatePipe( &cmdtab[ slot ].pipe_out[ 0 ], &cmdtab[ slot ].pipe_out[ 1 ], &sa, 0 ) ) { perror( "CreatePipe" ); exit( EXITBAD ); } /* Create the stdout, which is also the merged out+err, pipe. */ if ( globs.pipe_action == 2 ) { if ( !CreatePipe( &cmdtab[ slot ].pipe_err[ 0 ], &cmdtab[ slot ].pipe_err[ 1 ], &sa, 0 ) ) { perror( "CreatePipe" ); exit( EXITBAD ); } } /* Set handle inheritance off for the pipe ends the parent reads from. */ SetHandleInformation( cmdtab[ slot ].pipe_out[ 0 ], HANDLE_FLAG_INHERIT, 0 ); if ( globs.pipe_action == 2 ) SetHandleInformation( cmdtab[ slot ].pipe_err[ 0 ], HANDLE_FLAG_INHERIT, 0 ); /* Hide the child window, if any. */ si.dwFlags |= STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; /* Set the child outputs to the pipes. */ si.dwFlags |= STARTF_USESTDHANDLES; si.hStdOutput = cmdtab[ slot ].pipe_out[ 1 ]; if ( globs.pipe_action == 2 ) { /* Pipe stderr to the action error output. */ si.hStdError = cmdtab[ slot ].pipe_err[ 1 ]; } else if ( globs.pipe_action == 1 ) { /* Pipe stderr to the console error output. */ si.hStdError = GetStdHandle( STD_ERROR_HANDLE ); } else { /* Pipe stderr to the action merged output. */ si.hStdError = cmdtab[ slot ].pipe_out[ 1 ]; } /* Let the child inherit stdin, as some commands assume it's available. */ si.hStdInput = GetStdHandle(STD_INPUT_HANDLE); /* Save the operation for exec_wait() to find. */ cmdtab[ slot ].func = func; cmdtab[ slot ].closure = closure; if ( action && target ) { string_copy( &cmdtab[ slot ].action, action ); string_copy( &cmdtab[ slot ].target, target ); } else { string_free( &cmdtab[ slot ].action ); string_new ( &cmdtab[ slot ].action ); string_free( &cmdtab[ slot ].target ); string_new ( &cmdtab[ slot ].target ); } string_copy( &cmdtab[ slot ].command, command_orig ); /* Put together the command we run. */ { char * * argp = argv; string_new( &cmd ); string_copy( &cmd, *(argp++) ); while ( *argp ) { string_push_back( &cmd, ' ' ); string_append( &cmd, *(argp++) ); } } /* Create output buffers. */ string_new( &cmdtab[ slot ].buffer_out ); string_new( &cmdtab[ slot ].buffer_err ); /* Run the command by creating a sub-process for it. */ if ( ! CreateProcess( NULL , /* application name */ cmd.value , /* command line */ NULL , /* process attributes */ NULL , /* thread attributes */ TRUE , /* inherit handles */ CREATE_NEW_PROCESS_GROUP, /* create flags */ NULL , /* env vars, null inherits env */ NULL , /* current dir, null is our */ /* current dir */ &si , /* startup info */ &cmdtab[ slot ].pi /* child process info, if created */ ) ) { perror( "CreateProcess" ); exit( EXITBAD ); } /* Clean up temporary stuff. */ string_free( &cmd ); } /* Wait until we are under the limit of concurrent commands. Do not trust * globs.jobs alone. */ while ( ( cmdsrunning >= MAXJOBS ) || ( cmdsrunning >= globs.jobs ) ) if ( !exec_wait() ) break; if ( argv != argv_static ) free_argv( argv ); }
LIST * var_expand( LIST *l, char *in, char *end, LOL *lol, int cancopyin ) { char out_buf[ MAXSYM ]; string buf[1]; string out1[1]; /* Temporary buffer */ size_t prefix_length; char *out; char *inp = in; char *ov; /* for temp copy of variable in outbuf */ int depth; if( DEBUG_VAREXP ) printf( "expand '%.*s'\n", end - in, in ); /* This gets alot of cases: $(<) and $(>) */ if( in[0] == '$' && in[1] == '(' && in[3] == ')' && !in[4] ) { switch( in[2] ) { case '1': case '<': return list_copy( l, lol_get( lol, 0 ) ); case '2': case '>': return list_copy( l, lol_get( lol, 1 ) ); } } /* Just try simple copy of in to out. */ while( in < end ) if( *in++ == '$' && *in == '(' ) goto expand; /* No variables expanded - just add copy of input string to list. */ /* Cancopyin is an optimization: if the input was already a list */ /* item, we can use the copystr() to put it on the new list. */ /* Otherwise, we use the slower newstr(). */ if( cancopyin ) { return list_new( l, copystr( inp ) ); } else { LIST* r; string_new( buf ); string_append_range( buf, inp, end ); r = list_new( l, newstr( buf->value) ); string_free( buf ); return r; } expand: string_new( buf ); string_append_range( buf, inp, in - 1); /* copy the part before '$'. */ /* * Input so far (ignore blanks): * * stuff-in-outbuf $(variable) remainder * ^ ^ * in end * Output so far: * * stuff-in-outbuf $ * ^ ^ * out_buf out * * * We just copied the $ of $(...), so back up one on the output. * We now find the matching close paren, copying the variable and * modifiers between the $( and ) temporarily into out_buf, so that * we can replace :'s with MAGIC_COLON. This is necessary to avoid * being confused by modifier values that are variables containing * :'s. Ugly. */ depth = 1; inp = ++in; /* skip over the '(' */ while( in < end && depth ) { switch( *in++ ) { case '(': depth++; break; case ')': depth--; break; } } /* * Input so far (ignore blanks): * * stuff-in-outbuf $(variable) remainder * ^ ^ ^ * inp in end */ prefix_length = buf->size; string_append_range( buf, inp, in - 1 ); out = buf->value + prefix_length; for ( ov = out; ov < buf->value + buf->size; ++ov ) { switch( *ov ) { case ':': *ov = MAGIC_COLON; break; case '[': *ov = MAGIC_LEFT; break; case ']': *ov = MAGIC_RIGHT; break; } } /* * Input so far (ignore blanks): * * stuff-in-outbuf $(variable) remainder * ^ ^ * in end * Output so far: * * stuff-in-outbuf variable * ^ ^ ^ * out_buf out ov * * Later we will overwrite 'variable' in out_buf, but we'll be * done with it by then. 'variable' may be a multi-element list, * so may each value for '$(variable element)', and so may 'remainder'. * Thus we produce a product of three lists. */ { LIST *variables = 0; LIST *remainder = 0; LIST *vars; /* Recursively expand variable name & rest of input */ if( out < ov ) variables = var_expand( L0, out, ov, lol, 0 ); if( in < end ) remainder = var_expand( L0, in, end, lol, 0 ); /* Now produce the result chain */ /* For each variable name */ for( vars = variables; vars; vars = list_next( vars ) ) { LIST *value, *evalue = 0; char *colon; char *bracket; string variable[1]; char *varname; int sub1 = 0, sub2 = -1; VAR_EDITS edits; /* Look for a : modifier in the variable name */ /* Must copy into varname so we can modify it */ string_copy( variable, vars->string ); varname = variable->value; if( colon = strchr( varname, MAGIC_COLON ) ) { string_truncate( variable, colon - varname ); var_edit_parse( colon + 1, &edits ); } /* Look for [x-y] subscripting */ /* sub1 and sub2 are x and y. */ if ( bracket = strchr( varname, MAGIC_LEFT ) ) { /* ** Make all syntax errors in [] subscripting ** result in the same behavior: silenty return an empty ** expansion (by setting sub2 = 0). Brute force parsing; ** May get moved into yacc someday. */ char *s = bracket + 1; string_truncate( variable, bracket - varname ); do /* so we can use "break" */ { /* Allow negative indexes. */ if (! isdigit( *s ) && ! ( *s == '-') ) { sub2 = 0; break; } sub1 = atoi(s); /* Skip over the first symbol, which is either a digit or dash. */ s++; while ( isdigit( *s ) ) s++; if ( *s == MAGIC_RIGHT ) { sub2 = sub1; break; } if ( *s != '-') { sub2 = 0; break; } s++; if ( *s == MAGIC_RIGHT ) { sub2 = -1; break; } if (! isdigit( *s ) && ! ( *s == '-') ) { sub2 = 0; break; } /* First, compute the index of the last element. */ sub2 = atoi(s); s++; while ( isdigit( *s ) ) s++; if ( *s != MAGIC_RIGHT) sub2 = 0; } while (0); /* ** Anything but the end of the string, or the colon ** introducing a modifier is a syntax error. */ s++; if (*s && *s != MAGIC_COLON) sub2 = 0; *bracket = '\0'; } /* Get variable value, specially handling $(<), $(>), $(n) */ if( varname[0] == '<' && !varname[1] ) value = lol_get( lol, 0 ); else if( varname[0] == '>' && !varname[1] ) value = lol_get( lol, 1 ); else if( varname[0] >= '1' && varname[0] <= '9' && !varname[1] ) value = lol_get( lol, varname[0] - '1' ); else value = var_get( varname ); /* Handle negitive indexes: part two. */ { int length = list_length( value ); if (sub1 < 0) sub1 = length + sub1; else sub1 -= 1; if (sub2 < 0) sub2 = length + 1 + sub2 - sub1; else sub2 -= sub1; /* ** The "sub2 < 0" test handles the semantic error ** of sub2 < sub1. */ if ( sub2 < 0 ) sub2 = 0; } /* The fast path: $(x) - just copy the variable value. */ /* This is only an optimization */ if( out == out_buf && !bracket && !colon && in == end ) { string_free( variable ); l = list_copy( l, value ); continue; } /* Handle start subscript */ while( sub1 > 0 && value ) --sub1, value = list_next( value ); /* Empty w/ :E=default? */ if( !value && colon && edits.empty.ptr ) evalue = value = list_new( L0, newstr( edits.empty.ptr ) ); /* For each variable value */ string_new( out1 ); for( ; value; value = list_next( value ) ) { LIST *rem; size_t postfix_start; /* Handle end subscript (length actually) */ if( sub2 >= 0 && --sub2 < 0 ) break; string_truncate( buf, prefix_length ); /* Apply : mods, if present */ if( colon && edits.filemods ) var_edit_file( value->string, out1, &edits ); else string_append( out1, value->string ); if( colon && ( edits.upshift || edits.downshift || edits.to_slashes || edits.to_windows ) ) var_edit_shift( out1, &edits ); /* Handle :J=joinval */ /* If we have more values for this var, just */ /* keep appending them (with the join value) */ /* rather than creating separate LIST elements. */ if( colon && edits.join.ptr && ( list_next( value ) || list_next( vars ) ) ) { string_append( out1, edits.join.ptr ); continue; } string_append( buf, out1->value ); string_free( out1 ); string_new( out1 ); /* If no remainder, append result to output chain. */ if( in == end ) { l = list_new( l, newstr( buf->value ) ); continue; } /* For each remainder, append the complete string */ /* to the output chain. */ /* Remember the end of the variable expansion so */ /* we can just tack on each instance of 'remainder' */ postfix_start = buf->size; for( rem = remainder; rem; rem = list_next( rem ) ) { string_truncate( buf, postfix_start ); string_append( buf, rem->string ); l = list_new( l, newstr( buf->value ) ); } } string_free( out1 ); /* Toss used empty */ if( evalue ) list_free( evalue ); string_free( variable ); } /* variables & remainder were gifts from var_expand */ /* and must be freed */ if( variables ) list_free( variables ); if( remainder) list_free( remainder ); if( DEBUG_VAREXP ) { printf( "expanded to " ); list_print( l ); printf( "\n" ); } string_free( buf ); return l; } }
char * search( char *target, time_t *time, char **another_target, int file ) { PATHNAME f[1]; LIST *varlist; string buf[1]; int found = 0; /* Will be set to 1 if target location is specified via LOCATE. */ int explicitly_located = 0; char *boundname = 0; if( another_target ) *another_target = 0; if (! explicit_bindings ) explicit_bindings = hashinit( sizeof(BINDING), "explicitly specified locations"); string_new( buf ); /* Parse the filename */ path_parse( target, f ); f->f_grist.ptr = 0; f->f_grist.len = 0; if( varlist = var_get( "LOCATE" ) ) { f->f_root.ptr = varlist->string; f->f_root.len = strlen( varlist->string ); path_build( f, buf, 1 ); if( DEBUG_SEARCH ) printf( "locate %s: %s\n", target, buf->value ); explicitly_located = 1; timestamp( buf->value, time ); found = 1; } else if( varlist = var_get( "SEARCH" ) ) { while( varlist ) { BINDING b, *ba = &b; file_info_t *ff; f->f_root.ptr = varlist->string; f->f_root.len = strlen( varlist->string ); string_truncate( buf, 0 ); path_build( f, buf, 1 ); if( DEBUG_SEARCH ) printf( "search %s: %s\n", target, buf->value ); ff = file_query(buf->value); timestamp( buf->value, time ); b.binding = buf->value; if( hashcheck( explicit_bindings, (HASHDATA**)&ba ) ) { if( DEBUG_SEARCH ) printf(" search %s: found explicitly located target %s\n", target, ba->target); if( another_target ) *another_target = ba->target; found = 1; break; } else if( ff && ff->time ) { if (!file || ff->is_file) { found = 1; break; } } varlist = list_next( varlist ); } } if (!found) { /* Look for the obvious */ /* This is a questionable move. Should we look in the */ /* obvious place if SEARCH is set? */ f->f_root.ptr = 0; f->f_root.len = 0; string_truncate( buf, 0 ); path_build( f, buf, 1 ); if( DEBUG_SEARCH ) printf( "search %s: %s\n", target, buf->value ); timestamp( buf->value, time ); } boundname = newstr( buf->value ); string_free( buf ); if (explicitly_located) { BINDING b, *ba = &b; b.binding = boundname; b.target = target; /* CONSIDER: we probably should issue a warning is another file is explicitly bound to the same location. This might break compatibility, though. */ hashenter(explicit_bindings, (HASHDATA**)&ba); } /* prepare a call to BINDRULE if the variable is set */ call_bind_rule( target, boundname ); return boundname; }
static int tunet_logon_recv_welcome() { BYTE tmpbuf[1024 * 8]; CHAR tmp[1024]; BYTE btag; UINT32 unknowntag; UINT32 datalen; BYTE *p; int len; const CHAR *WELCOME = "WELCOME TO TUNET"; //int msglen = 0; STRING *str = NULL; BOOL sr, sw, se; if(!main_socket) return OK; os_socket_tcp_status(main_socket, &sr, &sw, &se); if(tunet_state != TUNET_STATE_RECV_WELCOME) return OK; if(se) { logs_append(g_logs, "TUNET_NETWORK_ERROR", "RECV_WELCOME", NULL, 0); return ERR; } if(!sr) return OK; len = os_socket_tcp_recv(main_socket, tmpbuf, sizeof(tmpbuf)); if(len == -1) { logs_append(g_logs, "TUNET_NETWORK_ERROR", "RECV_WELCOME", NULL, 0); return ERR; } if(len > 0) { main_socket_buffer = buffer_append(main_socket_buffer, tmpbuf, len); logs_append(g_logs, "TUNET_LOGON_RECV", "WELCOME", tmpbuf, len); buf2output(tmpbuf, len, tmp, 16); //dprintf("data received(recv welcome):\n%s\n", tmp); p = main_socket_buffer->data; while(buffer_fetch_BYTE(main_socket_buffer, &p, &btag)) { switch(btag) { case 0x01: if(!buffer_fetch_STRING(main_socket_buffer, &p, &str, strlen(WELCOME))) return OK; if(strncmp(str->str, WELCOME, strlen(WELCOME)) != 0) { str = string_free(str); //TODO //process such error!!!!!!!!! logs_append(g_logs, "TUNET_LOGON_WELCOME", str->str, NULL, 0); tunet_state = TUNET_STATE_ERROR; return OK; } str = string_free(str); if(!buffer_fetch_DWORD(main_socket_buffer, &p, &unknowntag)) return OK; unknowntag = htonl(unknowntag); if(!buffer_fetch_bytes(main_socket_buffer, &p, welcome_data, 8)) return OK; if(!buffer_fetch_DWORD(main_socket_buffer, &p, &datalen)) return OK; datalen = htonl(datalen); //dprintf("欢迎消息长 %d\n", datalen); if(!buffer_fetch_STRING(main_socket_buffer, &p, &str, datalen)) return OK; logs_append(g_logs, "TUNET_LOGON_WELCOME", str->str, NULL, 0); //dprintf("%s\n", str->str); str = string_free(str); main_socket_buffer = buffer_rollto(main_socket_buffer, p); p = main_socket_buffer->data; tunet_state = TUNET_STATE_REPLY_WELCOME; break; case 0x02: case 0x05: datalen = htonl(BUF_FETCH_DWORD(p)); //dprintf("出错消息长 %d\n", datalen); str = string_new(""); str = string_nappend(str, (CHAR *)p, datalen); //dprintf("%s\n", str->str); tunet_state = TUNET_STATE_ERROR; logs_append(g_logs, "TUNET_LOGON_ERROR", str->str, NULL, 0); str = string_free(str); BUF_ROLL(p, datalen); main_socket_buffer = buffer_rollto(main_socket_buffer, p); p = main_socket_buffer->data; break; } } } return OK; }
/* * This function signs the session id (known as H) as a string then * the content of sigbuf */ STRING *ssh_do_sign(SSH_SESSION *session, BUFFER *sigbuf, PRIVATE_KEY *privatekey) { CRYPTO *crypto = session->current_crypto ? session->current_crypto : session->next_crypto; unsigned char hash[SHA_DIGEST_LEN + 1] = {0}; STRING *session_str = NULL; STRING *signature = NULL; SIGNATURE *sign = NULL; SHACTX ctx = NULL; #ifdef HAVE_LIBGCRYPT gcry_sexp_t gcryhash; #endif session_str = string_new(SHA_DIGEST_LEN); if (session_str == NULL) { return NULL; } string_fill(session_str, crypto->session_id, SHA_DIGEST_LEN); ctx = sha1_init(); if (ctx == NULL) { string_free(session_str); return NULL; } sha1_update(ctx, session_str, string_len(session_str) + 4); string_free(session_str); sha1_update(ctx, buffer_get(sigbuf), buffer_get_len(sigbuf)); sha1_final(hash + 1,ctx); hash[0] = 0; #ifdef DEBUG_CRYPTO ssh_print_hexa("Hash being signed with dsa", hash + 1, SHA_DIGEST_LEN); #endif sign = malloc(sizeof(SIGNATURE)); if (sign == NULL) { return NULL; } switch(privatekey->type) { case TYPE_DSS: #ifdef HAVE_LIBGCRYPT if (gcry_sexp_build(&gcryhash, NULL, "%b", SHA_DIGEST_LEN + 1, hash) || gcry_pk_sign(&sign->dsa_sign, gcryhash, privatekey->dsa_priv)) { ssh_set_error(session, SSH_FATAL, "Signing: libcrypt error"); gcry_sexp_release(gcryhash); signature_free(sign); return NULL; } #elif defined HAVE_LIBCRYPTO sign->dsa_sign = DSA_do_sign(hash + 1, SHA_DIGEST_LEN, privatekey->dsa_priv); if (sign->dsa_sign == NULL) { ssh_set_error(session, SSH_FATAL, "Signing: openssl error"); signature_free(sign); return NULL; } #ifdef DEBUG_CRYPTO ssh_print_bignum("r", sign->dsa_sign->r); ssh_print_bignum("s", sign->dsa_sign->s); #endif #endif /* HAVE_LIBCRYPTO */ sign->rsa_sign = NULL; break; case TYPE_RSA: #ifdef HAVE_LIBGCRYPT if (gcry_sexp_build(&gcryhash, NULL, "(data(flags pkcs1)(hash sha1 %b))", SHA_DIGEST_LEN, hash + 1) || gcry_pk_sign(&sign->rsa_sign, gcryhash, privatekey->rsa_priv)) { ssh_set_error(session, SSH_FATAL, "Signing: libcrypt error"); gcry_sexp_release(gcryhash); signature_free(sign); return NULL; } #elif defined HAVE_LIBCRYPTO sign->rsa_sign = RSA_do_sign(hash + 1, SHA_DIGEST_LEN, privatekey->rsa_priv); if (sign->rsa_sign == NULL) { ssh_set_error(session, SSH_FATAL, "Signing: openssl error"); signature_free(sign); return NULL; } #endif sign->dsa_sign = NULL; break; } #ifdef HAVE_LIBGCRYPT gcry_sexp_release(gcryhash); #endif sign->type = privatekey->type; signature = signature_to_string(sign); signature_free(sign); return signature; }
void string_copy( string* s, char const* rhs ) { string_new( s ); string_append( s, rhs ); }
/** \brief Makes a PUBLIC_KEY object out of a PRIVATE_KEY object * \param prv the Private key * \returns the public key * \see publickey_to_string() */ PUBLIC_KEY *publickey_from_privatekey(PRIVATE_KEY *prv) { PUBLIC_KEY *key = NULL; #ifdef HAVE_LIBGCRYPT gcry_sexp_t sexp; const char *tmp = NULL; size_t size; STRING *p = NULL; STRING *q = NULL; STRING *g = NULL; STRING *y = NULL; STRING *e = NULL; STRING *n = NULL; #endif /* HAVE_LIBGCRYPT */ key = malloc(sizeof(PUBLIC_KEY)); if (key == NULL) { return NULL; } key->type = prv->type; switch(key->type) { case TYPE_DSS: #ifdef HAVE_LIBGCRYPT sexp = gcry_sexp_find_token(prv->dsa_priv, "p", 0); if (sexp == NULL) { goto error; } tmp = gcry_sexp_nth_data(sexp, 1, &size); p = string_new(size); if (p == NULL) { goto error; } string_fill(p,(char *) tmp, size); gcry_sexp_release(sexp); sexp = gcry_sexp_find_token(prv->dsa_priv,"q",0); if (sexp == NULL) { goto error; } tmp = gcry_sexp_nth_data(sexp,1,&size); q = string_new(size); if (q == NULL) { goto error; } string_fill(q,(char *) tmp,size); gcry_sexp_release(sexp); sexp = gcry_sexp_find_token(prv->dsa_priv, "g", 0); if (sexp == NULL) { goto error; } tmp = gcry_sexp_nth_data(sexp,1,&size); g = string_new(size); if (g == NULL) { goto error; } string_fill(g,(char *) tmp,size); gcry_sexp_release(sexp); sexp = gcry_sexp_find_token(prv->dsa_priv,"y",0); if (sexp == NULL) { goto error; } tmp = gcry_sexp_nth_data(sexp,1,&size); y = string_new(size); if (y == NULL) { goto error; } string_fill(y,(char *) tmp,size); gcry_sexp_release(sexp); gcry_sexp_build(&key->dsa_pub, NULL, "(public-key(dsa(p %b)(q %b)(g %b)(y %b)))", string_len(p), p->string, string_len(q), q->string, string_len(g), g->string, string_len(y), y->string); string_burn(p); string_free(p); string_burn(q); string_free(q); string_burn(g); string_free(g); string_burn(y); string_free(y); #elif defined HAVE_LIBCRYPTO key->dsa_pub = DSA_new(); if (key->dsa_pub == NULL) { goto error; } key->dsa_pub->p = BN_dup(prv->dsa_priv->p); key->dsa_pub->q = BN_dup(prv->dsa_priv->q); key->dsa_pub->g = BN_dup(prv->dsa_priv->g); key->dsa_pub->pub_key = BN_dup(prv->dsa_priv->pub_key); if (key->dsa_pub->p == NULL || key->dsa_pub->q == NULL || key->dsa_pub->g == NULL || key->dsa_pub->pub_key == NULL) { goto error; } #endif /* HAVE_LIBCRYPTO */ break; case TYPE_RSA: case TYPE_RSA1: #ifdef HAVE_LIBGCRYPT sexp = gcry_sexp_find_token(prv->rsa_priv, "n", 0); if (sexp == NULL) { goto error; } tmp = gcry_sexp_nth_data(sexp, 1, &size); n = string_new(size); if (n == NULL) { goto error; } string_fill(n, (char *) tmp, size); gcry_sexp_release(sexp); sexp = gcry_sexp_find_token(prv->rsa_priv, "e", 0); if (sexp == NULL) { goto error; } tmp = gcry_sexp_nth_data(sexp, 1, &size); e = string_new(size); if (e == NULL) { goto error; } string_fill(e, (char *) tmp, size); gcry_sexp_release(sexp); gcry_sexp_build(&key->rsa_pub, NULL, "(public-key(rsa(n %b)(e %b)))", string_len(n), n->string, string_len(e), e->string); if (key->rsa_pub == NULL) { goto error; } string_burn(e); string_free(e); string_burn(n); string_free(n); #elif defined HAVE_LIBCRYPTO key->rsa_pub = RSA_new(); if (key->rsa_pub == NULL) { goto error; } key->rsa_pub->e = BN_dup(prv->rsa_priv->e); key->rsa_pub->n = BN_dup(prv->rsa_priv->n); if (key->rsa_pub->e == NULL || key->rsa_pub->n == NULL) { goto error; } #endif break; } key->type_c = ssh_type_to_char(prv->type); return key; error: #ifdef HAVE_LIBGCRYPT gcry_sexp_release(sexp); string_burn(p); string_free(p); string_burn(q); string_free(q); string_burn(g); string_free(g); string_burn(y); string_free(y); string_burn(e); string_free(e); string_burn(n); string_free(n); #endif publickey_free(key); return NULL; }
tipoConfigSWAP* crearConfigSWAP(){ tipoConfigSWAP* cfg = malloc(sizeof(tipoConfigSWAP)); cfg->nombreDeSWAP = string_new(); return cfg; }