int isDontBumpMetaName( struct swline *tmplist, char *tag) { char *tmptag; if (!tmplist) return 0; if (strcmp(tmplist->line,"*")==0) return 1; tmptag=estrdup(tag); tmptag=strtolower(tmptag); while(tmplist) { if( strcasecmp(tmptag,tmplist->line)==0 ) { efree(tmptag); return 1; } tmplist=tmplist->next; } efree(tmptag); return 0; }
int checkword(char * str, strhash &htab, ivector &wcount, ivector &tokens, unhash &unh) { strtolower(str); int userno; if (htab.count(str)) { userno = htab[str]; wcount[userno-1]++; } else { try { char * newstr = new char[strlen(str)+1]; strcpy(newstr, str); wcount.push_back(1); unh.push_back(newstr); userno = unh.size(); htab[newstr] = userno; } catch (bad_alloc) { cerr << "stringIndexer:checkstr: allocation error" << endl; throw; } } // fprintf(stderr, "token %s (%d)\n", str, userno); tokens.push_back(userno); return userno; }
/* Fonction appellée dès qu'une commande est reçus par le server */ LIBEXPORT void onCommand(char *cmd, char **parameters) { if(!strcmp(strtolower(cmd),"tux_open")) { if(parameters != NULL) { if(parameters[0] != NULL) { char **phrases = (char **)malloc(sizeof(char *)); phrases[0] = (char *)malloc(sizeof(char)*28); sprintf(phrases[0],"\"Commande reçue je m'exécute\""); phrases[1] = (char *)malloc(sizeof(char)*6); sprintf(phrases[1],"mb-fr1"); phrases[2] = (char *)malloc(sizeof(char)*2); sprintf(phrases[2],"50"); phrases[3] = (char *)malloc(sizeof(char)*3); sprintf(phrases[3],"115"); phrases[4] = (char *)malloc(sizeof(char)*1); sprintf(phrases[4],"1"); phrases[5] = (char *)malloc(sizeof(char)*1); sprintf(phrases[5],"0"); Tux_TTS(phrases,6); //Autre exemple de commande: Tux_Flippers("Up",NULL); } } } }
int gfx_parsecolor( struct color *col, char *colstr ) { char *ptr, conv[5]="0xff"; // fprintf( stderr, "col: 0x%08x, '%s'\n", col, colstr ); if( !col ) return( ERR_COLPARSEERROR ); if( !colstr ) return( ERR_COLPARSEERROR ); if( strlen( colstr )<3 ) return( ERR_COLPARSEERROR ); strtolower( colstr ); if( !strncmp( colstr, "0x", 2 ) ) ptr=colstr+2; else if( !strncmp( colstr, "#", 1 ) ) ptr=colstr+1; else if( !strncmp( colstr, "$", 1 ) ) ptr=colstr+1; else ptr=colstr; conv[2]=ptr[0]; conv[3]=ptr[1]; col->r=strtol( conv, (char **)NULL, 16 ); conv[2]=ptr[2]; conv[3]=ptr[3]; col->g=strtol( conv, (char **)NULL, 16 ); conv[2]=ptr[4]; conv[3]=ptr[5]; col->b=strtol( conv, (char **)NULL, 16 ); col->opacity=255; return( ERR_OK ); }
static struct search_list_country * search_list_country_new(struct item *item) { struct search_list_country *ret=g_new0(struct search_list_country, 1); struct attr attr; ret->common.item=ret->common.unique=*item; if (item_attr_get(item, attr_country_car, &attr)) ret->car=g_strdup(attr.u.str); if (item_attr_get(item, attr_country_iso2, &attr)) { #if HAVE_API_ANDROID ret->iso2=g_malloc(strlen(attr.u.str)+1); strtolower(ret->iso2, attr.u.str); #else ret->iso2=g_strdup(attr.u.str); #endif ret->flag=g_strdup_printf("country_%s", ret->iso2); } if (item_attr_get(item, attr_country_iso3, &attr)) ret->iso3=g_strdup(attr.u.str); if (item_attr_get(item, attr_country_name, &attr)) ret->name=g_strdup(attr.u.str); return ret; }
char * vec_basename(struct dvec *v) { char buf[BSIZE_SP], *t, *s; if (strchr(v->v_name, '.')) { if (cieq(v->v_plot->pl_typename, v->v_name)) (void) strcpy(buf, v->v_name + strlen(v->v_name) + 1); else (void) strcpy(buf, v->v_name); } else { (void) strcpy(buf, v->v_name); } strtolower(buf); for (t = buf; isspace(*t); t++) ; s = t; for (t = s; *t; t++) ; while ((t > s) && isspace(t[-1])) *--t = '\0'; return (copy(s)); }
static void getFieldNameToken(char ** const pP, char ** const fieldNameP, const char ** const errorP, uint16_t * const httpErrorCodeP) { /*---------------------------------------------------------------------------- Assuming that *pP points to the place in an HTTP header where the field name belongs, return the field name and advance *pP past that token. The field name is the lower case representation of the value of the field name token. -----------------------------------------------------------------------------*/ char * fieldName; NextToken((const char **)pP); fieldName = GetToken(pP); if (!fieldName) { xmlrpc_asprintf(errorP, "The header has no field name token"); *httpErrorCodeP = 400; /* Bad Request */ } else { if (fieldName[strlen(fieldName)-1] != ':') { /* Not a valid field name */ xmlrpc_asprintf(errorP, "The field name token '%s' " "does not end with a colon (:)", fieldName); *httpErrorCodeP = 400; /* Bad Request */ } else { fieldName[strlen(fieldName)-1] = '\0'; /* remove trailing colon */ strtolower(fieldName); *errorP = NULL; } } *fieldNameP = fieldName; }
const std::vector<Bytes>* RedisLink::recv_req(Buffer *input){ int ret = this->parse_req(input); if(ret == -1){ return NULL; } if(recv_bytes.empty()){ if(input->space() == 0){ input->nice(); if(input->space() == 0){ if(input->grow() == -1){ //log_error("fd: %d, unable to resize input buffer!", this->sock); return NULL; } //log_debug("fd: %d, resize input buffer, %s", this->sock, input->stats().c_str()); } } return &recv_bytes; } cmd = recv_bytes[0].String(); strtolower(&cmd); recv_string.clear(); this->convert_req(); // Bytes don't hold memory, so we firstly copy Bytes into string and store // in a vector of string, then create Bytes-es prointing to strings recv_bytes.clear(); for(int i=0; i<recv_string.size(); i++){ std::string *str = &recv_string[i]; recv_bytes.push_back(Bytes(str->data(), str->size())); } return &recv_bytes; }
void generate_code_shp(batch *b) { /* umlclasslist tmplist,parents,dependencies; umlassoclist associations; namelist used_classes,tmpnamelist; int tmpv; umlattrlist umla,tmpa; umloplist umlo; */ umlclasslist tmplist; umlclasslist parentlist, parentlist2; umlattrlist umla; int tmpv; char *tmpname; char outfilename[BIG_BUFFER]; FILE * outfileshp, *dummyfile; int tmpdirlgth, tmpfilelgth; if (b->outdir == NULL) { b->outdir = "."; } tmpdirlgth = strlen(b->outdir); tmplist = b->classlist; while ( tmplist != NULL ) { if ( ! ( is_present(b->classes, tmplist->key->name) ^ b->mask ) ) { tmpname = strtolower(tmplist->key->name); /* This prevents buffer overflows */ tmpfilelgth = strlen(tmpname); if (tmpfilelgth + tmpdirlgth > sizeof(*outfilename) - 2) { fprintf(stderr, "Sorry, name of file too long ...\nTry a smaller dir name\n"); exit(4); } sprintf(outfilename, "%s/createshapefiles.bat", b->outdir); dummyfile = fopen(outfilename, "r"); if ( b->clobber || ! dummyfile ) { outfileshp = fopen(outfilename, "a"); if ( outfileshp == NULL ) { fprintf(stderr, "Can't open file %s for writing\n", outfilename); exit(3); } /* This prevents buffer overflows */ tmpfilelgth = strlen(tmpname); if (tmpfilelgth + tmpdirlgth > sizeof(*outfilename) - 2) { fprintf(stderr, "Sorry, name of file too long ...\nTry a smaller dir name\n"); exit(4); } free(tmpname); tmpv = -1; if(tmplist->key->isabstract == 0) { /* create attribute table */ umla = tmplist->key->attributes; parentlist = tmplist; fprintf(outfileshp, "dbfcreate %s", tmplist->key->name); while ( umla != NULL) { if((strcmp(umla->key.name,"Shape") != 0)&& (umla->key.visibility != 1)) { if(strcmp(umla->key.type,"String") == 0) { fprintf(outfileshp, " -s %s 255", umla->key.name); } else if((strcmp(umla->key.type, "CodedValue") == 0)|| strcmp(umla->key.type, "Integer") ==0 ) { fprintf(outfileshp, " -n %s 16 0", umla->key.name); } else if(strcmp(umla->key.type, "Float") == 0) { fprintf(outfileshp, " -n %s 16 3", umla->key.name); } } umla = umla->next; if((umla == NULL)&&(parentlist != NULL)) { parentlist = parentlist->parents; if(parentlist != NULL) { umla = parentlist->key->attributes; parentlist2 = b->classlist; while((strcmp(parentlist->key->name, parentlist2->key->name) != 0)&& (parentlist2 != NULL)) parentlist2 = parentlist2->next; parentlist = parentlist2; } } } fprintf(outfileshp, "\n"); /* create shp file */ umla = tmplist->key->attributes; parentlist = tmplist; while ( umla != NULL) { if(strcmp(umla->key.name,"Shape") == 0) { if(strcmp(strtolower(umla->key.type), "polyline") == 0) { strcpy(umla->key.type, "arc"); } fprintf(outfileshp, "shpcreate %s %s\n\n", tmplist->key->name, strtolower(umla->key.type)); break; } umla = umla->next; if((umla == NULL)&&(parentlist != NULL)) { parentlist = parentlist->parents; if(parentlist != NULL) { umla = parentlist->key->attributes; parentlist2 = b->classlist; while((strcmp(parentlist->key->name, parentlist2->key->name) != 0)&& (parentlist2 != NULL)) parentlist2 = parentlist2->next; parentlist = parentlist2; } } } } } fclose(outfileshp); } tmplist = tmplist->next; } }
/* End of "Not listed" line. */ void xml_notlistedstr(FILE *outf, Outchoices *od, choice rep, unsigned long badn) { XML_TRACE(0); XML_OUT( XMLDBG "<col name=\"name\"><i18n key=\"notlisted-%s\" var=\"%lu\"/></col>", strtolower(report_name[rep]), badn ); #if 0 extern unsigned int *rep2lng, *rep2colhead; char **lngstr = od->lngstr; char *colhead = lngstr[rep2colhead[rep]]; char *colheadp = lngstr[rep2colhead[rep] + 1]; char gender = lngstr[rep2lng[rep] + 3][0]; char *notlistedstr; if (gender == 'm') notlistedstr = lngstr[notlistedm_]; else if (gender == 'f') notlistedstr = lngstr[notlistedf_]; else notlistedstr = lngstr[notlistedn_]; fprintf(outf, "[%s: ", notlistedstr); f3printf(outf, od, (double)badn, 0, od->sepchar); fprintf(outf, " %s]\n", (badn == 1)?colhead:colheadp); #endif }
static int32_t oscam_ser_parse_url(char *url, struct s_serial_client *serialdata, char *pcltype) { char *service, *usr, *dev, *baud=NULL, *dummy, *para; char cltype; cltype = pcltype?(*pcltype):cur_client()->typ; serialdata->oscam_ser_proto=P_AUTO; if( (dummy=strstr(url, "://")) ) { int32_t i; service=url; url=dummy+3; *dummy=0; for (i=1; i<=P_MAX; i++) if (!strcmp(service, proto_txt[i])) serialdata->oscam_ser_proto=i; } if (!(cltype == 'c') && (serialdata->oscam_ser_proto==P_AUTO)) return(0); switch(serialdata->oscam_ser_proto) // set the defaults { case P_GS: serialdata->oscam_ser_timeout=500; serialdata->oscam_ser_baud=B19200; break; default: serialdata->oscam_ser_timeout=50; #ifdef B115200 serialdata->oscam_ser_baud=B115200; #else serialdata->oscam_ser_baud=B9600; #endif } switch( serialdata->oscam_ser_proto ) { case P_DSR95: serialdata->dsr9500type=(cltype == 'c')?P_DSR_AUTO:P_DSR_WITHSID; break; case P_DSR95_OLD: serialdata->dsr9500type=P_DSR_AUTO; serialdata->oscam_ser_proto=P_DSR95; } usr=url; if( (dev=strchr(usr, '@')) ) { *dev++='\0'; if( (dummy=strchr(usr, ':')) ) // fake pwd *dummy++='\0'; if ((cltype == 'c') && (!usr[0])) return(0); } else { if (cltype == 'c') return(0); // user needed in server-mode dev=usr; } if( (baud=strchr(dev, ':')) )// port = baud *baud++='\0'; dummy=baud ? baud : dev; if( (para=strchr(dummy, '?')) ) { char *ptr1, *ptr2, *saveptr1 = NULL; *para++='\0'; for (ptr1=strtok_r(para, "&", &saveptr1); ptr1; ptr1=strtok_r(NULL, "&", &saveptr1)) { if (!(ptr2=strchr(ptr1, '='))) continue; *ptr2++='\0'; strtolower(ptr1); if (!strcmp("delay" , ptr1)) serialdata->oscam_ser_delay =atoi(ptr2); if (!strcmp("timeout", ptr1)) serialdata->oscam_ser_timeout=atoi(ptr2); } } if (baud) { trim(baud); #ifdef B115200 if (!strcmp(baud, "115200")) serialdata->oscam_ser_baud=B115200; else #endif #ifdef B57600 if (!strcmp(baud, "57600")) serialdata->oscam_ser_baud=B57600; else #endif if (!strcmp(baud, "38400")) serialdata->oscam_ser_baud=B38400; else if (!strcmp(baud, "19200")) serialdata->oscam_ser_baud=B19200; else if (!strcmp(baud, "9600")) serialdata->oscam_ser_baud=B9600; } if( (para=strchr(dev, ',')) )// device = ip/hostname and port { *para++='\0'; serialdata->oscam_ser_port=atoi(para); } else serialdata->oscam_ser_port=0; cs_strncpy(serialdata->oscam_ser_usr, usr, sizeof(serialdata->oscam_ser_usr)); cs_strncpy(serialdata->oscam_ser_device, dev, sizeof(serialdata->oscam_ser_device)); return(serialdata->oscam_ser_baud); }
/* Single cell, listing percentage */ void xml_pccell(FILE *outf, Outchoices *od, choice rep, choice col, double n, double tot, unsigned int width) { XML_TRACE(0); XML_OUT( XMLDBG"<col name=\"%s\">%f</col>", strtolower(column_name[col]), tot>0 ? 100*n/tot : 0.0 ); }
/* Single cell, index */ void xml_indexcell(FILE *outf, Outchoices *od, choice rep, choice col, long index, unsigned int width) { XML_TRACE(0); XML_OUT( XMLDBG"<col name=\"%s\">%ld</col>", strtolower(column_name[col]), index ); }
//Create new variable menu. int create_var_menu(Variable *varArry, int *arrySize, int arrySpot){ String type = (String)malloc(ARRAYLENGHT * sizeof (char)); String name = (String)malloc(ARRAYLENGHT * sizeof (char)); int flag; //Check if memory allocated properly. mem_check(type); mem_check(name); //Get the variable's type do{ //User interaction. printf("%s", "\n\nGive the variable's type. Valid types are Integer, Decimal, String and Bool. To go back type <:"); fgets(type, ARRAYLENGHT, stdin); flag = false; if (type[strlen(type) - 1] == '\n' && strlen(type) > 1){ type[strcspn(type, "\n")] = 0; //Drop the \n from fgets input strtolower(type); //Convert the string to lowercase for ease of use. //Check for back input if (!strcmp(type, "<")){ return false; } //Check for valid input. if (strcmp(type, "integer") && strcmp(type, "decimal") && strcmp(type, "string") && strcmp(type, "bool")){ printf("%s", "\n\nInvalid type!\n\n"); } } else{ flag = true; printf("%s", "\n\nInvalid lenght. It must be between 1 and 255 characters!\n\n"); if (strlen(type) > 1) clear_stdin(); //Clear stdin from extra input } } while (strcmp(type, "integer") && strcmp(type, "decimal") && strcmp(type, "string") && strcmp(type, "bool") || flag); //Loop until user decides to cooperate. //Get the variable's name. do{ //User interaction. printf("%s", "\n\nGive a name for the variable. The max lenght is 255 characters. It can't contain whitespaces or symbols, except underscores (_):"); fgets(name, ARRAYLENGHT, stdin); flag = false; //Check for valid lenght if (name[strlen(name) - 1] == '\n' && strlen(name) > 2){ name[strcspn(name, "\n")] = 0; //Drop the \n from fgets input. //Check for valid input if (strpbrk(name, " [email protected]#$%^&*()-+=\\|[]{};\':\",./<>?") != NULL){ printf("%s", "\n\nInvalid name!\n\n"); } else if (var_exist(varArry, name, *arrySize)){ printf("%s", "\n\nA variable with that name already exists!\n\n"); } } else{ flag = true; printf("%s", "\n\nInvalid lenght. It must be between 1 and 255 characters!\n\n"); if (strlen(name) > 1) clear_stdin(); //Clear stdin from extra input } } while (flag || strpbrk(name, " `[email protected]#$%^&*()-+=\\|[]{};\':\",./<>?") != NULL || var_exist(varArry, name, *arrySize)); //Loop until valid. //Copy the name and the type in the variables struct array. strcpy(varArry[arrySpot].type, type); strcpy(varArry[arrySpot].name, name); //Free the memory we don't need anymore. free(name); free(type); //Run the function corresponding to the entered type. if (!strcmp(varArry[arrySpot].type, "integer")){ set_var_int(varArry, arrySpot); } else if (!strcmp(varArry[arrySpot].type, "decimal")){ set_var_decimal(varArry, arrySpot); } else if (!strcmp(varArry[arrySpot].type, "string")){ //Loop until the lenght is correct. do{ //User interaction. For strings we don't need any valid input checks. printf("%s", "\n\nGive the variables value (String, 255 characters max):"); fgets(varArry[arrySpot].value, ARRAYLENGHT, stdin); flag = false; if (varArry[arrySpot].value[strlen(varArry[arrySpot].value) - 1] == '\n') varArry[arrySpot].value[strcspn(varArry[arrySpot].value, "\n")] = 0; //Drop the \n from fgets input. else{ flag = true; printf("%s", "\n\nInvalid lenght. It must be between 1 and 255 characters!\n\n"); clear_stdin(); //Clear stdin from extra input } } while (flag); } else{ set_var_bool(varArry, arrySpot); } return true; }
/* Single cell, listing bytes */ void xml_bytescell(FILE *outf, Outchoices *od, choice rep, choice col, double b, double bmult, unsigned int width) { XML_TRACE(0); XML_OUT( XMLDBG"<col name=\"%s\">%f</col>", strtolower(column_name[col]), b ); }
static int proc_config(int lineno, char *line, key_cmd **cmd) { int i, l, f = 1, etype = INVALID, ret = CONFERR; char *event = NULL, *attrs = NULL, *command = NULL; char *dup = NULL, *err = NULL, *tmp = NULL; unsigned char *keys; /*, *mledon[3], *mledoff[3];*/ unsigned int attr_bits = 0; attr_t *attrlst = NULL, *attr = NULL, *attr_last = NULL; l = strlen(line); for (i = 0; i <= l; ++i) { if (((line[i] == '#') || (line[i] == '\n') || (line[i] == '\0')) && (f < 4)) { err = "missing fields"; goto ERROR; } if ((line[i] == ':') && (f < 4)) { switch (f) { case 1: event = line + i + 1; break; case 2: attrs = line + i + 1; break; case 3: command = line + i + 1; break; } ++f; } } /* Keep a copy of the line */ dup = strdup(line); if (dup == NULL) { lprintf("Error: memory allocation failed\n"); ret = MEMERR; goto ERROR; } /* Set the field boundaries */ *(event - 1) = '\0'; *(attrs - 1) = '\0'; *(command - 1) = '\0'; if (line[l - 1] == '\n') line[l - 1] = '\0'; /* Set the event type */ strtolower(event); while ((tmp = strsep(&event, ", \t")) != NULL) { if (strlen(tmp) == 0) continue; if (strcmp(tmp, "key") == 0) { etype |= KEY; } else if (strcmp(tmp, "rep") == 0) { etype |= REP; } else if (strcmp(tmp, "rel") == 0) { etype |= REL; } else if (strcmp(tmp, "led") == 0) { /* Need some way to set LED on/off from incoming midi */ /* then error it because it is not a key stroke */ etype |= LED; } else { err = "invalid event type"; goto ERROR; } } /* If no event type was specified, fall back to `key' */ if (etype == INVALID) etype = KEY; /* The keys are always at the beginning of the line */ if (strmask(&keys, line) != OK) { err = "invalid <keys> field"; goto ERROR; } /* Set the attribute list */ strtolower(attrs); while ((tmp = strsep(&attrs, ", \t")) != NULL) { int type = -1; /* void *opt = NULL;*/ int opt = NULL; char *num = NULL; if (strlen(tmp) == 0) continue; if (strcmp(tmp, "noexec") == 0) { attr_bits |= BIT_ATTR_NOEXEC; } else if (strcmp(tmp, "grabbed") == 0) { attr_bits |= BIT_ATTR_GRABBED; } else if (strcmp(tmp, "ungrabbed") == 0) { attr_bits |= BIT_ATTR_UNGRABBED; } else if (strcmp(tmp, "not") == 0) { attr_bits |= BIT_ATTR_NOT; } else if (strcmp(tmp, "all") == 0) { attr_bits |= BIT_ATTR_ALL; } else if (strcmp(tmp, "any") == 0) { attr_bits |= BIT_ATTR_ANY; } else if (strcmp(tmp, "jackt") == 0) { type = ATTR_JACKT; attr_bits |= BIT_ATTR_NOEXEC; } else if (strcmp(tmp, "jackm") == 0) { type = ATTR_JACKM; attr_bits |= BIT_ATTR_NOEXEC; } else if (strcmp(tmp, "fader") == 0) { type = ATTR_FADER; attr_bits |= BIT_ATTR_NOEXEC; } else if (strcmp(tmp, "control") == 0) { type = ATTR_CNTRL; attr_bits |= BIT_ATTR_NOEXEC; } else if (strcmp(tmp, "exec") == 0) { type = ATTR_EXEC; } else if (strcmp(tmp, "grab") == 0) { type = ATTR_GRAB; } else if (strcmp(tmp, "ungrab") == 0) { type = ATTR_UNGRAB; } else if (strcmp(tmp, "ignrel") == 0) { type = ATTR_IGNREL; } else if (strcmp(tmp, "rcvrel") == 0) { type = ATTR_RCVREL; } else if (strcmp(tmp, "allrel") == 0) { type = ATTR_ALLREL; } else if (strncmp(tmp, "key(", 4) == 0) { type = ATTR_KEY; tmp += 4; num = (void *)1; } else if (strncmp(tmp, "rel(", 4) == 0) { type = ATTR_REL; tmp += 4; num = (void *)1; } else if (strncmp(tmp, "rep(", 4) == 0) { type = ATTR_REP; tmp += 4; num = (void *)1; } else if (strncmp(tmp, "set(", 4) == 0) { type = ATTR_SET; tmp += 4; num = (void *)1; } else if (strncmp(tmp, "unset(", 6) == 0) { type = ATTR_UNSET; tmp += 6; num = (void *)1; } else if (strncmp(tmp, "ledon(", 6) == 0) { type = ATTR_LEDON; tmp += 6; num = (void *)1; } else if (strncmp(tmp, "ledoff(", 7) == 0) { type = ATTR_LEDOFF; tmp += 7; num = (void *)1; } else { lprintf("Warning: unknown attribute %s\n", tmp); } if (num == (void *)1) { num = strsep(&tmp, "()"); errno = 0; if (strlen(num) > 0) { /* opt = (void *)((int)strtol(num, (char **)NULL, 10));*/ opt = ((int)strtol(num, (char **)NULL, 10)); } else { /* opt = (void *)((int)(-1));*/ opt = ((int)(-1)); } if (((int)opt < 0) && ((type == ATTR_LEDON) || (type == ATTR_LEDOFF))) errno = EINVAL; if (errno != 0) { err = "invalid attribute argument"; goto ERROR; } } /* handle event = LED */ if (etype == LED) { mled[num[0] - 48][0] = strtol(command, &command, 16); /* erroring out makes sure we don't set a key */ err = "incoming midi, no key"; goto ERROR; } if (type != -1) { attr = (attr_t *)(malloc(sizeof(attr_t))); if (attr == NULL) { lprintf("Error: memory allocation failed\n"); ret = MEMERR; goto ERROR; } attr->type = type; attr->opt = opt; attr->next = NULL; if (attrlst == NULL) { attrlst = attr; attr_last = attr; } else { attr_last->next = attr; attr_last = attr; } } } *cmd = (key_cmd *)(malloc(sizeof(key_cmd))); if (*cmd == NULL) { lprintf("Error: memory allocation failed\n"); ret = MEMERR; goto ERROR; } else { (*cmd)->keys = keys; (*cmd)->type = etype; (*cmd)->command = strdup(command); (*cmd)->attr_bits = attr_bits; (*cmd)->attrs = attrlst; } /* Destroy the line copy */ free(dup); return OK; /* Error handler */ ERROR: if ((verbose > 1) && (err != NULL)) lprintf("Warning: %s in configuration line %i\n", err, lineno); if (verbose > 0) lprintf("Warning: discarding configuration line %i:\n\t%s%c", lineno, (dup != NULL)?dup:line, (((dup != NULL)?dup:line)[l - 1] == '\n')?'\0':'\n'); *cmd = NULL; /* Free the attribute list */ while (attrlst != NULL) { attr = attrlst; attrlst = attrlst->next; free(attr); } if (dup != NULL) free(dup); return ret; }
/* A horizontal rule */ void xml_hrule(FILE *outf, Outchoices *od) { // an odd place to place this, but the only option. XML_OUT( XMLDBG"</report><!-- name=\"%s\" -->", strtolower(report_name[this_report]) ); }
/* *************************************************************************** * Main entry to the iostat program. *************************************************************************** */ int main(int argc, char **argv) { int it = 0; int opt = 1; int i, report_set = FALSE; long count = 1; struct utsname header; struct io_dlist *st_dev_list_i; struct tm rectime; char *t, *persist_devname, *devname; #ifdef USE_NLS /* Init National Language Support */ init_nls(); #endif /* Get HZ */ get_HZ(); /* Allocate structures for device list */ if (argc > 1) { salloc_dev_list(argc - 1 + count_csvalues(argc, argv)); } /* Process args... */ while (opt < argc) { /* -p option used individually. See below for grouped use */ if (!strcmp(argv[opt], "-p")) { flags |= I_D_PARTITIONS; if (argv[++opt] && (strspn(argv[opt], DIGITS) != strlen(argv[opt])) && (strncmp(argv[opt], "-", 1))) { flags |= I_D_UNFILTERED; for (t = strtok(argv[opt], ","); t; t = strtok(NULL, ",")) { if (!strcmp(t, K_ALL)) { flags |= I_D_PART_ALL; } else { devname = device_name(t); if (DISPLAY_PERSIST_NAME_I(flags)) { /* Get device persistent name */ persist_devname = get_pretty_name_from_persistent(devname); if (persist_devname != NULL) { devname = persist_devname; } } /* Store device name */ i = update_dev_list(&dlist_idx, devname); st_dev_list_i = st_dev_list + i; st_dev_list_i->disp_part = TRUE; } } opt++; } else { flags |= I_D_PART_ALL; } } else if (!strcmp(argv[opt], "-g")) { /* * Option -g: Stats for a group of devices. * group_name contains the last group name entered on * the command line. If we define an additional one, save * the previous one in the list. We do that this way because we * want the group name to appear in the list _after_ all * the devices included in that group. The last group name * will be saved in the list later, in presave_device_list() function. */ if (group_nr > 0) { update_dev_list(&dlist_idx, group_name); } if (argv[++opt]) { /* * MAX_NAME_LEN - 2: one char for the heading space, * and one for the trailing '\0'. */ snprintf(group_name, MAX_NAME_LEN, " %-.*s", MAX_NAME_LEN - 2, argv[opt++]); } else { usage(argv[0]); } group_nr++; } else if (!strcmp(argv[opt], "-j")) { if (argv[++opt]) { if (strnlen(argv[opt], MAX_FILE_LEN) >= MAX_FILE_LEN - 1) { usage(argv[0]); } strncpy(persistent_name_type, argv[opt], MAX_FILE_LEN - 1); persistent_name_type[MAX_FILE_LEN - 1] = '\0'; strtolower(persistent_name_type); /* Check that this is a valid type of persistent device name */ if (!get_persistent_type_dir(persistent_name_type)) { fprintf(stderr, _("Invalid type of persistent device name\n")); exit(1); } /* * Persistent names are usually long: Display * them as human readable by default. */ flags |= I_D_PERSIST_NAME + I_D_HUMAN_READ; opt++; } else { usage(argv[0]); } } #ifdef DEBUG else if (!strcmp(argv[opt], "--debuginfo")) { flags |= I_D_DEBUG; opt++; } #endif else if (!strncmp(argv[opt], "-", 1)) { for (i = 1; *(argv[opt] + i); i++) { switch (*(argv[opt] + i)) { case 'c': /* Display cpu usage */ flags |= I_D_CPU; report_set = TRUE; break; case 'd': /* Display disk utilization */ flags |= I_D_DISK; report_set = TRUE; break; case 'h': /* * Display device utilization report * in a human readable format. */ flags |= I_D_HUMAN_READ; break; case 'k': if (DISPLAY_MEGABYTES(flags)) { usage(argv[0]); } /* Display stats in kB/s */ flags |= I_D_KILOBYTES; break; case 'm': if (DISPLAY_KILOBYTES(flags)) { usage(argv[0]); } /* Display stats in MB/s */ flags |= I_D_MEGABYTES; break; case 'N': /* Display device mapper logical name */ flags |= I_D_DEVMAP_NAME; break; case 'p': /* If option -p is grouped then it cannot take an arg */ flags |= I_D_PARTITIONS + I_D_PART_ALL; break; case 'T': /* Display stats only for the groups */ flags |= I_D_GROUP_TOTAL_ONLY; break; case 't': /* Display timestamp */ flags |= I_D_TIMESTAMP; break; case 'x': /* Display extended stats */ flags |= I_D_EXTENDED; break; case 'y': /* Don't display stats since system restart */ flags |= I_D_OMIT_SINCE_BOOT; break; case 'z': /* Omit output for devices with no activity */ flags |= I_D_ZERO_OMIT; break; case 'V': /* Print version number and exit */ print_version(); break; default: usage(argv[0]); } } opt++; } else if (!isdigit(argv[opt][0])) { /* * By default iostat doesn't display unused devices. * If some devices are explictly entered on the command line * then don't apply this rule any more. */ flags |= I_D_UNFILTERED; if (strcmp(argv[opt], K_ALL)) { /* Store device name entered on the command line */ devname = device_name(argv[opt++]); if (DISPLAY_PERSIST_NAME_I(flags)) { persist_devname = get_pretty_name_from_persistent(devname); if (persist_devname != NULL) { devname = persist_devname; } } update_dev_list(&dlist_idx, devname); } else { opt++; } } else if (!it) { interval = atol(argv[opt++]); if (interval < 0) { usage(argv[0]); } count = -1; it = 1; } else if (it > 0) { count = atol(argv[opt++]); if ((count < 1) || !interval) { usage(argv[0]); } it = -1; } else { usage(argv[0]); } } if (!interval) { count = 1; } /* Default: Display CPU and DISK reports */ if (!report_set) { flags |= I_D_CPU + I_D_DISK; } /* * Also display DISK reports if options -p, -x or a device has been entered * on the command line. */ if (DISPLAY_PARTITIONS(flags) || DISPLAY_EXTENDED(flags) || DISPLAY_UNFILTERED(flags)) { flags |= I_D_DISK; } /* Option -T can only be used with option -g */ if (DISPLAY_GROUP_TOTAL_ONLY(flags) && !group_nr) { usage(argv[0]); } /* Select disk output unit (kB/s or blocks/s) */ set_disk_output_unit(); /* Ignore device list if '-p ALL' entered on the command line */ if (DISPLAY_PART_ALL(flags)) { dlist_idx = 0; } if (DISPLAY_DEVMAP_NAME(flags)) { dm_major = get_devmap_major(); } /* Init structures according to machine architecture */ io_sys_init(); if (group_nr > 0) { /* * If groups of devices have been defined * then save devices and groups in the list. */ presave_device_list(); } get_localtime(&rectime, 0); /* Get system name, release number and hostname */ uname(&header); if (print_gal_header(&rectime, header.sysname, header.release, header.nodename, header.machine, cpu_nr)) { flags |= I_D_ISO; } printf("\n"); /* Set a handler for SIGALRM */ memset(&alrm_act, 0, sizeof(alrm_act)); alrm_act.sa_handler = alarm_handler; sigaction(SIGALRM, &alrm_act, NULL); alarm(interval); /* Main loop */ rw_io_stat_loop(count, &rectime); /* Free structures */ io_sys_free(); sfree_dev_list(); return 0; }
int lws_client_interpret_server_handshake(struct lws *wsi) { int n, len, okay = 0, isErrorCodeReceived = 0, port = 0, ssl = 0; struct lws_context *context = wsi->context; int close_reason = LWS_CLOSE_STATUS_PROTOCOL_ERR; const char *pc, *prot, *ads = NULL, *path; char *p; #ifndef LWS_NO_EXTENSIONS struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi]; char *sb = (char *)&pt->serv_buf[0]; const struct lws_ext_options *opts; const struct lws_extension *ext; char ext_name[128]; const char *c, *a; char ignore; int more = 1; void *v; #endif /* * well, what the server sent looked reasonable for syntax. * Now let's confirm it sent all the necessary headers */ p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP); if (!p) { lwsl_info("no URI\n"); goto bail3; } n = atoi(p); if (n == 301 || n == 302 || n == 303 || n == 307 || n == 308) { p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_LOCATION); if (!p) goto bail3; if (lws_parse_uri(p, &prot, &ads, &port, &path)) goto bail3; if (!strcmp(prot, "wss://") || !strcmp(prot, "https://")) ssl = 1; if (lws_client_reset(wsi, ssl, ads, port, path, ads)) { lwsl_err("Redirect failed\n"); goto bail3; } return 0; } if (lws_hdr_total_length(wsi, WSI_TOKEN_ACCEPT) == 0) { lwsl_info("no ACCEPT\n"); isErrorCodeReceived = 1; goto bail3; } if (p && strncmp(p, "101", 3)) { lwsl_warn( "lws_client_handshake: got bad HTTP response '%s'\n", p); goto bail3; } p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE); if (!p) { lwsl_info("no UPGRADE\n"); goto bail3; } strtolower(p); if (strcmp(p, "websocket")) { lwsl_warn( "lws_client_handshake: got bad Upgrade header '%s'\n", p); goto bail3; } p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_CONNECTION); if (!p) { lwsl_info("no Connection hdr\n"); goto bail3; } strtolower(p); if (strcmp(p, "upgrade")) { lwsl_warn("lws_client_int_s_hs: bad header %s\n", p); goto bail3; } pc = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS); if (!pc) { lwsl_parser("lws_client_int_s_hs: no protocol list\n"); } else lwsl_parser("lws_client_int_s_hs: protocol list '%s'\n", pc); /* * confirm the protocol the server wants to talk was in the list * of protocols we offered */ len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL); if (!len) { lwsl_info("lws_client_int_s_hs: WSI_TOKEN_PROTOCOL is null\n"); /* * no protocol name to work from, * default to first protocol */ wsi->protocol = &context->protocols[0]; goto check_extensions; } p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL); len = strlen(p); while (pc && *pc && !okay) { if (!strncmp(pc, p, len) && (pc[len] == ',' || pc[len] == '\0')) { okay = 1; continue; } while (*pc && *pc++ != ',') ; while (*pc && *pc == ' ') pc++; } if (!okay) { lwsl_err("lws_client_int_s_hs: got bad protocol %s\n", p); goto bail2; } /* * identify the selected protocol struct and set it */ n = 0; wsi->protocol = NULL; while (context->protocols[n].callback && !wsi->protocol) { if (strcmp(p, context->protocols[n].name) == 0) { wsi->protocol = &context->protocols[n]; break; } n++; } if (wsi->protocol == NULL) { lwsl_err("lws_client_int_s_hs: fail protocol %s\n", p); goto bail2; } check_extensions: #ifndef LWS_NO_EXTENSIONS /* instantiate the accepted extensions */ if (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS)) { lwsl_ext("no client extenstions allowed by server\n"); goto check_accept; } /* * break down the list of server accepted extensions * and go through matching them or identifying bogons */ if (lws_hdr_copy(wsi, sb, LWS_MAX_SOCKET_IO_BUF, WSI_TOKEN_EXTENSIONS) < 0) { lwsl_warn("ext list from server failed to copy\n"); goto bail2; } c = sb; n = 0; ignore = 0; a = NULL; while (more) { if (*c && (*c != ',' && *c != '\t')) { if (*c == ';') { ignore = 1; if (!a) a = c + 1; } if (ignore || *c == ' ') { c++; continue; } ext_name[n] = *c++; if (n < sizeof(ext_name) - 1) n++; continue; } ext_name[n] = '\0'; ignore = 0; if (!*c) more = 0; else { c++; if (!n) continue; } /* check we actually support it */ lwsl_notice("checking client ext %s\n", ext_name); n = 0; ext = lws_get_context(wsi)->extensions; while (ext && ext->callback) { if (strcmp(ext_name, ext->name)) { ext++; continue; } n = 1; lwsl_notice("instantiating client ext %s\n", ext_name); /* instantiate the extension on this conn */ wsi->active_extensions[wsi->count_act_ext] = ext; /* allow him to construct his ext instance */ ext->callback(lws_get_context(wsi), ext, wsi, LWS_EXT_CB_CLIENT_CONSTRUCT, (void *)&wsi->act_ext_user[wsi->count_act_ext], (void *)&opts, 0); /* * allow the user code to override ext defaults if it * wants to */ ext_name[0] = '\0'; if (user_callback_handle_rxflow(wsi->protocol->callback, wsi, LWS_CALLBACK_WS_EXT_DEFAULTS, (char *)ext->name, ext_name, sizeof(ext_name))) goto bail2; if (ext_name[0] && lws_ext_parse_options(ext, wsi, wsi->act_ext_user[ wsi->count_act_ext], opts, ext_name, strlen(ext_name))) { lwsl_err("%s: unable to parse user defaults '%s'", __func__, ext_name); goto bail2; } /* * give the extension the server options */ if (a && lws_ext_parse_options(ext, wsi, wsi->act_ext_user[wsi->count_act_ext], opts, a, c - a)) { lwsl_err("%s: unable to parse remote def '%s'", __func__, a); goto bail2; } if (ext->callback(lws_get_context(wsi), ext, wsi, LWS_EXT_CB_OPTION_CONFIRM, wsi->act_ext_user[wsi->count_act_ext], NULL, 0)) { lwsl_err("%s: ext %s rejects server options %s", ext->name, a); goto bail2; } wsi->count_act_ext++; ext++; } if (n == 0) { lwsl_warn("Unknown ext '%s'!\n", ext_name); goto bail2; } a = NULL; n = 0; } check_accept: #endif /* * Confirm his accept token is the one we precomputed */ p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_ACCEPT); if (strcmp(p, wsi->u.hdr.ah->initial_handshake_hash_base64)) { lwsl_warn("lws_client_int_s_hs: accept '%s' wrong vs '%s'\n", p, wsi->u.hdr.ah->initial_handshake_hash_base64); goto bail2; } /* allocate the per-connection user memory (if any) */ if (lws_ensure_user_space(wsi)) { lwsl_err("Problem allocating wsi user mem\n"); goto bail2; } /* * we seem to be good to go, give client last chance to check * headers and OK it */ if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH, wsi->user_space, NULL, 0)) goto bail2; /* clear his proxy connection timeout */ lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); /* free up his parsing allocations */ lws_free_header_table(wsi); lws_union_transition(wsi, LWSCM_WS_CLIENT); wsi->state = LWSS_ESTABLISHED; wsi->rxflow_change_to = LWS_RXFLOW_ALLOW; /* * create the frame buffer for this connection according to the * size mentioned in the protocol definition. If 0 there, then * use a big default for compatibility */ n = wsi->protocol->rx_buffer_size; if (!n) n = LWS_MAX_SOCKET_IO_BUF; n += LWS_PRE; wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */); if (!wsi->u.ws.rx_ubuf) { lwsl_err("Out of Mem allocating rx buffer %d\n", n); goto bail2; } wsi->u.ws.rx_ubuf_alloc = n; lwsl_info("Allocating client RX buffer %d\n", n); if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF, (const char *)&n, sizeof n)) { lwsl_warn("Failed to set SNDBUF to %d", n); goto bail3; } lwsl_debug("handshake OK for protocol %s\n", wsi->protocol->name); /* call him back to inform him he is up */ if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_ESTABLISHED, wsi->user_space, NULL, 0)) goto bail3; #ifndef LWS_NO_EXTENSIONS /* * inform all extensions, not just active ones since they * already know */ ext = context->extensions; while (ext && ext->callback) { v = NULL; for (n = 0; n < wsi->count_act_ext; n++) if (wsi->active_extensions[n] == ext) v = wsi->act_ext_user[n]; ext->callback(context, ext, wsi, LWS_EXT_CB_ANY_WSI_ESTABLISHED, v, NULL, 0); ext++; } #endif return 0; bail3: close_reason = LWS_CLOSE_STATUS_NOSTATUS; bail2: if (wsi->protocol && wsi->state == LWSS_ESTABLISHED) { if (isErrorCodeReceived && p) { wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_CONNECTION_ERROR, wsi->user_space, p, (unsigned int)strlen(p)); } else { wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_CONNECTION_ERROR, wsi->user_space, NULL, 0); } } lwsl_info("closing connection due to bail2 connection error\n"); /* closing will free up his parsing allocations */ lws_close_free_wsi(wsi, close_reason); return 1; }
int main (int argc, char **argv) { SHPLOADERCONFIG *config; SHPLOADERSTATE *state; char *header, *footer, *record; int c; int ret, i; #ifdef ENABLE_NLS setlocale (LC_ALL, ""); bindtextdomain (PACKAGE, PGSQL_LOCALEDIR); textdomain (PACKAGE); #endif /* If no options are specified, display usage */ if (argc == 1) { usage(); exit(0); } /* Parse command line options and set configuration */ config = malloc(sizeof(SHPLOADERCONFIG)); set_loader_config_defaults(config); /* Keep the flag list alphabetic so it's easy to see what's left. */ while ((c = pgis_getopt(argc, argv, "acdeg:iknps:t:wDGIN:ST:W:X:")) != EOF) { switch (c) { case 'c': case 'd': case 'a': case 'p': config->opt = c; break; case 'D': config->dump_format = 1; break; case 'G': config->geography = 1; break; case 'S': config->simple_geometries = 1; break; case 's': if (pgis_optarg) { char *ptr = strchr(pgis_optarg, ':'); if (ptr) { *ptr++ = '\0'; sscanf(pgis_optarg, "%d", &config->shp_sr_id); sscanf(ptr, "%d", &config->sr_id); } else { /* Only TO_SRID specified */ sscanf(pgis_optarg, "%d", &config->sr_id); } } else { /* With -s, user must specify TO_SRID or FROM_SRID:TO_SRID */ fprintf(stderr, "The -s parameter must be specified in the form [FROM_SRID:]TO_SRID\n"); exit(1); } break; case 'g': config->geo_col = pgis_optarg; break; case 'k': config->quoteidentifiers = 1; break; case 'i': config->forceint4 = 1; break; case 'I': config->createindex = 1; break; case 'w': config->use_wkt = 1; break; case 'n': config->readshape = 0; break; case 'W': config->encoding = pgis_optarg; break; case 'N': switch (pgis_optarg[0]) { case 'a': config->null_policy = POLICY_NULL_ABORT; break; case 'i': config->null_policy = POLICY_NULL_INSERT; break; case 's': config->null_policy = POLICY_NULL_SKIP; break; default: fprintf(stderr, "Unsupported NULL geometry handling policy.\nValid policies: insert, skip, abort\n"); exit(1); } break; case 't': if (strcasecmp(pgis_optarg, "2D") == 0) { config->force_output = FORCE_OUTPUT_2D; } else if (strcasecmp(pgis_optarg, "3DZ") == 0 ) { config->force_output = FORCE_OUTPUT_3DZ; } else if (strcasecmp(pgis_optarg, "3DM") == 0 ) { config->force_output = FORCE_OUTPUT_3DM; } else if (strcasecmp(pgis_optarg, "4D") == 0 ) { config->force_output = FORCE_OUTPUT_4D; } else { fprintf(stderr, "Unsupported output type: %s\nValid output types are 2D, 3DZ, 3DM and 4D\n", pgis_optarg); exit(1); } break; case 'T': config->tablespace = pgis_optarg; break; case 'X': config->idxtablespace = pgis_optarg; break; case 'e': config->usetransaction = 0; break; case '?': usage(); exit(0); default: usage(); exit(0); } } /* Once we have parsed the arguments, make sure certain combinations are valid */ if (config->dump_format && !config->usetransaction) { fprintf(stderr, "Invalid argument combination - cannot use both -D and -e\n"); exit(1); } if (config->dump_format && config->shp_sr_id != SRID_UNKNOWN) { fprintf(stderr, "Invalid argument combination - cannot use -D with -s FROM_SRID:TO_SRID\n"); exit(1); } /* Determine the shapefile name from the next argument, if no shape file, exit. */ if (pgis_optind < argc) { config->shp_file = argv[pgis_optind]; pgis_optind++; } else { usage(); exit(0); } /* Determine the table and schema names from the next argument */ if (pgis_optind < argc) { char *strptr = argv[pgis_optind]; char *chrptr = strchr(strptr, '.'); /* OK, this is a schema-qualified table name... */ if (chrptr) { if ( chrptr == strptr ) { /* ".something" ??? */ usage(); exit(0); } /* Null terminate at the '.' */ *chrptr = '\0'; /* Copy in the parts */ config->schema = strdup(strptr); config->table = strdup(chrptr+1); } else { config->table = strdup(strptr); } } /* If the table parameter is not provided, use the shape file name as a proxy value. Strip out the .shp and the leading path information first. */ if ( config->shp_file && config->table == NULL) { char *shp_file = strdup(config->shp_file); char *ptr; for ( ptr = shp_file + strlen(shp_file); ptr > shp_file; ptr-- ) { if ( *ptr == '.' ) { *ptr = '\0'; } if ( *ptr == '/' || *ptr == '\\' ) { ptr++; break; } } config->table = strdup(ptr); free(shp_file); } /* Transform table name to lower case if no quoting specified */ if (!config->quoteidentifiers) { if ( config->table ) strtolower(config->table); if ( config->schema ) strtolower(config->schema); } /* Create the shapefile state object */ state = ShpLoaderCreate(config); /* Open the shapefile */ ret = ShpLoaderOpenShape(state); if (ret != SHPLOADEROK) { fprintf(stderr, "%s\n", state->message); if (ret == SHPLOADERERR) exit(1); } /* If reading the whole shapefile, display its type */ if (state->config->readshape) { fprintf(stderr, "Shapefile type: %s\n", SHPTypeName(state->shpfiletype)); fprintf(stderr, "Postgis type: %s[%d]\n", state->pgtype, state->pgdims); } /* Print the header to stdout */ ret = ShpLoaderGetSQLHeader(state, &header); if (ret != SHPLOADEROK) { fprintf(stderr, "%s\n", state->message); if (ret == SHPLOADERERR) exit(1); } printf("%s", header); free(header); /* If we are not in "prepare" mode, go ahead and write out the data. */ if ( state->config->opt != 'p' ) { /* If in COPY mode, output the COPY statement */ if (state->config->dump_format) { ret = ShpLoaderGetSQLCopyStatement(state, &header); if (ret != SHPLOADEROK) { fprintf(stderr, "%s\n", state->message); if (ret == SHPLOADERERR) exit(1); } printf("%s", header); free(header); } /* Main loop: iterate through all of the records and send them to stdout */ for (i = 0; i < ShpLoaderGetRecordCount(state); i++) { ret = ShpLoaderGenerateSQLRowStatement(state, i, &record); switch (ret) { case SHPLOADEROK: /* Simply display the geometry */ printf("%s\n", record); free(record); break; case SHPLOADERERR: /* Display the error message then stop */ fprintf(stderr, "%s\n", state->message); exit(1); break; case SHPLOADERWARN: /* Display the warning, but continue */ fprintf(stderr, "%s\n", state->message); printf("%s\n", record); free(record); break; case SHPLOADERRECDELETED: /* Record is marked as deleted - ignore */ break; case SHPLOADERRECISNULL: /* Record is NULL and should be ignored according to NULL policy */ break; } } /* If in COPY mode, terminate the COPY statement */ if (state->config->dump_format) printf("\\.\n"); } /* Print the footer to stdout */ ret = ShpLoaderGetSQLFooter(state, &footer); if (ret != SHPLOADEROK) { fprintf(stderr, "%s\n", state->message); if (ret == SHPLOADERERR) exit(1); } printf("%s", footer); free(footer); /* Free the state object */ ShpLoaderDestroy(state); /* Free configuration variables */ if (config->schema) free(config->schema); if (config->table) free(config->table); free(config); return 0; }
bool matchScheme(const std::string& url, const std::string& scheme) { std::string s = strtolower(scheme) + ":"; return 0 == strtolower(url).find(s); }
void generate_code_python(batch *b) { umlclasslist tmplist, parents; umlattrlist umla, tmpa; umloplist umlo; char *tmpname; char outfilename[90]; FILE * outfile, *dummyfile, *licensefile = NULL; namelist used_classes, tmpnamelist; int tmpdirlgth, tmpfilelgth; int interface, abstract; if (b->outdir == NULL) { b->outdir = "."; } tmpdirlgth = strlen(b->outdir); tmplist = b->classlist; /* open license file */ if ( b->license != NULL ) { licensefile = fopen(b->license, "r"); if(!licensefile) { fprintf(stderr, "Can't open the license file.\n"); exit(2); } } while ( tmplist != NULL ) { if ( ! ( is_present(b->classes, tmplist->key->name) ^ b->mask ) ) { tmpname = tmplist->key->name; /* This prevents buffer overflows */ tmpfilelgth = strlen(tmpname); if (tmpfilelgth + tmpdirlgth > sizeof(*outfilename) - 2) { fprintf(stderr, "Sorry, name of file too long ...\nTry a smaller dir name\n"); exit(4); } sprintf(outfilename, "%s/%s.py", b->outdir, tmplist->key->name); dummyfile = fopen(outfilename, "r"); if ( b->clobber || ! dummyfile ) { outfile = fopen(outfilename, "w"); if ( outfile == NULL ) { fprintf(stderr, "Can't open file %s for writing\n", outfilename); exit(3); } /* add license to the header */ if(b->license != NULL){ char lc; rewind(licensefile); while((lc = fgetc(licensefile)) != EOF){ fprintf(outfile,"%c",lc); } } used_classes = find_classes(tmplist, b); tmpnamelist = used_classes; while (tmpnamelist != NULL) { fprintf(outfile, "from %s import %s\n", tmpnamelist->name, tmpnamelist->name); tmpnamelist = tmpnamelist->next; } fprintf(outfile, "\n"); tmpname = strtolower(tmplist->key->stereotype); interface = !strcmp("interface", tmpname); abstract = tmplist->key->isabstract; free(tmpname); fprintf(outfile, "class %s", tmplist->key->name); parents = tmplist->parents; if (parents != NULL) { fprintf(outfile, "("); while ( parents != NULL ) { fprintf(outfile, "%s", parents->key->name); parents = parents->next; if (parents != NULL) fprintf(outfile, ", "); } fprintf(outfile, ")"); } fprintf(outfile, ":\n"); if (abstract) { fprintf(outfile, " \"\"\"Abstract class %s\n \"\"\"\n", tmplist->key->name); } else if (interface) { fprintf(outfile, " \"\"\"Interface %s\n \"\"\"\n", tmplist->key->name); } else { fprintf(outfile, " \"\"\"Class %s\n \"\"\"\n", tmplist->key->name); } fprintf(outfile, " # Attributes:\n"); umla = tmplist->key->attributes; while ( umla != NULL) { switch (umla->key.visibility) { case '0': fprintf (outfile, " "); break; case '1': fprintf (outfile, " __"); break; case '2': fprintf (outfile, " _"); break; } fprintf(outfile, "%s", umla->key.name); if ( umla->key.value[0] != 0 ) { fprintf(outfile, " = %s", umla->key.value); } else { fprintf(outfile, " = None"); } fprintf(outfile, " # (%s) \n", umla->key.type); umla = umla->next; } fprintf(outfile, " \n"); umlo = tmplist->key->operations; fprintf(outfile, " # Operations\n"); while ( umlo != NULL) { switch (umlo->key.attr.visibility) { case '0': fprintf (outfile, " def %s(self", umlo->key.attr.name); break; case '1': fprintf (outfile, " def __%s(self", umlo->key.attr.name); break; case '2': fprintf (outfile, " def _%s(self", umlo->key.attr.name); break; } tmpa = umlo->key.parameters; while (tmpa != NULL) { fprintf(outfile, ", %s", tmpa->key.name); if ( tmpa->key.value[0] != 0 ) { fprintf(outfile, " = %s", tmpa->key.value); } tmpa = tmpa->next; } fprintf(outfile, "):\n"); fprintf(outfile, " \"\"\"function %s\n", umlo->key.attr.name); tmpa = umlo->key.parameters; if (tmpa) fprintf(outfile, " \n"); while (tmpa != NULL) { fprintf(outfile, " %s: %s\n", tmpa->key.name, tmpa->key.type); tmpa = tmpa->next; } fprintf(outfile, " \n"); fprintf(outfile, " returns %s\n", umlo->key.attr.type); fprintf(outfile, " \"\"\"\n"); if (abstract || interface) { fprintf(outfile, " raise NotImplementedError()\n \n"); } else { fprintf(outfile, " return None # should raise NotImplementedError()\n \n"); } umlo = umlo->next; } fprintf(outfile, "\n"); fclose(outfile); } } tmplist = tmplist->next; } }
int RedisLink::convert_req(){ if(!inited){ inited = true; RedisCommand_raw *def = &cmds_raw[0]; while(def->redis_cmd != NULL){ RedisRequestDesc desc; desc.strategy = def->strategy; desc.redis_cmd = def->redis_cmd; desc.ssdb_cmd = def->ssdb_cmd; desc.reply_type = def->reply_type; cmd_table[desc.redis_cmd] = desc; def += 1; } } this->req_desc = NULL; std::map<std::string, RedisRequestDesc>::iterator it; it = cmd_table.find(cmd); if(it == cmd_table.end()){ recv_string.push_back(cmd); return 0; } this->req_desc = &(it->second); if(this->req_desc->strategy == STRATEGY_HKEYS || this->req_desc->strategy == STRATEGY_HVALS ){ recv_string.push_back(req_desc->ssdb_cmd); if(recv_bytes.size() == 2){ recv_string.push_back(recv_bytes[1].String()); recv_string.push_back(""); recv_string.push_back(""); recv_string.push_back("99999999999999"); } return 0; } if(this->req_desc->strategy == STRATEGY_SETEX){ recv_string.push_back(req_desc->ssdb_cmd); if(recv_bytes.size() == 4){ recv_string.push_back(recv_bytes[1].String()); recv_string.push_back(recv_bytes[3].String()); recv_string.push_back(recv_bytes[2].String()); } return 0; } if(this->req_desc->strategy == STRATEGY_ZADD){ recv_string.push_back(req_desc->ssdb_cmd); if(recv_bytes.size() >= 2){ recv_string.push_back(recv_bytes[1].String()); for(int i=2; i<=recv_bytes.size()-2; i+=2){ recv_string.push_back(recv_bytes[i+1].String()); recv_string.push_back(recv_bytes[i].String()); } } return 0; } if(this->req_desc->strategy == STRATEGY_ZINCRBY){ recv_string.push_back(req_desc->ssdb_cmd); if(recv_bytes.size() == 4){ recv_string.push_back(recv_bytes[1].String()); recv_string.push_back(recv_bytes[3].String()); recv_string.push_back(recv_bytes[2].String()); } return 0; } if(this->req_desc->strategy == STRATEGY_REMRANGEBYRANK || this->req_desc->strategy == STRATEGY_REMRANGEBYSCORE) { recv_string.push_back(req_desc->ssdb_cmd); if(recv_bytes.size() >= 4){ recv_string.push_back(recv_bytes[1].String()); recv_string.push_back(recv_bytes[2].String()); recv_string.push_back(recv_bytes[3].String()); } return 0; } if(this->req_desc->strategy == STRATEGY_ZRANGE || this->req_desc->strategy == STRATEGY_ZREVRANGE) { recv_string.push_back(req_desc->ssdb_cmd); if(recv_bytes.size() >= 4){ int64_t start = recv_bytes[2].Int64(); int64_t end = recv_bytes[3].Int64(); if((start >= 0 && end >= 0) || end == -1){ int64_t size; if(end == -1){ size = -1; }else{ if(this->req_desc->strategy == STRATEGY_REMRANGEBYSCORE){ size = end; }else{ size = end - start + 1; } } recv_string.push_back(recv_bytes[1].String()); recv_string.push_back(recv_bytes[2].String()); recv_string.push_back(int64_to_str(size)); } } if(recv_bytes.size() > 4){ std::string s = recv_bytes[4].String(); strtolower(&s); recv_string.push_back(s); } return 0; } if(this->req_desc->strategy == STRATEGY_ZRANGEBYSCORE || this->req_desc->strategy == STRATEGY_ZREVRANGEBYSCORE){ recv_string.push_back(req_desc->ssdb_cmd); std::string name, smin, smax, withscores, offset, count; if(recv_bytes.size() >= 4){ name = recv_bytes[1].String(); smin = recv_bytes[2].String(); smax = recv_bytes[3].String(); bool after_limit = false; for(int i=4; i<recv_bytes.size(); i++){ std::string s = recv_bytes[i].String(); if(after_limit){ if(offset.empty()){ offset = s; }else{ count = s; after_limit = false; } } strtolower(&s); if(s == "withscores"){ withscores = s; }else if(s == "limit"){ after_limit = true; } } } if(smin.empty() || smax.empty()){ return 0; } recv_string.push_back(name); recv_string.push_back(""); if(smin == "-inf" || smin == "+inf"){ recv_string.push_back(""); }else{ if(smin[0] == '('){ std::string tmp(smin.data() + 1, smin.size() - 1); char buf[32]; if(this->req_desc->strategy == STRATEGY_ZRANGEBYSCORE){ snprintf(buf, sizeof(buf), "%d", str_to_int(tmp) + 1); }else{ snprintf(buf, sizeof(buf), "%d", str_to_int(tmp) - 1); } smin = buf; } recv_string.push_back(smin); } if(smax == "-inf" || smax == "+inf"){ recv_string.push_back(""); }else{ if(smax[0] == '('){ std::string tmp(smax.data() + 1, smax.size() - 1); char buf[32]; if(this->req_desc->strategy == STRATEGY_ZRANGEBYSCORE){ snprintf(buf, sizeof(buf), "%d", str_to_int(tmp) - 1); }else{ snprintf(buf, sizeof(buf), "%d", str_to_int(tmp) + 1); } smax = buf; } recv_string.push_back(smax); } if(!offset.empty()){ recv_string.push_back(offset); } if(count.empty()){ recv_string.push_back("999999999999"); }else{ recv_string.push_back(count); } recv_string.push_back(withscores); return 0; } recv_string.push_back(req_desc->ssdb_cmd); for(int i=1; i<recv_bytes.size(); i++){ recv_string.push_back(recv_bytes[i].String()); } return 0; }
/* Name column */ void xml_namecell(FILE *outf, Outchoices *od, choice rep, char *name, choice source, unsigned int width, logical name1st, logical isfirst, logical rightalign, Alias *aliashead, Include *linkhead, logical ispage, unsigned int spaces, char *baseurl) { char *p, *q; int n; XML_TRACE(0); // no output aliasing is done yet. not sure it will be done either. // we don't care, but by testing it we avoid printing the column twice. if ( !isfirst && name ) { XML_OUT( XMLDBG "<col name=\"name\">" ); switch( rep) { case REP_MONTH: case REP_YEAR: case REP_WEEK: case REP_QUARTERLY: case REP_DAYREP: case REP_HOURREP: case REP_QUARTERREP: case REP_FIVEREP: case REP_DAYSUM: case REP_HOURSUM: case REP_QUARTERSUM: case REP_FIVESUM: case REP_WEEKHOUR: // this is split because strtok needs to be called in the right order. XML_OUT( "<timespan from=\"%s\" ", strtok(name," ") ); XML_OUT( "to=\"%s\" ", strtok( NULL," ") ); switch( rep ) { case REP_DAYSUM: XML_OUT( "dayofweek=\"%s\" />", strtok( NULL," ") ); break; case REP_HOURSUM: XML_OUT( "hour=\"%s\" />", strtok( NULL," ") ); break; case REP_QUARTERSUM: XML_OUT( "minute=\"%s\" />", strtok( NULL," ") ); break; case REP_FIVESUM: XML_OUT( "minute=\"%s\" />", strtok( NULL," ") ); break; case REP_WEEKHOUR: XML_OUT( "dayofweek=\"%s\" ", strtok( NULL," ") ); XML_OUT( "hour=\"%s\" />", strtok( NULL," ") ); break; default: XML_OUT( "/>" ); } break; case REP_CODE: strtok(name, " "); // assumption: name = "nnn text" XML_OUT( name ); break; // n=array_index++; // XML_OUT( "%d", (int)(opts->arraydata[rep-FIRST_ARRAYREP][n].threshold) ); // break; case REP_OS: // kludge: the hardcoded OS names from tree.c are turned into i18n // keys - hardly a well thought out interface, but the best we can do // for the moment. p=strtolower(name); // all lowercase while ( (q=strchr(p,' ')) ) *q='-'; // replace ' ' with '-' while ( (q=strchr(p,'/')) ) *q='-'; XML_OUT( "<i18n key=\"os-%s\"/>", p ); break; case REP_SIZE: case REP_PROCTIME: n=array_index++; XML_OUT( "%f", opts->arraydata[rep-FIRST_ARRAYREP][n].threshold ); break; case REP_DOM: case REP_TYPE: // kludge: if the string supplied is delimited by square brackets, // we turn it into an i18n key. if ( *name=='[' && *(name+strlen(name)-1)==']' ) { p=strtolower(name+1); *(p+strlen(p)-1)=0; while ( (q=strchr(p,' ')) ) *q='-'; XML_OUT( "<i18n key=\"%s-%s\"/>", rep==REP_DOM?"domain":"type", p ); break; } // this is a delibrate fall-thru. default: XML_OUT( "<![CDATA[%s]]>", cleanprint(name) ); break; } XML_OUT( "</col>" ); } #if 0 extern char *workspace; choice savemultibyte; logical linked; int i; if (name1st != isfirst) return; if (isfirst) matchlengthn(outf, od, width - od->outputter->strlen(name), ' '); savemultibyte = od->multibyte; if (rep == REP_SIZE || rep == REP_PROCTIME) /* Kludge: for these two reports, we know the texts are things like "< 1" and we want to convert > and < */ od->multibyte = FALSE; strcpy(workspace, name); do_aliasx(workspace, aliashead); if (!isfirst) { if (rightalign) i = (int)width - (int)od->outputter->strlen(workspace) - (int)spaces; else i = (int)spaces; matchlengthn(outf, od, i, ' '); } linked = (linkhead != NULL && included(name, ispage, linkhead)); if (linked) { /* We link to the unaliased name, because the OUTPUTALIAS is usually in the nature of an annotation. */ fputs("<a href=\"", outf); if (baseurl != NULL) htmlputs(outf, od, baseurl, IN_HREF); // xml_escfprintf(outf, name); fputs("\">", outf); } htmlputs(outf, od, workspace, UNTRUSTED); if (linked) fputs("</a>", outf); if (isfirst) fputs(": ", outf); od->multibyte = savemultibyte; /* restore multibyte */ #endif }
/*** Remove any expired messages from boards unless force = 2 in which case just do a recount. ***/ void check_messages(UR_OBJECT user, int chforce) { RM_OBJECT rm; FILE *infp=NULL,*outfp=NULL; char id[182],fname[FNAME_LEN],line[82],rmname[ROOM_NAME_LEN+1]; int valid,pt,write_rest; int board_cnt,old_cnt,bad_cnt,tmp; static int done=0; set_crash(); switch (chforce) { case 0: if (amsys->mesg_check_hour==thour && amsys->mesg_check_min==tmin) { if (done) return; } else { done=0; return; } break; case 1: printf("Checking boards...\n"); case 2: if (word_count>=2) { strtolower(word[1]); if (strcmp(word[1],"motds")) { write_usage(user,"recount [motds]"); return; } if (!count_motds(1)) { write_user(user,"Sorry, could not recount the motds at this time.\n"); write_syslog(ERRLOG,1,"Could not recount motds in check_messages().\n"); return; } vwrite_user(user,"There %s %d login motd%s and %d post-login motd%s\n",PLTEXT_WAS(amsys->motd1_cnt),amsys->motd1_cnt,PLTEXT_S(amsys->motd1_cnt),amsys->motd2_cnt,PLTEXT_S(amsys->motd2_cnt)); write_syslog(SYSLOG,1,"%s recounted the MOTDS.\n",user->name); return; } } done=1; board_cnt=0; old_cnt=0; bad_cnt=0; for (rm=room_first; rm!=NULL; rm=rm->next) { tmp=rm->mesg_cnt; rm->mesg_cnt=0; if (rm->access==PERSONAL_LOCKED || rm->access==PERSONAL_UNLOCKED) { midcpy(rm->name,rmname,1,strlen(rm->name)-2); rmname[0]=toupper(rmname[0]); sprintf(fname,"%s/%s.B", USERROOMS,rmname); } else sprintf(fname,"%s/%s.B", ROOMFILES, rm->name); if (!(infp=fopen(fname,"r"))) continue; if (chforce<2) { if (!(outfp=fopen("tempfile","w"))) { if (chforce) write_syslog(ERRLOG, 1, "Lotos: Couldn't open tempfile.\n"); write_syslog(ERRLOG,1,"Couldn't open tempfile in check_messages().\n"); fclose(infp); return; } } board_cnt++; /* We assume that once 1 in date message is encountered all the others will be in date too , hence write_rest once set to 1 is never set to 0 again */ valid=1; write_rest=0; fgets(line,82,infp); /* max of 80+newline+terminator = 82 */ while (!feof(infp)) { if (*line=='\n') valid=1; sscanf(line,"%s %d",id,&pt); if (!write_rest) { if (valid && !strcmp(id,"PT:")) { if (chforce==2) rm->mesg_cnt++; else { /* 86400 = num. of secs in a day */ if ((int)time(0) - pt < amsys->mesg_life*86400) { fputs(line,outfp); rm->mesg_cnt++; write_rest=1; } else old_cnt++; } valid=0; } } else { fputs(line,outfp); if (valid && !strcmp(id,"PT:")) { rm->mesg_cnt++; valid=0; } } fgets(line,82,infp); } fclose(infp); if (chforce<2) { fclose(outfp); unlink(fname); if (!write_rest) unlink("tempfile"); else rename("tempfile",fname); } if (rm->mesg_cnt!=tmp) bad_cnt++; } switch (chforce) { case 0: if (bad_cnt) write_syslog(SYSLOG,1,"CHECK_MESSAGES: %d file%s checked, %d had an incorrect message count, %d message%s deleted.\n", board_cnt,PLTEXT_S(board_cnt),bad_cnt,old_cnt,PLTEXT_S(old_cnt)); else write_syslog(SYSLOG,1,"CHECK_MESSAGES: %d file%s checked, %d message%s deleted.\n",board_cnt,PLTEXT_S(board_cnt),old_cnt,PLTEXT_S(old_cnt)); break; case 1: printf(" %d board file%s checked, %d out of date message%s found.\n",board_cnt,PLTEXT_S(board_cnt),old_cnt,PLTEXT_S(old_cnt)); break; case 2: vwrite_user(user,"%d board file%s checked, %d had an incorrect message count.\n",board_cnt,PLTEXT_S(board_cnt),bad_cnt); write_syslog(SYSLOG,1,"%s forced a recount of the message boards.\n",user->name); } }
/** * Checks for common crop problems and reports them to ch. * * @param crop_data *cp The item to audit. * @param char_data *ch The person to report to. * @return bool TRUE if any problems were reported; FALSE if all good. */ bool audit_crop(crop_data *cp, char_data *ch) { extern adv_data *get_adventure_for_vnum(rmt_vnum vnum); extern struct icon_data *get_icon_from_set(struct icon_data *set, int type); extern const char *icon_types[]; struct interaction_item *inter; char temp[MAX_STRING_LENGTH]; bool problem = FALSE; bool harv, forage; adv_data *adv; int iter; adv = get_adventure_for_vnum(GET_CROP_VNUM(cp)); if (!GET_CROP_NAME(cp) || !*GET_CROP_NAME(cp) || !str_cmp(GET_CROP_NAME(cp), "Unnamed Crop")) { olc_audit_msg(ch, GET_CROP_VNUM(cp), "No name set"); problem = TRUE; } strcpy(temp, GET_CROP_NAME(cp)); strtolower(temp); if (strcmp(GET_CROP_NAME(cp), temp)) { olc_audit_msg(ch, GET_CROP_VNUM(cp), "Non-lowercase name"); problem = TRUE; } if (!GET_CROP_TITLE(cp) || !*GET_CROP_TITLE(cp) || !str_cmp(GET_CROP_TITLE(cp), "An Unnamed Crop")) { olc_audit_msg(ch, GET_CROP_VNUM(cp), "No title set"); problem = TRUE; } if (adv && !CROP_FLAGGED(cp, CROPF_NOT_WILD)) { olc_audit_msg(ch, GET_CROP_VNUM(cp), "Missing !WILD flag in adventure crop"); problem = TRUE; } if (!adv && CROP_FLAGGED(cp, CROPF_NOT_WILD)) { olc_audit_msg(ch, GET_CROP_VNUM(cp), "!WILD flag on non-adventure crop"); problem = TRUE; } if (GET_CROP_MAPOUT(cp) == 0) { // slightly magic-numbered olc_audit_msg(ch, GET_CROP_VNUM(cp), "Mapout color not set"); problem = TRUE; } for (iter = 0; iter < NUM_TILESETS; ++iter) { if (!get_icon_from_set(GET_CROP_ICONS(cp), iter)) { olc_audit_msg(ch, GET_CROP_VNUM(cp), "No icon for '%s' tileset", icon_types[iter]); problem = TRUE; } } if (GET_CROP_CLIMATE(cp) == CLIMATE_NONE) { olc_audit_msg(ch, GET_CROP_VNUM(cp), "Climate not set"); problem = TRUE; } if (!GET_CROP_SPAWNS(cp)) { olc_audit_msg(ch, GET_CROP_VNUM(cp), "No spawns set"); problem = TRUE; } harv = forage = FALSE; LL_FOREACH(GET_CROP_INTERACTIONS(cp), inter) { if (inter->type == INTERACT_HARVEST) { harv = TRUE; } else if (inter->type == INTERACT_FORAGE) { forage = TRUE; } } if (!harv) { olc_audit_msg(ch, GET_CROP_VNUM(cp), "No HARVEST"); problem = TRUE; } if (!forage) { olc_audit_msg(ch, GET_CROP_VNUM(cp), "No FORAGE"); problem = TRUE; } return problem; }
int lws_client_interpret_server_handshake(struct lws *wsi) { struct lws_context *context = wsi->context; int close_reason = LWS_CLOSE_STATUS_PROTOCOL_ERR; int n, len, okay = 0, isErrorCodeReceived = 0; const char *pc; char *p; #ifndef LWS_NO_EXTENSIONS const struct lws_extension *ext; char ext_name[128]; const char *c; int more = 1; void *v; #endif /* * well, what the server sent looked reasonable for syntax. * Now let's confirm it sent all the necessary headers */ if (lws_hdr_total_length(wsi, WSI_TOKEN_ACCEPT) == 0) { lwsl_info("no ACCEPT\n"); p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP); isErrorCodeReceived = 1; goto bail3; } p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP); if (!p) { lwsl_info("no URI\n"); goto bail3; } if (p && strncmp(p, "101", 3)) { lwsl_warn( "lws_client_handshake: got bad HTTP response '%s'\n", p); goto bail3; } p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE); if (!p) { lwsl_info("no UPGRADE\n"); goto bail3; } strtolower(p); if (strcmp(p, "websocket")) { lwsl_warn( "lws_client_handshake: got bad Upgrade header '%s'\n", p); goto bail3; } p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_CONNECTION); if (!p) { lwsl_info("no Connection hdr\n"); goto bail3; } strtolower(p); if (strcmp(p, "upgrade")) { lwsl_warn("lws_client_int_s_hs: bad header %s\n", p); goto bail3; } pc = lws_hdr_simple_ptr(wsi, _WSI_TOKEN_CLIENT_SENT_PROTOCOLS); if (!pc) { lwsl_parser("lws_client_int_s_hs: no protocol list\n"); } else lwsl_parser("lws_client_int_s_hs: protocol list '%s'\n", pc); /* * confirm the protocol the server wants to talk was in the list * of protocols we offered */ len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL); if (!len) { lwsl_info("lws_client_int_s_hs: WSI_TOKEN_PROTOCOL is null\n"); /* * no protocol name to work from, * default to first protocol */ wsi->protocol = &context->protocols[0]; goto check_extensions; } p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL); len = strlen(p); while (pc && *pc && !okay) { if (!strncmp(pc, p, len) && (pc[len] == ',' || pc[len] == '\0')) { okay = 1; continue; } while (*pc && *pc++ != ',') ; while (*pc && *pc == ' ') pc++; } if (!okay) { lwsl_err("lws_client_int_s_hs: got bad protocol %s\n", p); goto bail2; } /* * identify the selected protocol struct and set it */ n = 0; wsi->protocol = NULL; while (context->protocols[n].callback && !wsi->protocol) { if (strcmp(p, context->protocols[n].name) == 0) { wsi->protocol = &context->protocols[n]; break; } n++; } if (wsi->protocol == NULL) { lwsl_err("lws_client_int_s_hs: fail protocol %s\n", p); goto bail2; } check_extensions: #ifndef LWS_NO_EXTENSIONS /* instantiate the accepted extensions */ if (!lws_hdr_total_length(wsi, WSI_TOKEN_EXTENSIONS)) { lwsl_ext("no client extenstions allowed by server\n"); goto check_accept; } /* * break down the list of server accepted extensions * and go through matching them or identifying bogons */ if (lws_hdr_copy(wsi, (char *)context->serv_buf, sizeof(context->serv_buf), WSI_TOKEN_EXTENSIONS) < 0) { lwsl_warn("ext list from server failed to copy\n"); goto bail2; } c = (char *)context->serv_buf; n = 0; while (more) { if (*c && (*c != ',' && *c != ' ' && *c != '\t')) { ext_name[n] = *c++; if (n < sizeof(ext_name) - 1) n++; continue; } ext_name[n] = '\0'; if (!*c) more = 0; else { c++; if (!n) continue; } /* check we actually support it */ lwsl_ext("checking client ext %s\n", ext_name); n = 0; ext = lws_get_context(wsi)->extensions; while (ext && ext->callback) { if (strcmp(ext_name, ext->name)) { ext++; continue; } n = 1; lwsl_ext("instantiating client ext %s\n", ext_name); /* instantiate the extension on this conn */ wsi->active_extensions_user[ wsi->count_active_extensions] = lws_zalloc(ext->per_session_data_size); if (wsi->active_extensions_user[ wsi->count_active_extensions] == NULL) { lwsl_err("Out of mem\n"); goto bail2; } wsi->active_extensions[ wsi->count_active_extensions] = ext; /* allow him to construct his context */ ext->callback(lws_get_context(wsi), ext, wsi, LWS_EXT_CALLBACK_CLIENT_CONSTRUCT, wsi->active_extensions_user[ wsi->count_active_extensions], NULL, 0); wsi->count_active_extensions++; ext++; } if (n == 0) { lwsl_warn("Unknown ext '%s'!\n", ext_name); goto bail2; } n = 0; } check_accept: #endif /* * Confirm his accept token is the one we precomputed */ p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_ACCEPT); if (strcmp(p, wsi->u.hdr.ah->initial_handshake_hash_base64)) { lwsl_warn("lws_client_int_s_hs: accept %s wrong vs %s\n", p, wsi->u.hdr.ah->initial_handshake_hash_base64); goto bail2; } /* allocate the per-connection user memory (if any) */ if (lws_ensure_user_space(wsi)) { lwsl_err("Problem allocating wsi user mem\n"); goto bail2; } /* * we seem to be good to go, give client last chance to check * headers and OK it */ if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH, wsi->user_space, NULL, 0)) goto bail2; /* clear his proxy connection timeout */ lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0); /* free up his parsing allocations */ lws_free(wsi->u.hdr.ah); lws_union_transition(wsi, LWSCM_WS_CLIENT); wsi->state = LWSS_ESTABLISHED; wsi->rxflow_change_to = LWS_RXFLOW_ALLOW; /* * create the frame buffer for this connection according to the * size mentioned in the protocol definition. If 0 there, then * use a big default for compatibility */ n = wsi->protocol->rx_buffer_size; if (!n) n = LWS_MAX_SOCKET_IO_BUF; n += LWS_SEND_BUFFER_PRE_PADDING + LWS_SEND_BUFFER_POST_PADDING; wsi->u.ws.rx_user_buffer = lws_malloc(n); if (!wsi->u.ws.rx_user_buffer) { lwsl_err("Out of Mem allocating rx buffer %d\n", n); goto bail2; } lwsl_info("Allocating client RX buffer %d\n", n); if (setsockopt(wsi->sock, SOL_SOCKET, SO_SNDBUF, (const char *)&n, sizeof n)) { lwsl_warn("Failed to set SNDBUF to %d", n); goto bail3; } lwsl_debug("handshake OK for protocol %s\n", wsi->protocol->name); /* call him back to inform him he is up */ if (wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_ESTABLISHED, wsi->user_space, NULL, 0)) goto bail3; #ifndef LWS_NO_EXTENSIONS /* * inform all extensions, not just active ones since they * already know */ ext = context->extensions; while (ext && ext->callback) { v = NULL; for (n = 0; n < wsi->count_active_extensions; n++) if (wsi->active_extensions[n] == ext) v = wsi->active_extensions_user[n]; ext->callback(context, ext, wsi, LWS_EXT_CALLBACK_ANY_WSI_ESTABLISHED, v, NULL, 0); ext++; } #endif return 0; bail3: lws_free_set_NULL(wsi->u.ws.rx_user_buffer); close_reason = LWS_CLOSE_STATUS_NOSTATUS; bail2: if (wsi->protocol) { if (isErrorCodeReceived && p) { wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_CONNECTION_ERROR, wsi->user_space, p, (unsigned int)strlen(p)); } else { wsi->protocol->callback(wsi, LWS_CALLBACK_CLIENT_CONNECTION_ERROR, wsi->user_space, NULL, 0); } } lwsl_info("closing connection due to bail2 connection error\n"); /* free up his parsing allocations */ lws_free_set_NULL(wsi->u.hdr.ah); lws_close_free_wsi(wsi, close_reason); return 1; }
/* Check if a normal user can remove a message */ int check_board_wipe(UR_OBJECT user) { FILE *fp; int valid,cnt,msg_number,yes,pt; char w1[ARR_SIZE],w2[ARR_SIZE],line[ARR_SIZE],line2[ARR_SIZE],fname[FNAME_LEN],id[ARR_SIZE],rmname[ROOM_NAME_LEN+1]; RM_OBJECT rm; set_crash(); if (word_count<2) { write_usage(user,"wipe <message #>"); return 0; } rm=user->room; if (!rm->mesg_cnt) { write_user(user, no_message_prompt); return 0; } msg_number=atoi(word[1]); if (!msg_number) { write_usage(user,"wipe <#>"); return 0; } if (msg_number>rm->mesg_cnt) { vwrite_user(user,"There %s only %d message%s on the board.\n", PLTEXT_IS(rm->mesg_cnt),rm->mesg_cnt,PLTEXT_S(rm->mesg_cnt)); return 0; } if (rm->access==PERSONAL_LOCKED || rm->access==PERSONAL_UNLOCKED) { midcpy(rm->name,rmname,1,strlen(rm->name)-2); rmname[0]=toupper(rmname[0]); sprintf(fname,"%s/%s.B", USERROOMS,rmname); } else sprintf(fname,"%s/%s.B", ROOMFILES, rm->name); if (!(fp=fopen(fname,"r"))) { write_user(user,"There was an error trying to read message board.\n"); write_syslog(ERRLOG,1,"Unable to open message board for %s in check_board_wipe().\n",rm->name); return 0; } valid=1; cnt=1; yes=0; id[0]='\0'; w1[0]='\0'; w2[0]='\0'; fgets(line,ARR_SIZE-1,fp); while(!feof(fp)) { if (*line=='\n') valid=1; sscanf(line,"%s %d",id,&pt); if (valid && !strcmp(id,"PT:")) { line2[0]='\0'; strcpy(line2,remove_first(remove_first(line))); sscanf(line2,"%s %s",w1,w2); if (msg_number==cnt) { /* lower case the name incase of recapping */ strtolower(w2); w2[0]=toupper(w2[0]); if (!strcmp(w2,user->name)) { yes=1; goto SKIP; /* found result, no need to go through rest of file */ } } valid=0; cnt++; if (cnt>msg_number) goto SKIP; /* no point carrying on if checked already */ } fgets(line,ARR_SIZE-1,fp); } SKIP: fclose(fp); if (!yes) { write_user(user,"You did not post that message. Use ~FTbfrom~RS to check the number again.\n"); return 0; } user->wipe_from=msg_number; user->wipe_to=msg_number; return 1; }
NetworkServer* NetworkServer::init(const Config &conf, int num_readers, int num_writers){ static bool inited = false; if(inited){ return NULL; } inited = true; NetworkServer *serv = new NetworkServer(); if(num_readers >= 0){ serv->num_readers = num_readers; } if(num_writers >= 0){ serv->num_writers = num_writers; } { // server const char *ip = conf.get_str("server.ip"); int port = conf.get_num("server.port"); if(ip == NULL || ip[0] == '\0'){ ip = "127.0.0.1"; } serv->serv_link = Link::listen(ip, port); if(serv->serv_link == NULL){ log_fatal("error opening server socket! %s", strerror(errno)); fprintf(stderr, "error opening server socket! %s\n", strerror(errno)); exit(1); } // see UNP // if client send RST between server's calls of select() and accept(), // accept() will block until next connection. // so, set server socket nonblock. serv->serv_link->noblock(); log_info("server listen on %s:%d", ip, port); std::string password; password = conf.get_str("server.auth"); if(password.size() && (password.size() < 32 || password == "very-strong-password")){ log_fatal("weak password is not allowed!"); fprintf(stderr, "WARNING! Weak password is not allowed!\n"); exit(1); } if(password.empty()){ log_info(" auth : off"); }else{ log_info(" auth : on"); } serv->need_auth = false; if(!password.empty()){ serv->need_auth = true; serv->password = password; } } // init ip_filter { Config *cc = (Config *)conf.get("server"); if(cc != NULL){ std::vector<Config *> *children = &cc->children; std::vector<Config *>::iterator it; for(it = children->begin(); it != children->end(); it++){ if((*it)->key == "allow"){ const char *ip = (*it)->str(); log_info(" allow : %s", ip); serv->ip_filter->add_allow(ip); } if((*it)->key == "deny"){ const char *ip = (*it)->str(); log_info(" deny : %s", ip); serv->ip_filter->add_deny(ip); } } } } std::string readonly = conf.get_str("server.readonly"); strtolower(&readonly); if(readonly == "yes"){ serv->readonly = true; }else{ readonly = "no"; serv->readonly = false; } log_info(" readonly: %s", readonly.c_str()); return serv; }
/* Report title */ void xml_reporttitle(FILE *outf, Outchoices *od, choice rep) { char *dir; XML_TRACE(0); assert( ((char*)od-(char*)opts)==offsetof(Options,outopts) ); array_index=0; XML_OUT( XMLDBG"<report name=\"%s\">", strtolower(report_name[rep]) ); this_report=rep; switch (rep) { case REP_GENSUM: break; case REP_YEAR: case REP_QUARTERLY: case REP_MONTH: case REP_WEEK: case REP_DAYREP: case REP_HOURREP: case REP_QUARTERREP: case REP_FIVEREP: XML_OUT( XMLDBG "<rowlimit count=\"%d\"/>", opts->outopts.rows[rep] ); case REP_DAYSUM: case REP_HOURSUM: case REP_WEEKHOUR: case REP_QUARTERSUM: case REP_FIVESUM: // only time reports (for the time being) have a 'back' setting to set their sort-order. XML_OUT( XMLDBG "<sort dir=\"%s\" by=\"\"/>", od->back[rep]? "descending" : "ascending" ); break; case REP_SIZE: case REP_PROCTIME: case REP_HOST: case REP_REDIRHOST: case REP_FAILHOST: case REP_VHOST: case REP_REDIRVHOST: case REP_FAILVHOST: case REP_USER: case REP_REDIRUSER: case REP_FAILUSER: case REP_SEARCHREP: case REP_SEARCHSUM: case REP_INTSEARCHREP: case REP_INTSEARCHSUM: case REP_BROWSUM: case REP_CODE: od->subsortby[rep]= od->subfloor[rep].floorby=UNSET; case REP_TYPE: // the following reports can also have subfloor/sort setting case REP_DIR: case REP_REQ: case REP_REDIR: case REP_FAIL: case REP_DOM: case REP_REF: case REP_BROWREP: case REP_OS: case REP_REDIRREF: case REP_FAILREF: case REP_ORG: case REP_REFSITE: dir="ascending"; // analog will sort all of these in ascending order. XML_OUT( XMLDBG "<sort dir=\"%s\" by=\"%s\"/>", dir, od->sortby[rep]==UNSET?"":criteria[od->sortby[rep]] ); // 5.90b1 there's something funky going on with subsortby // 5.90b2 ? assert( od->subsortby[rep]==UNSET || (od->subsortby[rep]>=REQUESTS && od->subsortby[rep]<=METHOD_NUMBER) ); if ( od->sortby[rep]!=UNSET ) if ( od->subsortby[rep]!=UNSET ) // is this dependable ?? // XML_OUT( XMLDBG "<sort dir=\"%s\" by=\"%s\"/>", dir, criteria[od->subsortby[rep]] ); XML_OUT( XMLDBG "<sort dir=\"%s\" by=\"%u\"/>", dir, od->subsortby[rep] ); // the *FLOOR setting XML_OUT( XMLDBG "<floor level=\"%f\" ", od->floor[rep].min ); if ( od->floor[rep].qual ) XML_OUT( "qual=\"%c\" ", od->floor[rep].qual ); XML_OUT( "by=\"%s\"/>", od->floor[rep].floorby==UNSET?"":criteria[od->floor[rep].floorby] ); if ( od->subfloor[rep].floorby!=UNSET ) { XML_OUT( XMLDBG "<floor level=\"%f\" ", od->subfloor[rep].min ); // if ( od->subfloor[rep].qual ) XML_OUT( "qual=\"%c\" ", od->subfloor[rep].qual ) XML_OUT( "by=\"%s\"/>", criteria[od->floor[rep].floorby] ); } break; default: puts(report_name[rep]); assert(0); break; } }