static void try_cmavo_fragment(char *lojban, char **transbuf, char* (*transfn)(char *)) { char buf[256], buf2[256]; char *pbuf; char *t, *e; char bufout[1024]; int len; bufout[0] = 0; strcpy(buf, lojban); pbuf = buf; if (*pbuf == '.') { pbuf++; } #if DIAG fprintf(stderr, "Start with %s\n", pbuf); #endif while (*pbuf) { e = pbuf; while (*e) e++; while (e > pbuf) { len = e - pbuf; #if DIAG fprintf(stderr, "Length = %d\n", len); #endif strncpy(buf2, pbuf, len); buf2[len] = 0; t = (*transfn)(buf2); if (t) { #if DIAG fprintf(stderr, "Got trans %s for %s\n", t, buf2); #endif if (bufout[0]) { strcat(bufout, " "); } strcat(bufout, t); pbuf += len; #if DIAG fprintf(stderr, "Now looking at %s\n", pbuf); #endif goto next_outer; } else { #if DIAG fprintf(stderr,"Failed to get a translation for %s\n", buf2); #endif do { e--; } while (strchr("aeiuo'", *e)); } } if (bufout[0]) { strcat(bufout, " "); } strcat(bufout, "?"); do { pbuf++; } while (*pbuf && strchr("aeiou'", *pbuf)); if (*pbuf == '.') ++pbuf; next_outer: ; } (*transbuf) = new_string(bufout); }
/** * Retrieve the message text for a give error code. * * @param code The Rexx error code * * @return The error message associated with that code. */ RexxString *SystemInterpreter::getMessageText(wholenumber_t code ) { #if defined( HAVE_NL_TYPES_H ) nl_catd catd; /* catalog descriptor from catopen() */ #endif int set_num = 1; /* message set 1 from catalog */ ERROR_MESSAGE *p; /* message table scan pointer */ int msgid; /* message number */ char DataArea[256]; /* buf to return message */ const char * message; /* loop through looking for the */ /* error code */ #if defined( HAVE_CATOPEN ) for (p = Message_table; p->code != 0; p++) { if (p->code == code) { /* found the target code? */ msgid = p->msgid; /* get msg number associated w/ error*/ /* open message catalog in NLSPATH */ if ((catd = catopen(REXXMESSAGEFILE, SECOND_PARAMETER)) == (nl_catd)CATD_ERR) { sprintf(DataArea, "%s/%s", ORX_CATDIR, REXXMESSAGEFILE); if ((catd = catopen(DataArea, SECOND_PARAMETER)) == (nl_catd)CATD_ERR) { sprintf(DataArea, "Cannot open REXX message catalog %s. Not in NLSPATH or %s.", REXXMESSAGEFILE, ORX_CATDIR); return new_string(DataArea); } } /* retrieve message from repository */ message = catgets(catd, set_num, msgid, NULL); if (!message) /* got a message ? */ { #if defined(OPSYS_LINUX) && !defined(OPSYS_SUN) sprintf(DataArea, "%s/%s", ORX_CATDIR, REXXMESSAGEFILE); if ((catd = catopen(DataArea, SECOND_PARAMETER)) == (nl_catd)CATD_ERR) { sprintf(DataArea, "Cannot open REXX message catalog %s. Not in NLSPATH or %s.", REXXMESSAGEFILE, ORX_CATDIR); return new_string(DataArea); } else { message = catgets(catd, set_num, msgid, NULL); if (!message) /* got a message ? */ { strcpy(DataArea,"Error message not found!"); } else { strcpy(DataArea, message); } } #else strcpy(DataArea,"Error message not found!"); #endif } else { strcpy(DataArea, message); } catclose(catd); /* close the catalog */ /* convert and return the message */ return new_string(DataArea); } } return OREF_NULL; /* no message retrieved */ #else sprintf(DataArea,"Cannot get description for error %d",msgid); return new_string(&DataArea); #endif }
oop QuartzWindow::get_scrap_text() { // See Pasteboard Manager Programming guide PasteboardRef clipboard; PasteboardSyncFlags syncFlags; CFDataRef textData = NULL; ItemCount itemCount; if ( PasteboardCreate(kPasteboardClipboard, &clipboard) != noErr || (PasteboardSynchronize(clipboard) & kPasteboardModified) || PasteboardGetItemCount(clipboard, &itemCount) != noErr ) return new_string("", 0); for( UInt32 itemIndex = 1; itemIndex <= itemCount; itemIndex++ ) { PasteboardItemID itemID = 0; CFArrayRef flavorTypeArray = NULL; CFIndex flavorCount = 0; if (PasteboardGetItemIdentifier(clipboard, itemIndex, &itemID) != noErr) continue; if (PasteboardCopyItemFlavors(clipboard, itemID, &flavorTypeArray) != noErr) continue; flavorCount = CFArrayGetCount(flavorTypeArray); for(CFIndex flavorIndex = 0; flavorIndex < flavorCount; flavorIndex++) { CFStringRef flavorType; CFDataRef flavorData; CFIndex flavorDataSize; char flavorText[256]; flavorType = (CFStringRef)CFArrayGetValueAtIndex( flavorTypeArray,// 6 flavorIndex ); if (UTTypeConformsTo(flavorType, kUTTypeOldMacText)) { if (PasteboardCopyItemFlavorData(clipboard, itemID, flavorType, &flavorData) != noErr) continue; flavorDataSize = CFDataGetLength(flavorData); // allocate new string. byteVectorOop r = Memory->byteVectorObj->cloneSize(flavorDataSize, CANFAIL); if (r->is_mark()) { CFRelease (flavorData); CFRelease (flavorTypeArray); return new_string("", 0); } // copy over CFDataGetBytes(flavorData, CFRangeMake(0,CFDataGetLength(flavorData)), (UInt8 *)r->bytes()); CFRelease(flavorData); CFRelease(flavorTypeArray); return r; } // else try next } CFRelease(flavorTypeArray); } }
/* * Get a service entry. Steps: * * 1. Parse entry attributes * 2. Determine service id * 3. Insert entry in table */ static void get_service_entry( int fd, pset_h sconfs, const char *name, struct service_config *defaults ) { struct service_config *scp ; const char *func = "get_service_entry" ; scp = sc_alloc( name ) ; if ( scp == NULL ) { skip_entry( fd ) ; return ; } /* Now fill in default attributes if given. */ if ( SC_SPECIFIED( defaults, A_LOG_ON_SUCCESS ) && ! SC_IS_PRESENT( scp, A_LOG_ON_SUCCESS) ) fill_attribute( A_LOG_ON_SUCCESS, scp, defaults ) ; if ( SC_SPECIFIED( defaults, A_LOG_ON_FAILURE ) && ! SC_IS_PRESENT( scp, A_LOG_ON_FAILURE ) ) fill_attribute( A_LOG_ON_FAILURE, scp, defaults ) ; if ( SC_SPECIFIED( defaults, A_ONLY_FROM ) && ! SC_IS_PRESENT( scp, A_ONLY_FROM ) ) fill_attribute( A_ONLY_FROM, scp, defaults ) ; if ( SC_SPECIFIED( defaults, A_NO_ACCESS ) && ! SC_IS_PRESENT( scp, A_NO_ACCESS ) ) fill_attribute( A_NO_ACCESS, scp, defaults ) ; if ( SC_SPECIFIED( defaults, A_PASSENV ) && ! SC_IS_PRESENT( scp, A_PASSENV ) ) fill_attribute( A_PASSENV, scp, defaults ) ; if ( SC_SPECIFIED( defaults, A_ACCESS_TIMES ) && ! SC_IS_PRESENT( scp, A_ACCESS_TIMES ) ) fill_attribute( A_ACCESS_TIMES, scp, defaults ) ; if ( SC_SPECIFIED( defaults, A_BANNER ) && ! SC_IS_PRESENT( scp, A_BANNER ) ) fill_attribute( A_BANNER, scp, defaults ) ; if ( SC_SPECIFIED( defaults, A_BANNER_SUCCESS ) && ! SC_IS_PRESENT( scp, A_BANNER_SUCCESS ) ) fill_attribute( A_BANNER_SUCCESS, scp, defaults ) ; if ( SC_SPECIFIED( defaults, A_BANNER_FAIL ) && ! SC_IS_PRESENT( scp, A_BANNER_FAIL ) ) fill_attribute( A_BANNER_FAIL, scp, defaults ) ; if ( parse_entry( SERVICE_ENTRY, fd, scp ) == FAILED ) { sc_free( scp ) ; skip_entry( fd ) ; return ; } /* * If no service id was specified, set it equal to the service name */ if ( ! SC_SPECIFIED( scp, A_ID ) ) { if ( (SC_ID(scp) = new_string( SC_NAME(scp) )) ) SC_PRESENT( scp, A_ID ) ; else { out_of_memory( func ) ; sc_free( scp ) ; return ; } } if ( ! (pset_add( sconfs, scp )) ) { out_of_memory( func ) ; sc_free( scp ) ; return ; } }
int main(int argc, char *argv[]) { int errn; string *str; int complete = -1; int i; long ans; long logintimeout = 20; char *s; char *password; char *username; if(argc < 4) { fprintf(stderr, "Usage: %s user password connecstring\n", argv[0]); exit(1); } if((mes = new_message(0)) == NULL) { fprintf(stderr, "%s: Cannot open message queue\n", argv[0]); exit(1); } /* * I believe a fork duplicates malloced stuff, I am in the poo if it does not :-) */ errn = fork(); if(errn == -1) { fprintf(stderr, "%s: Cannot fork child process\n", argv[0]); exit(1); } else if(errn) { /* * This is the parent - which behaves like clien */ /* * Initially just a status message is snt back, zero string length * * Still needs a string to put it into */ str = new_string(); if(message_receive(mes, str, &complete, MES_SERVER_TO_CLIENT) < 0) { fprintf(stderr, "%s: %s\n", argv[0], string_s(str)); message_destroy(mes); message_delete(mes); string_delete(str); exit(1); } else { printf("%d\n",message_id(mes)) ; message_delete(mes); string_delete(str); exit(0); } } /* * All parents have exited now */ /* * This is all a child */ /* * I think I need to do this here... * I do not fully understand why, it just works! * otherwise shell parent hangs! */ setsid(); if(fork()) exit(0); close(0); close(1); close(2); /* * We are in daemon mode now */ /* * open the database */ str = new_string(); for(i=3;i<argc;i++) { string_cat(str, argv[i]); if(i < argc - 1) string_cat_c(str, ' '); } username = strdup(argv[1]); password = strdup(argv[2]); wipe(argv[2]); wipe(argv[1]); ans = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &(env)); if((ans != SQL_SUCCESS) && (ans != SQL_SUCCESS_WITH_INFO)) { message_status(mes, 127, "ODBC: Cannot allocate environment handle\n", MES_SERVER_TO_CLIENT); message_delete(mes); free(username); free(password); exit(1); } ans = SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0); if ((ans != SQL_SUCCESS) && (ans != SQL_SUCCESS_WITH_INFO)) { SQLFreeHandle(SQL_HANDLE_ENV, env); message_status(mes, 127, "ODBC: Cannot set environment handle attributes\n", MES_SERVER_TO_CLIENT); message_delete(mes); exit(1); } /* 2. allocate connection handle, set timeout */ ans = SQLAllocHandle(SQL_HANDLE_DBC, env, &(hdbc)); if ((ans != SQL_SUCCESS) && (ans != SQL_SUCCESS_WITH_INFO)) { SQLFreeHandle(SQL_HANDLE_ENV, env); message_status(mes, 127, "ODBC: Cannot allocate database handle\n", MES_SERVER_TO_CLIENT); message_delete(mes); free(username); free(password); exit(1); } /* * TODO - Parameterize ODBC_TIMEOUT as environment variable */ s = getenv("ODBC_TIMEOUT"); if(s != NULL) { if(*s) { logintimeout = atol(s); } } SQLSetConnectAttr(hdbc, SQL_LOGIN_TIMEOUT, (SQLPOINTER)logintimeout, 0); /* 3. Connect to the datasource */ ans = SQLConnect(hdbc, (SQLCHAR*) string_s(str), SQL_NTS, (SQLCHAR*) username, SQL_NTS, (SQLCHAR*) password, SQL_NTS); if ((ans != SQL_SUCCESS) && (ans != SQL_SUCCESS_WITH_INFO)) { message_status(mes, 127, "ODBC: Cannot connect to database\n", MES_SERVER_TO_CLIENT); message_delete(mes); /* SQLGetDiagRec(SQL_HANDLE_DBC, V_OD_hdbc,1, V_OD_stat, &V_OD_err,V_OD_msg,100,&V_OD_mlen); printf("%s (%d)\n",V_OD_msg,V_OD_err); */ SQLFreeHandle(SQL_HANDLE_DBC, hdbc); SQLFreeHandle(SQL_HANDLE_ENV, env); free(username); free(password); exit(1); } /* * Transmit to parent that we are hunky dory */ message_status(mes, 0, "", MES_SERVER_TO_CLIENT); /* * We are open for business - Lets go */ mainloop(); /* * At the end, tidy up */ SQLDisconnect(hdbc); SQLFreeHandle(SQL_HANDLE_DBC, hdbc); SQLFreeHandle(SQL_HANDLE_ENV, env); message_destroy(mes); message_delete(mes); free(username); free(password); exit(0); }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //agenttype_systeminfo_create //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ int agenttype_systeminfo_create(agent *a, wchar_t *parameterstring) { if (0 == * parameterstring) return 2; // no param, no agent //Find the monitor type int monitor_type = SYSTEMINFO_TYPE_NONE; for (int i = 1; i < SYSTEMINFO_NUMTYPES; i++) { if (_wcsicmp(agenttype_systeminfo_types[i], parameterstring) == 0) { monitor_type = i; break; } } //If we didn't find a correct monitor type if (monitor_type == SYSTEMINFO_TYPE_NONE) { //On an error if (!plugin_suppresserrors) { wchar_t buffer[1000]; swprintf(buffer,1000, L"There was an error setting the System Information agent:\n\nType \"%s\" is not a valid type.", parameterstring); BBMessageBox(NULL, buffer, szAppName, MB_OK|MB_SYSTEMMODAL); } return 1; } //Create the details agenttype_systeminfo_details *details = new agenttype_systeminfo_details; details->monitor_type = monitor_type; //Create a unique string to assign to this (just a number from a counter) wchar_t identifierstring[64]; swprintf(identifierstring, L"%ul", agenttype_systeminfo_counter); details->internal_identifier = new_string(identifierstring); //Set the details a->agentdetails = (void *)details; //Add this to our internal tracking list ( need update value only ) if(details->monitor_type == SYSTEMINFO_TYPE_UPTIME || details->monitor_type == SYSTEMINFO_TYPE_STYLENAME){ agent *oldagent; list_add(agenttype_systeminfo_agents, details->internal_identifier, (void *) a, (void **) &oldagent); agenttype_systeminfo_updatevalue(details->monitor_type); //Start Timer if (!agenttype_systeminfo_hastimer) { SetTimer(agenttype_systeminfo_window, 0, 1000, agenttype_systeminfo_timercall); agenttype_systeminfo_hastimer = true; } } //Increment the counter agenttype_systeminfo_counter++; //No errors return 0; }
void f_add_a() { const char *str = sp->u.string; char *ret; char *p; char first; int len; int an; while( *str == ' ' ) str++; // If *str is 0, it was only spaces. Return "a ". if( *str == 0 ) { pop_stack(); copy_and_push_string( "a " ); return; } len = strlen( str ); // Don't add anything if it already begins with a or an. if( !strncasecmp( str, "a ", 2 ) || !strncasecmp( str, "an ", 3 ) ) { return; } first = *str; an = 0; // Some special cases. // If it begins with "us", check the following letter. // "a use", "a usurper", "a user", but "an usher". if( !strncasecmp( str, "us", 2 ) ) { first = str[2]; an = 1; } // "hour*" gets "an". if( !strncasecmp( str, "hour", 4 ) ) { first = 'o'; } switch( first ) { case 'a': case 'e': case 'i': case 'o': case 'u': case 'A': case 'E': case 'I': case 'O': case 'U': an = !an; break; default: break; } if( an ) { // Add an. if( len + 3 > max_string_length ) { free_string_svalue( sp ); error( "add_a() exceeded max string length.\n" ); } ret = new_string( len + 3, "f_add_a" ); memcpy( ret, "an ", 3 ); p = ret + 3; } else { // Add a. if( len + 2 > max_string_length ) { free_string_svalue( sp ); error( "add_a() exceeded max string length.\n" ); } ret = new_string( len + 2, "f_add_a" ); memcpy( ret, "a ", 2 ); p = ret + 2; } // Add the rest of the string. memcpy( p, str, len + 1 ); // + 1: get the \0. free_string_svalue( sp ); sp->type = T_STRING; sp->subtype = STRING_MALLOC; sp->u.string = ret; }
static cell_t *read_token(secd_t *secd, secd_parser_t *p) { int tok; cell_t *inp = NULL; switch (tok = p->token) { case '(': ++p->nested; inp = read_list(secd, p); if (p->token != ')') goto error_exit; return inp; case TOK_NUM: return new_number(secd, p->numtok); case TOK_CHAR: return new_char(secd, p->numtok); case TOK_SYM: return new_symbol(secd, p->symtok); case TOK_STR: inp = new_string(secd, strmem(p->strtok)); drop_cell(secd, p->strtok); return inp; case TOK_EOF: return new_symbol(secd, EOF_OBJ); case TOK_QUOTE: case TOK_QQ: case TOK_UQ: case TOK_UQSPL: { const char *formname = special_form_for(tok); assert(formname, "No special form for token=%d\n", tok); inp = sexp_read(secd, p); assert_cell(inp, "sexp_read: reading subexpression failed"); return new_cons(secd, new_symbol(secd, formname), new_cons(secd, inp, SECD_NIL)); } case '#': switch (tok = lexnext(p)) { case '(': { cell_t *tmplist = read_list(secd, p); if (p->token != ')') { free_cell(secd, tmplist); goto error_exit; } inp = list_to_vector(secd, tmplist); free_cell(secd, tmplist); return inp; } case TOK_SYM: { if (p->symtok[0] == '.') { int op = secdop_by_name(p->symtok + 1); if (op < 0) goto error_exit; return new_op(secd, op); } if (str_eq(p->symtok, "u8")) { lexnext(p); inp = read_bytevector(p); if (p->token != ')') goto error_exit; return inp; } } } errorf("Unknown suffix for #\n"); } error_exit: if (inp) free_cell(secd, inp); errorf("read_token: failed\n"); return new_error(secd, SECD_NIL, "read_token: failed on token %1$d '%1$c'", p->token); }
at * files(const char *s) { at *ans = NIL; at **where = &ans; /* UNIX code */ #ifdef UNIX DIR *dirp; struct dirent *d; dirp = opendir(s); if (dirp) { while ((d = readdir(dirp))) { int n = NAMLEN(d); at *ats = new_string_bylen(n); char *s = SADD(ats->Object); strncpy(s, d->d_name, n); s[n] = 0; *where = cons(ats,NIL); where = &(*where)->Cdr; } closedir(dirp); } #endif /* WIN32 code */ #ifdef WIN32 struct _finddata_t info; char *last; long hfind; if ((s[0]=='/' || s[0]=='\\') && (s[1]=='/' || s[1]=='\\') && !s[2]) { hfind = GetLogicalDrives(); strcpy(info.name,"A:\\"); for (info.name[0]='A'; info.name[0]<='Z'; info.name[0]++) if (hfind & (1<<(info.name[0]-'A'))) { *where = cons(new_string(info.name),NIL); where = &(*where)->Cdr; } } else if (dirp(s)) { *where = cons(new_string(".."),NIL); where = &(*where)->Cdr; } strcpy(string_buffer,s); last = string_buffer + strlen(string_buffer); if (last>string_buffer && last[-1]!='/' && last[-1]!='\\') strcpy(last,"\\*.*"); else strcpy(last,"*.*"); hfind = _findfirst(string_buffer, &info); if (hfind != -1) { do { if (strcmp(".",info.name) && strcmp("..",info.name)) { *where = cons(new_string(info.name),NIL); where = &(*where)->Cdr; } } while ( _findnext(hfind, &info) != -1 ); _findclose(hfind); } #endif /* Return */ return ans; }
static void check_and_initialize(mutable_strptr_type& str) { if(!str.get()) { str.reset(new_string()); } }
line *new_line( char *str, char lastcmd, int linenum ) { line *l = (line *)malloc( sizeof(line) ); int colon; int rparen, lparen; int i; char *contemp = NULL; // temp variable for condex string colon = findchar( str, ':' ); // get the position of the colon l->next = NULL; l->linenum = linenum; // is it a blank string? if( !strcmp(str, "") ) { l->cmd = lastcmd; l->args = NULL; l->cond = NULL; return l; } if( colon == -1 ) { // if there is no colon, it's an error err( NO_COLON, str ); } /* Notes for the 3/3/00 rewrite * There are 3 different possiblities for what will be the first character * in the line: * * 1) A letter signifing the command name (this includes 'Y' and 'N') * 2) A colon, meaning that we should use the last command for this one, too * 3) A left parentheses, like above, but with a conditional expression * */ if( colon != strlen(str)-1 ) { l->args = new_string_from( str, colon+1, strlen(str)-colon+1 ); ltrim( l->args ); } else { l->args = new_string( "" ); } /* * Here, we'll handle the second case first, because it is the easiest. * The command is the same as the last command, and everything after the * first character constitutes the arguments. */ if( str[0] == ':' ) { l->cmd = lastcmd; l->cond = NULL; return l; } /* * Now the third case. Like the second case, everything after the colon * forms the arguments. But we have to find the right parentheses in order * to create a conditional expression. The command is the same as the * previous one. */ if( str[0] == '(' ) { l->cmd = lastcmd; rparen = findchar( str, ')' ); if( rparen == -1 ) { // If there is no right parentheses, we signal an error err( NO_RPAREN, str ); } // otherwise, create a temporary string, and make a new condex // contemp = new_string_from( str, 1, rparen-1 ); contemp = new_string_from( str, 1, rparen-1 ); l->cond = new_condex( contemp ); free( contemp ); return l; } /* * Finally, the first case. This itself has four possibilities: * * 1) There is no conditional expression * 2) There is a conditional expression in parentheses * 3) There is a 'Y' as the conditional * 4) There is an 'N' as the conditional */ l->cmd = str[0]; // l->args = new_string_from( str, colon+1, strlen(str)-colon+1 ); lparen = findchar( str, '(' ); if( (lparen == -1)|| (lparen > colon) ) { // Now, we can see if there is a Y or N somehwere.. for( i=1; i<colon; i++ ) { if( toupper(str[i]) == 'Y' ) { l->cond = new_condex( "Y" ); return l; } else if( toupper(str[i]) == 'N' ) { l->cond = new_condex( "N" ); return l; } } // If we didn't find Y or N, there is no condex, so just return l->cond = NULL; return l; } // Now we have a conditional expression, so create a new condex and return rparen = findchar( str, ')' ); if( rparen == -1 ) { err( NO_RPAREN, str ); } // contemp = new_string_from( str, lparen+1, rparen-1 ); contemp = new_string_from( str, lparen+1, rparen-2 ); l->cond = new_condex( contemp ); free( contemp ); return l; }
/** * Default virtual method for handling a run() methods on * an activity dispatcher. */ void RexxStartDispatcher::run() { ProtectedSet savedObjects; // set default return values rc = 0; retcode = 0; RexxString *name = OREF_NULLSTRING; // name of the invoked program RexxString *fullname = name; // default the fulllength name to the simple name if (programName != NULL) /* have an actual name? */ { /* get string version of the name */ name = new_string(programName); } savedObjects.add(name); /* protect from garbage collect */ // get an array version of the arguments and protect RexxArray *new_arglist = new_array(argcount + 1); // + 1 to store count of named arguments = 0 savedObjects.add(new_arglist); // for compatibility reasons, if this is a command invocation and there is a leading blank // on the only argument, then remove that leading blank from the argument if (calltype == RXCOMMAND && argcount == 1 && arglist[0].strlength > 1 && arglist[0].strptr != NULL && arglist[0].strptr[0] == ' ') { new_arglist->put(new_string(arglist[0].strptr + 1, arglist[0].strlength - 1), 1); } else { /* loop through the argument list */ for (size_t i = 0; i < argcount; i++) { /* have a real argument? */ if (arglist[i].strptr != NULL) { /* add to the argument array */ new_arglist->put(new_string(arglist[i]), i + 1); } } } // Counter of named arguments. To support correctly omitted positional arguments, don't use append! // Omitted positional arguments not applicable here, but better to have the same approach everywhere. // Here, no named arguments : Zero. new_arglist->put(IntegerZero, argcount + 1); RexxString *source_calltype; switch (calltype) /* turn calltype into a string */ { case RXCOMMAND: /* command invocation */ source_calltype = OREF_COMMAND; /* this is the 'COMMAND' string */ break; case RXFUNCTION: /* function invocation */ /* 'FUNCTION' string */ source_calltype = OREF_FUNCTIONNAME; break; case RXSUBROUTINE: /* subroutine invocation */ /* 'SUBROUTINE' string */ source_calltype = OREF_SUBROUTINE; break; default: source_calltype = OREF_COMMAND; /* this is the 'COMMAND' string */ break; } RoutineClass *program = OREF_NULL; if (instore == NULL) /* no instore request? */ { /* go resolve the name */ fullname = activity->resolveProgramName(name, OREF_NULL, OREF_NULL); if (fullname == OREF_NULL) /* not found? */ { /* got an error here */ reportException(Error_Program_unreadable_notfound, name); } savedObjects.add(fullname); /* try to restore saved image */ program = RoutineClass::fromFile(fullname); } else /* have an instore program */ { /* go handle instore parms */ program = RoutineClass::processInstore(instore, name); if (program == OREF_NULL) /* couldn't get it? */ { /* got an error here */ reportException(Error_Program_unreadable_name, name); } } RexxString *initial_address = activity->getInstance()->getDefaultEnvironment(); /* actually need to run this? */ if (program != OREF_NULL) { ProtectedObject program_result; // call the program program->runProgram(activity, source_calltype, initial_address, new_arglist->data(), argcount, program_result); if (result != NULL) /* if return provided for */ { /* actually have a result to return? */ if ((RexxObject *)program_result != OREF_NULL) { /* force to a string value */ program_result = ((RexxObject *)program_result)->stringValue(); // copy this into the result RXSTRING ((RexxString *)program_result)->copyToRxstring(*result); } else /* make this an invalid string */ { MAKERXSTRING(*result, NULL, 0); } } /* If there is a return val... */ if ((RexxObject *)program_result != OREF_NULL) { wholenumber_t return_code; /* if a whole number... */ if (((RexxObject *)program_result)->numberValue(return_code) && return_code <= SHRT_MAX && return_code >= SHRT_MIN) { /* ...copy to return code. */ retcode = (short)return_code; } } } }
void f_compress_file (void) { int readb; int len; int num_arg = st_num_arg; const char* input_file; const char* output_file; const char* real_input_file; const char* real_output_file; char* tmpout; gzFile out_file; FILE* in_file; char buf[4096]; char outname[1024]; // Not a string? Error! if ((sp - num_arg + 1)->type != T_STRING) { pop_n_elems(num_arg); push_number(0); return ; } input_file = (sp - num_arg + 1)->u.string; if (num_arg == 2) { if (((sp - num_arg + 2)->type != T_STRING)) { pop_n_elems(num_arg); push_number(0); return ; } output_file = (sp - num_arg + 2)->u.string; } else { len = strlen(input_file); if (!strcmp(input_file + len - strlen(GZ_EXTENSION), GZ_EXTENSION)) { // Already compressed... pop_n_elems(num_arg); push_number(0); return ; } tmpout = new_string(strlen(input_file) + strlen(GZ_EXTENSION), "compress_file"); strcpy(tmpout, input_file); strcat(tmpout, GZ_EXTENSION); output_file = tmpout; } real_output_file = check_valid_path(output_file, current_object, "compress_file", 1); if (!real_output_file) { pop_n_elems(num_arg); push_number(0); return ; } // Copy it into our little buffer. strcpy(outname, real_output_file); // Free the old file. if (num_arg != 2) { FREE_MSTR(output_file); } output_file = outname; real_input_file = check_valid_path(input_file, current_object, "compress_file", 0); if (!real_input_file) { pop_n_elems(num_arg); push_number(0); return ; } in_file = fopen(real_input_file, "rb"); if (!in_file) { pop_n_elems(num_arg); push_number(0); return ; } out_file = gzopen(output_file, "wb"); if (!out_file) { fclose(in_file); pop_n_elems(num_arg); push_number(0); return ; } do { readb = fread(buf, 1, 4096, in_file); gzwrite(out_file, buf, readb); } while (readb == 4096); fclose(in_file); gzclose(out_file); unlink(real_input_file); pop_n_elems(num_arg); push_number(1); }
static int do_filter(lua_State *s) { if (!s || lua_gettop(s) < 2 || !lua_istable(s, -1) || !lua_islightuserdata(s, -2)) { return 0; } struct word_filter_t *flt = (struct word_filter_t *) lua_touserdata(s, -2); if (!flt) { return 0; } struct hash_tree_node_t *root = _get_node(flt, flt->root), *curr = NULL; if (!root) { // No root node return 0; } const char *content = NULL, *replacement = NULL; size_t content_len = 0, n, j, seg_len = 0; int all = 0, matched = 0, start = 0, replace = 0; unsigned char code; BSP_STRING *res = NULL; lua_getfield(s, -1, "content"); if (lua_isstring(s, -1)) { content = lua_tolstring(s, -1, &content_len); } lua_pop(s, 1); lua_getfield(s, -1, "all"); if (lua_isboolean(s, -1)) { all = lua_toboolean(s, -1); } lua_pop(s, 1); lua_getfield(s, -1, "replace"); if (lua_isboolean(s, -1)) { replace = lua_toboolean(s, -1); } lua_pop(s, 1); lua_getfield(s, -1, "replacement"); if (lua_isstring(s, -1)) { replacement = lua_tostring(s, -1); } lua_pop(s, 1); lua_newtable(s); if (content && content_len) { if (replace) { res = new_string(NULL, 0); if (!replacement || !strlen(replacement)) { replacement = DEFAULT_REPLACEMENT; } } for (n = 0; n < content_len; n ++) { if (!all && matched) { break; } curr = root; start = n; for (j = n; j <= content_len; j ++) { if (curr->value) { // Get word matched ++; lua_pushinteger(s, matched); lua_newtable(s); lua_pushstring(s, "word"); lua_pushlstring(s, content + start, j - start); lua_settable(s, -3); lua_pushstring(s, "offset"); lua_pushinteger(s, start); lua_settable(s, -3); lua_pushstring(s, "length"); lua_pushinteger(s, j - start); lua_settable(s, -3); lua_pushstring(s, "dsp_length"); lua_pushinteger(s, curr->length); lua_settable(s, -3); lua_pushstring(s, "value"); lua_pushinteger(s, curr->value); lua_settable(s, -3); lua_settable(s, -3); seg_len = j - start; if (!all) { break; } } if (j == content_len) { break; } code = (unsigned char) content[j]; if (!curr->path[code]) { // No match break; } curr = _get_node(flt, curr->path[code]); if (!curr) { break; } } if (replace) { if (seg_len > 0) { string_printf(res, "%s", replacement); seg_len --; } else { string_printf(res, "%c", (unsigned char) content[n]); } } } if (replace) { lua_pushstring(s, "replaced"); lua_pushlstring(s, STR_STR(res), STR_LEN(res)); lua_settable(s, -3); del_string(res); } } return 1; }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //agenttype_diskspacemonitor_create //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ int agenttype_diskspacemonitor_create(agent *a, char *parameterstring) { if (0 == * parameterstring) return 2; // no param, no agent //Find the monitor type int monitor_type = DISKSPACEMONITOR_TYPE_NONE; for (int i = 1; i < DISKSPACEMONITOR_NUMTYPES; i++) { if (_stricmp(agenttype_diskspacemonitor_types[i], parameterstring) == 0) { monitor_type = i; break; } } //If we didn't find a correct monitor type if (monitor_type == DISKSPACEMONITOR_TYPE_NONE) { //On an error if (!plugin_suppresserrors) { char buffer[1000]; sprintf(buffer, "There was an error setting the Disk Space Monitor agent:\n\nType \"%s\" is not a valid type.", parameterstring); BBMessageBox(NULL, buffer, szAppName, MB_OK|MB_SYSTEMMODAL); } return 1; } //Is this the first? bool first = (agenttype_diskspacemonitor_agents->first == NULL ? true : false); //Create the details agenttype_diskspacemonitor_details *details = new agenttype_diskspacemonitor_details; details->monitor_type = monitor_type; details->value=-1.0; details->previous_value = 0; details->path=NULL; strcpy(details->str_value,""); //Create a unique string to assign to this (just a number from a counter) char identifierstring[64]; sprintf(identifierstring, "%ul", agenttype_diskspacemonitor_counter); details->internal_identifier = new_string(identifierstring); //Set the details a->agentdetails = (void *)details; agenttype_diskspacemonitor_updatevalue(details); control_notify(a->controlptr,NOTIFY_NEEDUPDATE,NULL); //Add this to our internal tracking list agent *oldagent; //Unused, but we have to pass it list_add(agenttype_diskspacemonitor_agents, details->internal_identifier, (void *) a, (void **) &oldagent); //Increment the counter agenttype_diskspacemonitor_counter++; if (!agenttype_diskspacemonitor_hastimer) { SetTimer(agenttype_diskspacemonitor_window, 0, 10000, agenttype_diskspacemonitor_timercall); agenttype_diskspacemonitor_hastimer = true; } //No errors return 0; }
char *read_file (const char * file, int start, int len) { struct stat st; FILE *f; int lastchunk, chunk, ssize, fsize; char *str, *p, *p2; if (len < 0) return 0; file = check_valid_path(file, current_object, "read_file", 0); if (!file) return 0; /* * file doesn't exist, or is really a directory */ if (stat(file, &st) == -1 || (st.st_mode & S_IFDIR)) return 0; f = fopen(file, FOPEN_READ); if (f == 0) return 0; #ifndef LATTICE if (fstat(fileno(f), &st) == -1) fatal("Could not stat an open file.\n"); #endif /* lastchunk = the size of the last chunk we read * chunk = size of the next chunk we will read (always < fsize) * fsize = amount left in file */ lastchunk = chunk = ssize = fsize = st.st_size; if (fsize > READ_FILE_MAX_SIZE) lastchunk = chunk = ssize = READ_FILE_MAX_SIZE; /* Can't shortcut out if size > max even if start and len aren't specified, since we still need to check for \0, and \r's may pull the size into range */ if (start < 1) start = 1; if (len == 0) len = READ_FILE_MAX_SIZE; str = new_string(ssize, "read_file: str"); if (fsize == 0) { /* zero length file */ str[0] = 0; fclose(f); return str; } do { /* read another chunk */ if (fsize == 0 || fread(str, chunk, 1, f) != 1) goto free_str; p = str; lastchunk = chunk; fsize -= chunk; if (chunk > fsize) chunk = fsize; while (start > 1) { /* skip newlines */ p2 = memchr(p, '\n', str + lastchunk - p); if (p2) { p = p2 + 1; start--; } else break; /* get another chunk */ } } while (start > 1); /* until we've skipped enough */ p2 = str; while (1) { char c; if (p == str + lastchunk) { /* need another chunk */ if (chunk > ssize - (p2 - str)) chunk = ssize - (p2 - str); /* space remaining */ if (fsize == 0) break; /* nothing left */ if (chunk == 0 || fread(p2, chunk, 1, f) != 1) goto free_str; p = p2; lastchunk = chunk + (p2 - str); /* fudge since we didn't start at str */ fsize -= chunk; if (chunk > fsize) chunk = fsize; } c = *p++; if (c == '\0') { FREE_MSTR(str); fclose(f); error("Attempted to read '\\0' into string!\n"); } if (c != '\r' || *p != '\n') { *p2++ = c; if (c == '\n' && --len == 0) break; /* done */ } } *p2 = 0; str = extend_string(str, p2 - str); /* fix string length */ fclose(f); return str; /* Error path: unwind allocated resources */ free_str: FREE_MSTR(str); fclose(f); return 0; }
static int parse_printcap(char **names) { FILE *printcap; char str[300]; int i,j,k,len; int printers; Boolean comment; Boolean dudprinter; if ((printcap=fopen(PRINTCAP,"r"))==NULL) return 0; printers = 0; while (!feof(printcap)) { if (fgets(str, sizeof(str), printcap) == NULL) break; len = strlen(str); comment = False; /* get rid of newline */ str[--len] = '\0'; /* check for comments */ for (i=0; i<len; i++) { if (str[i] == '#') { comment = True; break; } if (str[i] != ' ' && str[i] != '\t') break; } /* skip comment */ if (comment) continue; /* skip blank line */ if (i==len) continue; /* get printer name */ for (j=i; j<len; j++) { if (str[j] == '|' || str[j] == ':' || str[j] == ' ') break; } str[j] = '\0'; /* Check for empty printer name or duplicate name */ dudprinter = True; for (k=0; k<j; k++) { if(str[k] !=' ' && str[k] != '\t') dudprinter = False; } if(printers > 0) { for (k=0; k<printers; k++) { if(strncmp(names[k],&str[i],j-i+1) == 0) dudprinter = True; } } if (dudprinter == True) continue; if (printers >= MAX_PRINTERS) { file_msg("Maximum number of printers (%d) exceeded in %s",MAX_PRINTERS,PRINTCAP); break; } if ((names[printers] = new_string(j-i)) == NULL) { file_msg("Out of memory while getting printer names"); fclose(printcap); break; } strncpy(names[printers],&str[i],j-i+1); printers++; for (j=len-1; j>0; j--) { if (str[j] == ' ' || str[j] == '\t') continue; /* found the next entry, break */ if (str[j] != '\\') break; /* this line has \ at the end, read the next line and check it */ if (fgets(str, sizeof(str), printcap) == NULL) break; /* set length to ignore newline */ len = strlen(str)-1; /* force loop to start over */ j=len; } } fclose(printcap); return printers; }
char *read_bytes (const char * file, int start, int len, int * rlen) { struct stat st; FILE *fptr; char *str; int size; if (len < 0) return 0; file = check_valid_path(file, current_object, "read_bytes", 0); if (!file) return 0; #ifdef LATTICE if (stat(file, &st) == -1) return 0; #endif fptr = fopen(file, "rb"); if (fptr == NULL) return 0; #ifndef LATTICE if (fstat(fileno(fptr), &st) == -1) fatal("Could not stat an open file.\n"); #endif size = st.st_size; if (start < 0) start = size + start; if (len == 0) len = size; if (len > MAX_BYTE_TRANSFER) { fclose(fptr); error("Transfer exceeded maximum allowed number of bytes.\n"); return 0; } if (start >= size) { fclose(fptr); return 0; } if ((start + len) > size) len = (size - start); if ((size = fseek(fptr, start, 0)) < 0) { fclose(fptr); return 0; } str = new_string(len, "read_bytes: str"); size = fread(str, 1, len, fptr); fclose(fptr); if (size <= 0) { FREE_MSTR(str); return 0; } /* * The string has to end to '\0'!!! */ str[size] = '\0'; *rlen = size; return str; }
int main (int argc, char **argv) { struct fnode *reminv; char *hostname = NULL; int port_number = 21; char *username = NULL; char *password = NULL; char *remote_root = NULL; char *listing_file = NULL; /* Download the remote tree to create an initial inventory listing. */ int do_remote_inv = 0; /* Download the remote tree and see what is out of step with the listing file. */ int do_lint = 0; /* Actually do the upload operation. */ int do_upload = 0; /* Work out what would get uploaded/removed and show to user */ int do_dummy_upload = 0; int active_ftp = 0; while (++argv, --argc) { if ((*argv)[0] == '-') { if (!strcmp(*argv, "-u")) { --argc, ++argv; username = *argv; } else if (!strcmp(*argv, "-p")) { --argc, ++argv; password = *argv; } else if (!strcmp(*argv, "-P")) { --argc, ++argv; port_number = atoi(*argv); } else if (!strcmp(*argv, "-r")) { --argc, ++argv; remote_root = *argv; } else if (!strcmp(*argv, "-l")) { --argc, ++argv; listing_file = *argv; } else if (!strcmp(*argv, "-h") || !strcmp(*argv, "--help")) { usage(); exit(0); } else if (!strcmp(*argv, "-U") || !strcmp(*argv, "--upload")) { do_upload = 1; } else if (!strcmp(*argv, "-N") || !strcmp(*argv, "--dummy")) { do_dummy_upload = 1; } else if (!strcmp(*argv, "-R") || !strcmp(*argv, "--remote-inventory")) { do_remote_inv = 1; } else if (!strcmp(*argv, "-v") || !strcmp(*argv, "--verbose")) { verbose = 1; } else if (!strcmp(*argv, "-a") || !strcmp(*argv, "--active-ftp")) { active_ftp = 1; } else { fprintf(stderr, "Unrecognized option %s\n", *argv); exit(2); } } else { hostname = *argv; } } if (!do_remote_inv && !do_lint && !do_upload && !do_dummy_upload) { fprintf(stderr, "One of the options -R, -L, -U or -N is required\n"); exit(1); } if (do_remote_inv || do_upload) { if (!password) { password = getpass("PASSWORD: "******"@@[email protected]@"; } if (do_remote_inv) { if (!hostname) { fprintf(stderr, "-R requires hostname\n"); exit(1); } if (!username) { fprintf(stderr, "-R requires username\n"); exit(1); } reminv = make_remoteinv(hostname, port_number, username, password, remote_root, active_ftp); print_inventory(reminv, listing_file, hostname, port_number, username, remote_root); } else if (do_lint) { } else if (do_upload) { upload(password, 0, listing_file, active_ftp); } else if (do_dummy_upload) { upload(password, 1, listing_file, active_ftp); } return 0; }
void CoreProcessInitCallback::func(Process* proc) { Config* config = NULL; DistributedLicenseRequester* license_requester = NULL; ServerRegistry* registry = NULL; int backlog = 0; int setegid_err = 0; int seteuid_err = 0; INT32 nUseRegistryForStats = 0; printf ("Starting %s %d.%d Core...\n", ServerVersion::ProductName(), ServerVersion::MajorVersion(), ServerVersion::MinorVersion()); proc->pc = new CoreContainer(proc); proc->pc->process_type = PTCore; proc->pc->lbound_tcp_listenRTSPResponse = NULL; proc->pc->dispatchq = dispatch_queue; proc->pc->dispatchq->init(proc); MulticastAccessControl* mcast_ctrl = new MulticastAccessControl(); /* * Must create the ErrorSinkHandler before accessing Config */ proc->pc->error_sink_handler = new ErrorSinkHandler(); progname = GetProgName(argv[0]); os_init(); registry = new ServerRegistry(proc); proc->pc->registry = registry; registry->AddComp("Client", proc); registry->AddComp("Server", proc); // Add system composite to the registry registry->AddComp("system", proc); // Add startuplog info to the registry ServerBuffer* pBuf = new ServerBuffer((UCHAR*)g_szStartupLog, strlen(g_szStartupLog)); if (g_szStartupLog) registry->AddStr("Server.StartupLogPath", pBuf, proc); config = new Config(proc, g_pszConfigFile, g_pszImportKey, registry); if (!config->valid()) { ERRMSG(proc->pc->error_handler, "Invalid configuration.\n"); terminate(1); } if (g_pszImportKey && g_pszImportKey[0]) { terminate(1); } proc->pc->client_stats_manager = new ClientStatsManager; //proc->pc->client_stats_manager->AddRef(); if (SUCCEEDED(registry->GetInt("config.ClientStats.UseRegistry", &nUseRegistryForStats, proc))) { proc->pc->client_stats_manager->SetUseRegistryForStats(nUseRegistryForStats ? TRUE : FALSE); } proc->pc->license_requester = new DistributedLicenseRequester; /* * Now that the proc->pc and the registry are established, it is safe to * initialize the IHXNetworkServicesContext */ proc->pc->network_services->Init(proc->pc->server_context, proc->pc->engine, NULL); proc->pc->net_services->Init(proc->pc->server_context); // MulticastManager needs MulticastAddressPool! proc->pc->mcst_addr_pool = new MulticastAddressPool(); proc->pc->mcst_addr_pool->AddRef(); /* * CSapManager and MulticastManager both needs * plugin hander which will be avilable in * _main CoreTransferCallback::func */ // will be Init'ed in _main CoreTransferCallback::func proc->pc->sap_mgr = new CSapManager(); proc->pc->sap_mgr->AddRef(); // addtional Init will be done in _main CoreTransferCallback::func proc->pc->multicast_mgr = new MulticastManager(proc->pc->server_context); /* */ proc->pc->alt_server_proxy_cfg_mgr = new AltServerProxyConfigHandler(proc, registry); proc->pc->alt_server_proxy_cfg_mgr->AddRef(); if (HXR_FAIL == proc->pc->alt_server_proxy_cfg_mgr->Init()) { HX_RELEASE(proc->pc->alt_server_proxy_cfg_mgr); } /* setup QoS core */ proc->pc->qos_prof_select = new QoSProfileSelector(proc); proc->pc->qos_prof_select->AddRef(); proc->pc->qos_bus_ctl = new QoSSignalBusController(); proc->pc->qos_bus_ctl->AddRef(); proc->pc->qos_sig_src = new QoSSignalSource(proc, proc->pc->qos_bus_ctl); proc->pc->qos_sig_src->AddRef(); /* setup capex profile cache */ proc->pc->capex_static_cache = new StaticProfileCache(); proc->pc->capex_static_cache->AddRef(); proc->pc->capex_profile_cache = new HTTPProfileCache(); proc->pc->capex_profile_cache->AddRef(); Config_error* error_result = 0; backlog = config->GetInt(proc, "config.ListenBacklog"); if (backlog < CONFIG_BACKLOG) backlog = CONFIG_BACKLOG; #ifdef DEBUG debug_level() = g_ulDebugFlags ? g_ulDebugFlags : config->GetInt(proc, "config.Debug"); debug_func_level() = g_ulDebugFuncFlags ? g_ulDebugFuncFlags : config->GetInt(proc, "config.DebugFunc"); #endif ((CoreContainer*)proc->pc)->m_pListenResponseList = new CHXSimpleList; HXRegistry* hxreg = new HXRegistry(registry, proc); HX_RESULT res = HXR_OK; hxreg->AddRef(); char** pHTTPablePaths = NULL; char** pHTTPpostablePaths = NULL; ::GetHTTPPaths(hxreg, (char*)"config.HTTPDeliverable", pHTTPablePaths); ::GetHTTPPaths(hxreg, (char*)"config.HTTPPostable", pHTTPpostablePaths); /* * Add key for broadcast plugins to register their connections */ hxreg->AddComp("LiveConnections"); hxreg->AddInt("LiveConnections.Index", 0); hxreg->AddInt("LiveConnections.Count", 0); proc->pc->named_lock_manager->CreateNamedLock("LiveConnectionsLock"); INT32* pEncoders = new INT32; IHXBuffer* pIHXBuf = new ServerBuffer(TRUE); HX_ASSERT(pIHXBuf); *pEncoders = 0; pIHXBuf->SetSize(sizeof(void*)); *((void**)pIHXBuf->GetBuffer()) = (void*)pEncoders; hxreg->AddBuf("EncoderConnections.Index", pIHXBuf); HX_RELEASE(pIHXBuf); /* * Add key for monitor plugins to register their connections */ hxreg->AddComp("Monitors"); hxreg->AddInt("Monitors.Count", 0); /* * Add key for splitters to register their connections */ hxreg->AddComp("Splitters"); hxreg->AddInt("Splitters.Index", 0); hxreg->AddInt("Splitters.Count", 0); mcast_ctrl->Init(proc); proc->pc->mcast_ctrl = mcast_ctrl; IHXValues* pAddrList = NULL; IHXBuffer* pAddrBuf = NULL; const char* pAddrStr = NULL; BOOL bBindToLocalHost = FALSE; TimeZoneCheckCallback* tzcb = new TimeZoneCheckCallback(proc); tzcb->SetTimeZone(); tzcb->ScheduleFirstCheckCallback(); HX_RESULT pn_res = hxreg->GetPropListByName("config.IPBindings", pAddrList); if (pn_res != HXR_OK) { pn_res = hxreg->GetPropListByName("config.IPBinding", pAddrList); } INT32 sbind_id = hxreg->AddComp("server.ipbinding"); HX_ASSERT(sbind_id); int num_props = 0; switch (pn_res) { case HXR_OK: { const char* addr_prop_name; UINT32 addr_prop_id; res = pAddrList->GetFirstPropertyULONG32(addr_prop_name, addr_prop_id); while(res == HXR_OK) { char str[64]; if (HXR_OK == hxreg->GetStrById(addr_prop_id, pAddrBuf)) { const char* strAddr = (const char*)pAddrBuf->GetBuffer(); if (!strcmp(strAddr, "*")) { //XXXJJ "*" means any interfaces(including ipv4 and ipv6) // will be handled in "default:". //if we have "*", we shouldn't have other entries in the list. HX_ASSERT(num_props == 0); break; } else if (!strcmp(strAddr, "127.0.0.1") || !strcmp(strAddr, "0.0.0.0")) { bBindToLocalHost = TRUE; } ++num_props; sprintf(str, "server.ipbinding.addr_%.2d", num_props); hxreg->AddStr(str, pAddrBuf); HX_RELEASE(pAddrBuf); } res = pAddrList->GetNextPropertyULONG32(addr_prop_name, addr_prop_id); } pAddrList->Release(); if (num_props) break; } // Three cases fall into here: no ipbinding list, empty list, or only "*" // in the list default: { ServerBuffer::FromCharArray("*", &pAddrBuf); hxreg->AddStr("server.ipbinding.addr_01", pAddrBuf); pAddrBuf->Release(); bBindToLocalHost = TRUE; break; } }; if(!g_pHeartBeatIP) { // heartbeat ip not specified if(!bBindToLocalHost) { //localhost is not in the binding list, we need to manually add it // for heartbeat connection to succeed. char str[64]; ++num_props; sprintf(str, "server.ipbinding.addr_%.2d", num_props); ServerBuffer::FromCharArray("127.0.0.1", &pAddrBuf); hxreg->AddStr(str, pAddrBuf); pAddrBuf->Release(); } } _initializeListenRespObjects(proc, config, registry, backlog); hxreg->Release(); // This used to set g_pCPUCount based on config.ProcessorCount but // setting StreamerCount is the way to do this now. *g_pCPUCount = g_bSkipCPUTest ? 1 : CPUDetect(); // // This just gives the "Linux22Compat" code a platform-neutral // name for testing/debugging on other platforms. // UINT32 ulLessParallel = config->GetInt(proc, "config.LessParallel"); if (ulLessParallel) { printf("Note: Configuration specified LessParallel mode.\n"); *g_bLimitParallelism = TRUE; } #ifdef _UNIX const char* pPIDPath; if ((pPIDPath = config->GetString(proc, "config.PidPath"))) { FILE* f = fopen(pPIDPath, "w"); if (f > 0) { #if defined PTHREADS_SUPPORTED fprintf(f, "%d\n", getpid()); #else fprintf(f, "%d\n", proc->procid(PROC_RM_CONTROLLER)); #endif fclose(f); } else { ERRMSG(proc->pc->error_handler, "Couldn't open PID File %s", pPIDPath); } } int gid = GetGIDFromConfig(proc, config); int uid = GetUIDFromConfig(proc, config); if (pPIDPath && gid >= 0 && uid >= 0) { if (chown(pPIDPath, uid, gid) < 0) perror("could not set the PIDPath's ownership\n"); } if (gid >= 0) { #ifdef _AIX if (setregid(-1, gid) < 0) #elif defined _HPUX if (setresgid(-1, gid, gid) < 0) #else if (setegid(gid) < 0) #endif { setegid_err = errno; perror("setegid() failed(1)"); *return_gid = (UINT32)-1; } else *return_gid = gid; } if (uid >= 0) { #if defined _AIX || defined _HPUX if (setreuid(-1, uid) < 0) #else if (seteuid(uid) < 0) #endif { seteuid_err = errno; perror("seteuid() failed(1)"); *return_uid = (UINT32)-1; } else { *return_uid = uid; } } fflush(0); #endif proc->pc->config = config; /* * Handle streamer_info creation and overriding of capacity defaults * from the config file. */ UINT32 ul; proc->pc->streamer_info = new StreamerInfo; if (HXR_OK == proc->pc->registry->GetInt("config.StreamerSessionCapacity", (INT32*)&ul, proc)) { proc->pc->streamer_info->SetSessionCapacity(ul); } if (HXR_OK == proc->pc->registry->GetInt("config.MaxSockCapacity", (INT32*)&ul, proc)) { SOCK_CAPACITY_VALUE = ul; } if ((HXR_OK == proc->pc->registry->GetInt("config.MaxDescCapacity", (INT32*)&ul, proc)) || (HXR_OK == proc->pc->registry->GetInt("config.MaxDescriptorCapacity", (INT32*)&ul, proc))) { DESCRIPTOR_CAPACITY_VALUE = ul; } proc->pc->conn_id_table = new CHXTSID(config->GetInt(proc, "config.Capacity")); proc->pc->resolver_info = new ResolverInfo; proc->pc->rdispatch = new ResolverDispatch(proc); proc->pc->scheduler = new ServerScheduler(proc); proc->pc->server_prefs = new ServerPreferences(proc); proc->pc->server_info = new ServerInfo(proc); proc->pc->loadinfo = new LoadInfo(proc); //XXXTDM: Where's all the AddRef() calls??? proc->pc->net_services->AddRef(); proc->pc->scheduler->AddRef(); // Tell mem routines where to find a regularly-updated timestamp in shared memory SharedMemory::SetTimePtr(&proc->pc->engine->now); #ifdef PAULM_LEAKCHECK if (g_bLeakCheck) new MemChecker(proc); #endif /* PAULM_LEAKCHECK */ proc->pc->misc_plugins = new CHXMapPtrToPtr(); proc->pc->allowance_plugins = new CHXMapPtrToPtr(); proc->pc->server_fork = new ServerFork(proc); proc->pc->global_server_control = new GlobalServerControl(proc); proc->pc->data_convert_con = new DataConvertController; #if defined _UNIX proc->pc->m_pResMUX = new ResolverMUX(RESOLVER_CAPACITY_VALUE, MAX_RESOLVERS, proc->pc->server_fork, proc->pc->async_io, proc->pc->error_handler); #endif proc->pc->HTTP_deliver_paths = new char**; if (pHTTPablePaths) { *proc->pc->HTTP_deliver_paths= pHTTPablePaths; } else { *proc->pc->HTTP_deliver_paths = NULL; } new HTTPDeliverablePrefController(proc, (char*)"config.HTTPDeliverable", proc->pc->HTTP_deliver_paths); proc->pc->HTTP_postable_paths = new char**; if (pHTTPpostablePaths) { *proc->pc->HTTP_postable_paths= pHTTPpostablePaths; } else { *proc->pc->HTTP_postable_paths = NULL; } new HTTPDeliverablePrefController(proc, (char*)"config.HTTPPostable", proc->pc->HTTP_postable_paths); proc->pc->cloaked_guid_dict = new CloakedGUIDDict(); proc->pc->broadcast_manager = new BroadcastManager(); proc->pc->load_listen_mgr = new LoadBalancedListenerManager(proc); /* * Setup the global mimetype dictionary. */ proc->pc->mime_type_dict = new Dict(); hxreg = new HXRegistry(proc->pc->registry, proc); hxreg->AddRef(); IHXValues* pTypeList; if(HXR_OK == hxreg->GetPropListByName("config.MimeTypes", pTypeList)) { HX_RESULT res; const char* mimeTypeRegname; UINT32 mime_id; res = pTypeList->GetFirstPropertyULONG32(mimeTypeRegname, mime_id); while(HXR_OK == res) { HXPropType mimetypetype = hxreg->GetTypeById(mime_id); if(mimetypetype != PT_COMPOSITE) res = HXR_FAIL; else { const char* mimeType = strrchr(mimeTypeRegname, '.'); if(!mimeType) mimeType = mimeTypeRegname; else mimeType++; IHXValues* pExtList; if(HXR_OK == hxreg->GetPropListById(mime_id, pExtList)) { const char* ext; UINT32 ext_id; res = pExtList->GetFirstPropertyULONG32(ext, ext_id); while(res == HXR_OK) { if(PT_STRING == hxreg->GetTypeById(ext_id) || PT_BUFFER == hxreg->GetTypeById(ext_id)) { IHXBuffer* extBuffer; if(HXR_OK == hxreg->GetStrById(ext_id, extBuffer)) { proc->pc->mime_type_dict->enter( (const char*)extBuffer->GetBuffer(), new_string(mimeType)); HX_RELEASE(extBuffer); } } res = pExtList->GetNextPropertyULONG32(ext, ext_id); } HX_RELEASE(pExtList); } res = pTypeList->GetNextPropertyULONG32(mimeTypeRegname, mime_id); } } HX_RELEASE(pTypeList); } HX_RELEASE(hxreg); proc->pc->rtspstats_manager = new RTSPEventsManager(); proc->pc->sdpstats_manager = new SDPAggregateStats(); proc->pc->sdpstats_manager->AddRef(); // If a default mime type doesn't yet exist, add one so that // we will always send some mime type Dict_entry* ent = proc->pc->mime_type_dict->find("*"); if(!ent) { proc->pc->mime_type_dict->enter("*", new_string("application/octet-stream")); } new MimeTypesPrefController(proc); ((CoreContainer *)proc->pc)->cdispatch = new ConnDispatch(proc); /* * AddRef() all objects handed out by ServerContext */ proc->pc->server_prefs->AddRef(); proc->pc->server_fork->AddRef(); *core_proc = proc; *controller_waiting_on_core = 0; // Signal Controller to continue while (!(*controller_ready)) microsleep(1); // Busy Wait for the Controller delete controller_ready; CoreTransferCallback* cb = new CoreTransferCallback; cb->core_proc = proc; #ifdef DEBUG cb->m_debug_level = debug_level(); cb->m_debug_func_level = debug_func_level(); #endif int* volatile core_waiting_for_refresh; cb->core_waiting_for_refresh = new int; *cb->core_waiting_for_refresh = 1; core_waiting_for_refresh = cb->core_waiting_for_refresh; #ifdef _WIN32 MaybeNotifyServiceUp(); #endif proc->pc->dispatchq->send(proc, cb, PROC_RM_CONTROLLER); /* * Wait here for the controller to get the plugins loaded. */ while (*core_waiting_for_refresh) microsleep(1); delete core_waiting_for_refresh; /* * NOTE: Both NT and mac have servers that run to completion in * os_start() */ os_start(); fflush(0); // add the global var ptr into the registry, so that the mmap managers in // each process can then access and modify the var using atomic // operations. g_pMemoryMappedDataSize is used to report the amount of // mmapped data that is read via the local file system (smplfsys). registry->AddIntRef("server.MMappedDataSize", (INT32 *)g_pMemoryMappedDataSize, proc); proc->pc->engine->mainloop(); // NEVER REACHED! #if 0 delete this; #endif PANIC(("Internal Error cp/737\n")); }
/* * Find the next service entry. * Look for a line of the form: * * <white-space> service <white-space> <service_name> * * followed by a line containing only the ENTRY_BEGIN character */ static entry_e find_next_entry( int fd, char **snamep ) { char *p ; str_h strp ; char *sname = NULL; entry_e entry_type=0; char *line = next_line( fd ) ; const char *func = "find_next_entry" ; if ( line == CHAR_NULL ) return( NO_ENTRY ) ; strp = str_parse( line, " \t", STR_RETURN_ERROR, INT_NULL ) ; if ( strp == NULL ) { parsemsg( LOG_CRIT, func, "str_parse failed" ) ; return( BAD_ENTRY ) ; } if ( ( p = str_component( strp ) ) == CHAR_NULL ) { /* * This shouldn't happen since it implies that there is a bug * in next_line */ parsemsg( LOG_WARNING, func, "empty line" ) ; str_endparse( strp ) ; return( BAD_ENTRY ) ; } /* * Look for a keyword */ if ( EQ( p, KW_SERVICE ) || EQ( p, KW_INCLUDE ) || EQ(p, KW_INCLUDEDIR)) { if ( EQ( p, KW_INCLUDE )) entry_type = INCLUDE_ENTRY; else if ( EQ( p, KW_INCLUDEDIR )) entry_type = INCLUDEDIR_ENTRY; /* * Now get the service name */ if ( ( p = str_component( strp ) ) == CHAR_NULL ) { parsemsg( LOG_ERR, func, "service name missing" ) ; str_endparse( strp ) ; return( BAD_ENTRY ) ; } sname = new_string( p ) ; if ( sname == CHAR_NULL ) { out_of_memory( func ) ; str_endparse( strp ) ; return( BAD_ENTRY ) ; } str_endparse( strp ) ; if( (entry_type == INCLUDE_ENTRY) || (entry_type == INCLUDEDIR_ENTRY)) { *snamep = sname ; return( entry_type ) ; } else entry_type = SERVICE_ENTRY ; } else if ( EQ( p, KW_DEFAULTS ) ) { str_endparse( strp ) ; entry_type = DEFAULTS_ENTRY ; } else { parsemsg( LOG_ERR, func, "missing service keyword" ) ; str_endparse( strp ) ; return( BAD_ENTRY ) ; } /* * Now look for ENTRY_BEGIN */ line = next_line( fd ) ; if ( line == NULL || ! line_has_only_1_char( line, ENTRY_BEGIN ) ) { parsemsg( LOG_ERR, func, "Service %s: missing '%c'", sname, ENTRY_BEGIN ) ; if ( entry_type == SERVICE_ENTRY ) free( sname ) ; return( BAD_ENTRY ) ; } *snamep = sname ; return( entry_type ) ; }
int cgc_program_run(program_t *prog, io_t *io) { int result = EVAL_ERROR; interp_t interp; cgc_memset(&interp, 0, sizeof(interp_t)); interp.io = io; interp.prog = prog; if (!cgc_dict_init(&interp.vars, cgc_free_var)) return 0; if ((interp.buf = cgc_malloc(BUF_SIZE)) == NULL) goto done; if (!cgc_dict_add(&interp.vars, "RS", new_string(cgc_strdup("\n")))) goto done; if (!cgc_dict_add(&interp.vars, "ORS", new_string(cgc_strdup("\n")))) goto done; if (!cgc_dict_add(&interp.vars, "FS", new_string(cgc_strdup(" ")))) goto done; if (!cgc_dict_add(&interp.vars, "OFS", new_string(cgc_strdup(" ")))) goto done; while (1) { pattern_t *p; result = EVAL_FINISHED; if (!read_record(&interp)) break; #define DO_EVAL() do { \ result = cgc_eval_statements(&interp, p->stmt); \ if (result == EVAL_NEXT) \ goto next; \ else if (result != EVAL_FINISHED) \ goto done; \ } while (0) // apply BEGIN patterns for (p = interp.prog->patterns; p != NULL; p = p->next) { if (p->pattern == PATTERN_BEGIN) DO_EVAL(); } // apply normal patterns for (p = interp.prog->patterns; p != NULL; p = p->next) { if (p->pattern == PATTERN_INVALID || p->pattern == PATTERN_BEGIN || p->pattern == PATTERN_END) continue; if (p->pattern == PATTERN_EMPTY) { DO_EVAL(); } else { if (!cgc_eval_expression(&interp, (expr_t*)p->pattern)) goto done; if (coerce_bool(&interp, &interp.result)) DO_EVAL(); } } next: // apply END patterns for (p = interp.prog->patterns; p != NULL; p = p->next) { if (p->pattern == PATTERN_END) DO_EVAL(); } free_fields(&interp); } done: free_fields(&interp); cgc_free(interp.buf); cgc_dict_free(&interp.vars); return result != EVAL_ERROR; }
/* * This is the main server bit * * It receives SQL statements and executes them, breaking at EOF */ void mainloop() { int sz; string *str = NULL; int complete = -1; int ans; SQLSMALLINT ncol; SQLHSTMT stmt; char format; str = new_string(); while(isloop) { signal(SIGINT, sighand); signal(SIGTERM, sighand); complete = -1; sz = message_receive(mes, str, &complete, MES_CLIENT_TO_SERVER); if(sz < 0) { /* * End of file */ isloop = 0; break; } else if(sz <= 1) continue; format = *(string_s(str)); ans = SQLAllocHandle(SQL_HANDLE_STMT, (SQLHANDLE) hdbc, (SQLHANDLE *)stmt); if((ans != SQL_SUCCESS) && ( ans != SQL_SUCCESS_WITH_INFO)) { message_status(mes, 127, "ODBC: Cannot allocate statement handle\n", MES_SERVER_TO_CLIENT); return; } /* WTF: +1??? */ ans = SQLPrepare(stmt, (SQLCHAR*)string_s(str) + 1, SQL_NTS); if((ans != SQL_SUCCESS) && ( ans != SQL_SUCCESS_WITH_INFO)) { message_status(mes, 127, "ODBC: Cannot execute statement\n", MES_SERVER_TO_CLIENT); SQLFreeHandle(SQL_HANDLE_STMT, stmt); return; } ans = SQLNumResultCols(stmt, &(ncol)); if(ans != SQL_SUCCESS && ans != SQL_SUCCESS_WITH_INFO) { message_status(mes, 127, "ODBC: - cannot determine SQL type\n", MES_SERVER_TO_CLIENT); SQLFreeHandle(SQL_HANDLE_STMT, stmt); return; } if(ncol) dolines(&stmt, ncol, format); SQLFreeHandle(SQL_HANDLE_STMT, stmt); string_clear(str); message_send(mes, str, -1, MES_SERVER_TO_CLIENT); } string_delete(str); }
void string_renew(String* str, const char* renew_string) { delete_string(str); str = new_string(renew_string); }
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //agenttype_systemmonitor_create //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ int agenttype_systemmonitor_create(agent *a, char *parameterstring) { if (0 == * parameterstring) return 2; // no param, no agent //Find the monitor type int monitor_type = SYSTEMMONITOR_TYPE_NONE; for (int i = 1; i < SYSTEMMONITOR_NUMTYPES; i++) { if (_stricmp(agenttype_systemmonitor_types[i], parameterstring) == 0) { monitor_type = i; break; } } //If we didn't find a correct monitor type if (monitor_type == SYSTEMMONITOR_TYPE_NONE) { //On an error if (!plugin_suppresserrors) { char buffer[1000]; sprintf(buffer, "There was an error setting the System Monitor agent:\n\nType \"%s\" is not a valid type.", parameterstring); BBMessageBox(NULL, buffer, szAppName, MB_OK|MB_SYSTEMMODAL); } return 1; } //Is this the first? bool first = (agenttype_systemmonitor_agents->first == NULL ? true : false); //Create the details agenttype_systemmonitor_details *details = new agenttype_systemmonitor_details; details->monitor_type = monitor_type; //Create a unique string to assign to this (just a number from a counter) char identifierstring[64]; sprintf(identifierstring, "%ul", agenttype_systemmonitor_counter); details->internal_identifier = new_string(identifierstring); //Set the details a->agentdetails = (void *)details; //Add this to our internal tracking list agent *oldagent; //Unused, but we have to pass it list_add(agenttype_systemmonitor_agents, details->internal_identifier, (void *) a, (void **) &oldagent); //Increment the counter agenttype_systemmonitor_counter++; //If this is the first one if (first) { SetTimer(agenttype_systemmonitor_window, 0, 1000, agenttype_systemmonitor_timercall); } //No errors return 0; }
char *read_file(const char * file, int start, int len) { struct stat st; #ifndef PACKAGE_COMPRESS FILE *f; #else gzFile f; #endif int chunk; char *str, *p, *p2; if (len < 0) return 0; file = check_valid_path(file, current_object, "read_file", 0); if (!file) return 0; /* * file doesn't exist, or is really a directory */ if (stat(file, &st) == -1 || (st.st_mode & S_IFDIR)) return 0; #ifndef PACKAGE_COMPRESS f = fopen(file, FOPEN_READ); #else f = gzopen(file, "rb"); #endif if (f == 0) return 0; if (start < 1) start = 1; if (len == 0) len = 2*READ_FILE_MAX_SIZE; str = new_string(2*READ_FILE_MAX_SIZE, "read_file: str"); if (st.st_size== 0) { /* zero length file */ str[0] = 0; #ifndef PACKAGE_COMPRESS fclose(f); #else gzclose(f); #endif str = extend_string(str, 0); /* fix string length */ return str; } do { #ifndef PACKAGE_COMPRESS chunk = fread(str, 1, 2*READ_FILE_MAX_SIZE, f); #else chunk = gzread(f, str, 2*READ_FILE_MAX_SIZE); #endif if (chunk < 1) goto free_str; p = str; while (start > 1) { /* skip newlines */ p2 = (char *)memchr(p, '\n', 2*READ_FILE_MAX_SIZE+str-p); if (p2) { p = p2 + 1; start--; } else break; } } while (start > 1); p2 = str; while (1) { char c; c = *p++; if (p-str > chunk) { if (chunk == 2*READ_FILE_MAX_SIZE) { goto free_str; //file too big } else break; //reached the end } if (p2-str > READ_FILE_MAX_SIZE) goto free_str; //file too big if (c == '\0') { FREE_MSTR(str); #ifndef PACKAGE_COMPRESS fclose(f); #else gzclose(f); #endif error("Attempted to read '\\0' into string!\n"); } if (c != '\r' || *p != '\n') { *p2++ = c; if (c == '\n' && --len == 0) break; /* done */ } } *p2 = 0; str = extend_string(str, p2 - str); /* fix string length */ #ifndef PACKAGE_COMPRESS fclose(f); #else gzclose(f); #endif return str; /* Error path: unwind allocated resources */ free_str: FREE_MSTR(str); #ifndef PACKAGE_COMPRESS fclose(f); #else gzclose(f); #endif return 0; }
void f_cwrap () { register int i, j; int width, slen, blanks; register char *istr, *ostr, *ret; if(st_num_arg >= 2) { if(st_num_arg == 3) { blanks = sp->u.number; pop_stack(); if(blanks < 0) blanks = 0; } else blanks = 4; width = sp->u.number; pop_stack(); if(width < 2) width = 64; if(width - blanks < 2) { width = 64; blanks = 4; } } else { blanks = 4; width = 64; } istr = (char *)sp->u.string; slen = SVALUE_STRLEN(sp); if(slen < blanks) blanks = 0; i = blanks; ostr = ret = new_string(slen+slen/width+blanks, "f_cwrap"); while(blanks--) *ostr++ = ' '; while(*istr) { if(*istr == '\n') { istr++; continue; } if(istr[0] == 27 && istr[1] == '[') { j=2; while(istr[j] && (isdigit(istr[j]) || istr[j]==';')) j++; if(istr[j++] == 'm') { while(j--) *ostr++ = *istr++; continue; } } i++; *ostr++ = *istr++; if(is_B51((unsigned char)*(istr-1))) { i++; *ostr++ = *istr++; } else if((unsigned char)*(istr-1) == '\t') i += 4; if(i >= width) { *ostr++ = '\n'; i = 0; } } *ostr = '\0'; ostr = string_copy(ret, "f_cwrap"); FREE_MSTR(ret); free_string_svalue(sp); put_malloced_string(ostr); }
TEST(Core_String, end_method_regression) { cv::String old_string = "012345"; cv::String new_string(old_string.begin(), old_string.end()); EXPECT_EQ(6u, new_string.size()); }
/* Hideous mangling of C code by Taffyd. */ void query_multiple_short(svalue_t * arg, const char * type, int no_dollars, int quiet, int dark, int num_arg) { char m[] = "$M$"; char s[] = "_short"; char default_function[] = "a_short"; char separator[] = ", "; char andsep[] = " and "; int mlen = strlen(m); int slen = strlen(s); int seplen = strlen( separator ); int andlen = strlen( andsep ); array_t *arr = arg->u.arr; svalue_t *sv; svalue_t *v; int size = arr->size; int i; int len; int total_len; char *str, *res; object_t *ob; char *fun; if (!size) { str = new_string(0, "f_query_multiple_short"); str[0] = '\0'; pop_n_elems(num_arg); push_malloced_string(str); return; } /* if (no_dollars && sizeof(args) && objectp(args[0]) && undefinedp(dark) && this_player() && environment(this_player())) { dark = this_player()->check_dark(environment(this_player())->query_light()); if (dark) { return "some objects you cannot make out"; } } */ if (no_dollars && arr->item->type == T_OBJECT && !dark && command_giver && command_giver->super) { call_origin = ORIGIN_EFUN; if(!apply_low("query_light", command_giver->super, 0)) push_number(0); v = apply("check_dark", command_giver, 1, ORIGIN_EFUN); if (v && v->type == T_NUMBER && v->u.number) { pop_n_elems(num_arg); copy_and_push_string("some objects you cannot make out"); return; } } /* If we don't have a type parameter, then use default_function */ /* We need to free this value with FREE_MSTR() */ if ( !type ) { len = strlen( default_function ); fun = new_string( len, "f_query_multiple_short"); fun[len] = '\0'; strncpy( fun, default_function, len ); } else { len = strlen( type ) + slen; fun = new_string( len, "f_query_multiple_short"); fun[len] = '\0'; strncpy( fun, type, len ); strncpy( fun + strlen( type ), s, slen); } /* Check to see if there are any non-objects in the array. */ for (i = 0; i < size; i++) { if ((arr->item + i)->type != T_OBJECT) { break; } } /* The array consists only of objects, and will use the $M$ expansion code. */ if (i == size && !no_dollars) { str = new_string(max_string_length, "f_query_multiple_short"); str[max_string_length]= '\0'; strncpy(str, m, mlen); total_len = mlen; for ( i = 0; i < size; i++ ) { sv = (arr->item + i); push_number(quiet); v = apply(fun, sv->u.ob, 1, ORIGIN_EFUN); if (!v || v->type != T_STRING) { continue; } if(total_len + SVALUE_STRLEN(v) > max_string_length - mlen) continue; strncpy(str + total_len, v->u.string, (len = SVALUE_STRLEN(v))); total_len += len; } strncpy(str + total_len, m, mlen); total_len += mlen; res = new_string( total_len, "f_query_multiple_short" ); res[ total_len ] = '\0'; memcpy(res, str, total_len); /* Clean up our temporary buffer. */ FREE_MSTR(str); FREE_MSTR(fun); pop_n_elems(num_arg); push_malloced_string(res); return; } /* This is a mixed array, so we don't use $M$ format. Instead, we do as much $a_short$ conversion as we can etc. */ str = new_string(max_string_length, "f_query_multiple_short"); str[max_string_length]= '\0'; total_len = 0; for ( i = 0; i < size; i++ ) { sv = (arr->item + i); switch(sv->type) { case T_STRING: len = SVALUE_STRLEN(sv); if(total_len + len < max_string_length) { strncpy(str + total_len, sv->u.string, len); total_len += len; } break; case T_OBJECT: push_number(quiet); v = apply(fun, sv->u.ob, 1, ORIGIN_EFUN); if (!v || v->type != T_STRING) { continue; } if(total_len + SVALUE_STRLEN(v) < max_string_length) { strncpy(str + total_len, v->u.string, (len = SVALUE_STRLEN(v))); total_len += len; } break; case T_ARRAY: /* Does anyone use this? */ /* args[ i ] = "$"+ type +"_short:"+ file_name( args[ i ][ 1 ] ) +"$"; */ default: /* Get the next element. */ continue; break; } if ( len && size > 1 ) { if ( i < size - 2 ) { if(total_len+seplen < max_string_length) { strncpy( str + total_len, separator, seplen ); total_len += seplen; } } else { if ( i < size - 1 ) { if(total_len+andlen < max_string_length) { strncpy( str + total_len, andsep, andlen ); total_len += andlen; } } } } } FREE_MSTR(fun); res = new_string(total_len, "f_query_multiple_short"); res[total_len] = '\0'; memcpy(res, str, total_len); FREE_MSTR(str); /* Ok, now that we have cleaned up here we have to decide what to do with it. If nodollars is 0, then we need to pass it to an object for conversion. */ if (no_dollars) { if (command_giver) { /* We need to call on this_player(). */ push_malloced_string(res); v = apply("convert_message", command_giver, 1, ORIGIN_EFUN); if (v && v->type == T_STRING) { pop_n_elems(num_arg); share_and_push_string(v->u.string); } else { pop_n_elems(num_arg); push_undefined(); } } else { /* We need to find /global/player. */ /* Does this work? Seems not to. */ ob = find_object("/global/player"); if (ob) { push_malloced_string(res); v = apply("convert_message", ob, 1, ORIGIN_EFUN); /* Return the result! */ if (v && v->type == T_STRING) { pop_n_elems(num_arg); share_and_push_string(v->u.string); } else { pop_n_elems(num_arg); push_undefined(); } } else { pop_n_elems(num_arg); push_undefined(); } } } else { pop_n_elems(num_arg); push_malloced_string(res); } } /* query_multiple_short() */
static int get_next_inet_entry( int fd, pset_h sconfs, struct service_config *defaults) { char *p; str_h strp; char *line = next_line(fd); struct service_config *scp; unsigned u, i; const char *func = "get_next_inet_entry"; char *name = NULL, *rpcvers = NULL, *rpcproto = NULL; char *group, *proto, *stype; const struct name_value *nvp; struct protoent *pep ; struct passwd *pw ; struct group *grp ; const char *dot = "."; const char *slash = "/"; pset_h args; if( line == CHAR_NULL ) return -2; strp = str_parse( line, " \t", STR_RETURN_ERROR, INT_NULL ) ; if( strp == NULL ) { parsemsg( LOG_CRIT, func, "inetd.conf - str_parse failed" ) ; return( -1 ) ; } if( (args = pset_create(10,10)) == NULL ) { out_of_memory(func); return -1; } /* Break the line into components, based on spaces */ while( (p = str_component( strp )) ) { if( pset_add(args, p) == NULL ) { parsemsg( LOG_CRIT, func, ES_NOMEM ); pset_destroy(args); return -1; } } str_endparse( strp ); /* get the service name */ name = new_string((char *)pset_pointer( args, 0 )); if( name == NULL ) { parsemsg( LOG_ERR, func, "inetd.conf - Invalid service name" ); pset_destroy(args); return -1; } /* Check to find the '/' for specifying RPC version numbers */ if( (rpcvers = strstr(name, slash)) != NULL ) { *rpcvers = '\0'; rpcvers++; } scp = sc_alloc( name ); if( scp == NULL ) { pset_destroy(args); free( name ); return -1; } /* * sc_alloc makes its own copy of name. At this point, sc_alloc worked * so we will free our copy to avoid leaks. */ free( name ); /* Replicate inetd behavior in this regard. Also makes sure the * service actually works on system where setgroups(0,NULL) doesn't * work. */ SC_GROUPS(scp) = YES; SC_SPECIFY( scp, A_GROUPS ); /* Get the socket type (stream dgram) */ stype = (char *)pset_pointer(args, 1); if( stype == NULL ) { parsemsg( LOG_ERR, func, "inetd.conf - Invalid socket type" ); pset_destroy(args); sc_free(scp); return -1; } nvp = nv_find_value( socket_types, stype ); if( nvp == NULL ) { parsemsg( LOG_ERR, func, "inetd.conf - Bad socket type: %s", p); pset_destroy(args); sc_free(scp); return -1; } SC_SOCKET_TYPE(scp) = nvp->value; /* Get the protocol type */ proto = (char *)pset_pointer(args,2); if( strstr(proto, "rpc") != NULL ) { int rpcmin, rpcmax; struct rpc_data *rdp = SC_RPCDATA( scp ) ; if( rpcvers == NULL ) { pset_destroy(args); sc_free(scp); return -1; /* uh oh */ } p = strchr(rpcvers, '-'); if( p && parse_int(rpcvers, 10, '-', &rpcmin) == 0 ) { if( parse_base10(p + 1, &rpcmax) || rpcmin > rpcmax ) { pset_destroy(args); sc_free(scp); return -1; } } else { if( parse_base10(rpcvers, &rpcmin) ) { pset_destroy(args); sc_free(scp); return -1; } rpcmax = rpcmin; } /* now have min and max rpc versions */ rdp->rd_min_version = rpcmin; rdp->rd_max_version = rpcmax; rpcproto = strstr(proto, slash); if( rpcproto == NULL ) { parsemsg( LOG_ERR, func, "inetd.conf - bad rpc version numbers" ); pset_destroy(args); sc_free(scp); return -1; } *rpcproto = '\0'; rpcproto++; proto = rpcproto; /* Set the RPC type field */ nvp = nv_find_value( service_types, "RPC" ); if ( nvp == NULL ) { parsemsg( LOG_WARNING, func, "inetd.conf - Bad foo %s", name ) ; pset_destroy(args); sc_free(scp); return -1; } M_SET(SC_TYPE(scp), nvp->value); } if ( ( pep = getprotobyname( proto ) ) == NULL ) { parsemsg( LOG_ERR, func, "inetd.conf - Protocol %s not in /etc/protocols", proto ) ; pset_destroy(args); sc_free(scp); return -1; } SC_PROTONAME(scp) = new_string( proto ) ; if ( SC_PROTONAME(scp) == NULL ) { out_of_memory( func ) ; pset_destroy(args); sc_free(scp); return -1; } SC_PROTOVAL(scp) = pep->p_proto; SC_SPECIFY(scp, A_PROTOCOL); /* Get the wait attribute */ p = (char *)pset_pointer(args, 3); if ( p == NULL ) { parsemsg( LOG_ERR, func, "inetd.conf - No value specified for wait" ); sc_free(scp); return -1; } if ( EQ( p, "wait" ) ) SC_WAIT(scp) = YES ; else if ( EQ( p, "nowait" ) ) SC_WAIT(scp) = NO ; else parsemsg( LOG_ERR, func, "inetd.conf - Bad value for wait: %s", p ) ; /* Get the user to run as */ p = (char *)pset_pointer(args, 4); if ( p == NULL ) { parsemsg( LOG_ERR, func, "inetd.conf - No value specified for user" ); sc_free(scp); return -1; } if( (group = strstr(p, dot)) ) { *group = '\0'; group++; grp = (struct group *)getgrnam( (char *)group ) ; if ( grp == NULL ) { parsemsg( LOG_ERR, func, "inetd.conf - Unknown group: %s", group ) ; pset_destroy(args); sc_free(scp); return -1; } SC_GID(scp) = ((struct group *)grp)->gr_gid; SC_SPECIFY( scp, A_GROUP ); } pw = getpwnam( p ); if ( pw == NULL ) { parsemsg( LOG_ERR, func, "inetd.conf - Unknown user: %s", p ) ; pset_destroy(args); sc_free(scp); return -1; } str_fill( pw->pw_passwd, ' ' ); SC_UID(scp) = pw->pw_uid; SC_USER_GID(scp) = pw->pw_gid; /* Get server name, or flag as internal */ p = (char *)pset_pointer(args, 5); if ( p == NULL ) { parsemsg( LOG_ERR, func, "inetd.conf - No value specified for user" ); sc_free(scp); return -1; } if( EQ( p, "internal" ) ) { nvp = nv_find_value( service_types, "INTERNAL" ); if ( nvp == NULL ) { parsemsg( LOG_WARNING, func, "inetd.conf - Bad foo %s", name ) ; pset_destroy(args); sc_free(scp); return -1; } M_SET(SC_TYPE(scp), nvp->value); if( EQ( SC_NAME(scp), "time" ) ) { if( EQ( proto, "stream" ) ) SC_ID(scp) = new_string("time-stream"); else SC_ID(scp) = new_string("time-dgram"); } if( EQ( SC_NAME(scp), "daytime" ) ) { if( EQ( proto, "stream" ) ) SC_ID(scp) = new_string("daytime-stream"); else SC_ID(scp) = new_string("daytime-dgram"); } if( EQ( SC_NAME(scp), "chargen" ) ) { if( EQ( proto, "stream" ) ) SC_ID(scp) = new_string("chargen-stream"); else SC_ID(scp) = new_string("chargen-dgram"); } if( EQ( SC_NAME(scp), "echo" ) ) { if( EQ( proto, "stream" ) ) SC_ID(scp) = new_string("echo-stream"); else SC_ID(scp) = new_string("echo-dgram"); } if( EQ( SC_NAME(scp), "discard" ) ) { parsemsg(LOG_WARNING, func, "inetd.conf - service discard not supported"); pset_destroy(args); sc_free(scp); return -1; } } else { SC_SERVER(scp) = new_string( p ); if ( SC_SERVER(scp) == NULL ) { out_of_memory( func ) ; pset_destroy(args); sc_free(scp); return -1; } SC_SPECIFY( scp, A_SERVER); /* Get argv */ SC_SERVER_ARGV(scp) = (char **)argv_alloc(pset_count(args)+1); for( u = 0; u < pset_count(args)-6 ; u++ ) { p = new_string((char *)pset_pointer(args, u+6)); if( p == NULL ) { for ( i = 1 ; i < u ; i++ ) free( SC_SERVER_ARGV(scp)[i] ); free( SC_SERVER_ARGV(scp) ); pset_destroy(args); sc_free(scp); return -1; } SC_SERVER_ARGV(scp)[u] = p; } /* Set the reuse flag, as this is the default for inetd */ nvp = nv_find_value( service_flags, "REUSE" ); if ( nvp == NULL ) { parsemsg( LOG_WARNING, func, "inetd.conf - Bad foo %s", name ) ; pset_destroy(args); sc_free(scp); return -1; } M_SET(SC_XFLAGS(scp), nvp->value); /* Set the NOLIBWRAP flag, since inetd doesn't have libwrap built in */ nvp = nv_find_value( service_flags, "NOLIBWRAP" ); if ( nvp == NULL ) { parsemsg( LOG_WARNING, func, "inetd.conf - Bad foo %s", name ) ; pset_destroy(args); sc_free(scp); return -1; } M_SET(SC_XFLAGS(scp), nvp->value); /* Set the NAMEINARGS flag, as that's the default for inetd */ nvp = nv_find_value( service_flags, "NAMEINARGS" ); if ( nvp == NULL ) { parsemsg( LOG_WARNING, func, "inetd.conf - Bad foo %s", name ) ; pset_destroy(args); sc_free(scp); return (-1); } M_SET(SC_XFLAGS(scp), nvp->value); SC_SPECIFY( scp, A_SERVER_ARGS ); if ( (SC_ID(scp) = new_string( SC_NAME(scp) )) ) SC_PRESENT( scp, A_ID ) ; else { out_of_memory( func ) ; pset_destroy(args); sc_free(scp); return -1; } } SC_SPECIFY( scp, A_PROTOCOL ); SC_SPECIFY( scp, A_USER ); SC_SPECIFY( scp, A_SOCKET_TYPE ); SC_SPECIFY( scp, A_WAIT ); if( ! pset_add(sconfs, scp) ) { out_of_memory( func ); pset_destroy(args); sc_free(scp); return -1; } pset_destroy(args); parsemsg( LOG_DEBUG, func, "added service %s", SC_NAME(scp)); return 0; }