Example #1
0
File: bti.c Project: thesues/bti
static int find_urls(const char *tweet, int **pranges)
{
	/*
	 * magic obtained from
	 * http://www.geekpedia.com/KB65_How-to-validate-an-URL-using-RegEx-in-Csharp.html
	 */
	static const char *re_magic =
	    "(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)/{1,3}"
	    "[0-9a-zA-Z;/~?:@&=+$\\.\\-_'()%]+)"
	    "(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?";
	pcre *re;
	const char *errptr;
	int erroffset;
	int ovector[10] = { 0, };
	const size_t ovsize = sizeof(ovector) / sizeof(*ovector);
	int startoffset, tweetlen;
	int i, rc;
	int rbound = 10;
	int rcount = 0;
	int *ranges = malloc(sizeof(int) * rbound);

	re = pcre_compile(re_magic,
			  PCRE_NO_AUTO_CAPTURE, &errptr, &erroffset, NULL);
	if (!re) {
		fprintf(stderr, "pcre_compile @%u: %s\n", erroffset, errptr);
		exit(1);
	}

	tweetlen = strlen(tweet);
	for (startoffset = 0; startoffset < tweetlen;) {

		rc = pcre_exec(re, NULL, tweet, strlen(tweet), startoffset, 0,
			       ovector, ovsize);
		if (rc == PCRE_ERROR_NOMATCH)
			break;

		if (rc < 0) {
			fprintf(stderr, "pcre_exec @%u: %s\n",
				erroffset, errptr);
			exit(1);
		}

		for (i = 0; i < rc; i += 2) {
			if ((rcount + 2) == rbound) {
				rbound *= 2;
				ranges = realloc(ranges, sizeof(int) * rbound);
			}

			ranges[rcount++] = ovector[i];
			ranges[rcount++] = ovector[i + 1];
		}

		startoffset = ovector[1];
	}

	pcre_free(re);

	*pranges = ranges;
	return rcount;
}
Example #2
0
/*
============
idStr::FindText

returns -1 if not found otherwise the index of the text
============
*/
int idStr::FindText( const char *str, const char *text, bool casesensitive, int start, int end ) {
	int l, i, j;

	if ( end == -1 ) {
		end = strlen( str );
	}
	l = end - strlen( text );
	for ( i = start; i <= l; i++ ) {
		if ( casesensitive ) {
			for ( j = 0; text[j]; j++ ) {
				if ( str[i+j] != text[j] ) {
					break;
				}
			}
		} else {
			for ( j = 0; text[j]; j++ ) {
				if ( ::toupper( str[i+j] ) != ::toupper( text[j] ) ) {
					break;
				}
			}
		}
		if ( !text[j] ) {
			return i;
		}
	}
	return -1;
}
static void panoMenderDuplicateScriptFile(char *scriptFileName, char *script, fullPath  *scriptPathName)
{
    FILE* scriptFD;
    int temp;
    
    strcpy(scriptPathName->name, scriptFileName);
      
    // Get a temp filename for the copy of the script
    if (panoFileMakeTemp(scriptPathName) == 0) {
        PrintError("Could not make Tempfile");
        exit(1);
    }
    
    // Copy the script
    if ((scriptFD = fopen(scriptPathName->name, "w")) == NULL) {
        PrintError("Could not open temporary Scriptfile");
        exit(1);
    }
    
    temp = fwrite(script, 1, (int) strlen(script), scriptFD); 
    
    if (strlen(script) != temp) {
        PrintError("Could not write temporary Scriptfile");
        exit(1);
    }
    
    fclose(scriptFD);
    
}
Example #4
0
char *osi_LogSaveString(osi_log_t *logp, char *s)
{
    char *saveplace;

    if (!logp) return s;

    if (!logp->enabled) return s;

    if (s == NULL) return NULL;

    thrd_EnterCrit(&logp->cs);

    saveplace = logp->stringsp[logp->stringindex];

    if (strlen(s) >= OSI_LOG_STRINGSIZE)
        StringCbPrintfA(saveplace, OSI_LOG_STRINGSIZE,
                        "...%s",
                        s + strlen(s) - (OSI_LOG_STRINGSIZE - 4));
    else
        StringCbCopyA(saveplace, OSI_LOG_STRINGSIZE, s);

    logp->stringindex++;

    if (logp->stringindex >= logp->maxstringindex)
        logp->stringindex = 0;

    thrd_LeaveCrit(&logp->cs);

    return saveplace;
}
Example #5
0
static int __init process_acpi_sdt_table(char *tab_sign, u32 *tab_data)
{
    struct vmm_devtree_node *node = vmm_devtree_getnode(VMM_DEVTREE_PATH_SEPARATOR_STRING
                                    VMM_DEVTREE_MOTHERBOARD_NODE_NAME);
    /* FIXME: First find if tab_size already exists. */
    struct vmm_devtree_node *cnode = vmm_devtree_addnode(node, tab_sign);

    vmm_devtree_dref_node(node);
    if (!strncmp(tab_sign, APIC_SIGNATURE, strlen(APIC_SIGNATURE))) {
        struct acpi_madt_hdr *madt_hdr;
        madt_hdr = (struct acpi_madt_hdr *)tab_data;
        if (acpi_populate_ioapic_devtree(madt_hdr, cnode) != VMM_OK)
            return VMM_EFAIL;

        if (acpi_populate_lapic_devtree(madt_hdr, cnode) != VMM_OK)
            return VMM_EFAIL;
    } else if (!strncmp(tab_sign, HPET_SIGNATURE, strlen(HPET_SIGNATURE))) {
        struct acpi_hpet hpet_chip, *hpet;
        int nr_hpet_blks, i;
        char hpet_nm[256];

        if (acpi_read_sdt_at(tab_data,
                             (struct acpi_sdt_hdr *)&hpet_chip,
                             sizeof(struct acpi_hpet),
                             HPET_SIGNATURE) < 0) {
            return VMM_EFAIL;
        }

        hpet = (struct acpi_hpet *)tab_data;
        nr_hpet_blks = (hpet->hdr.len - sizeof(struct acpi_sdt_hdr))
                       /sizeof(struct acpi_timer_blocks);

        vmm_devtree_setattr(cnode, VMM_DEVTREE_NR_HPET_ATTR_NAME,
                            &nr_hpet_blks, VMM_DEVTREE_ATTRTYPE_UINT32,
                            sizeof(nr_hpet_blks), FALSE);

        for (i = 0; i < nr_hpet_blks; i++) {
            memset(hpet_nm, 0, sizeof(hpet_nm));
            vmm_sprintf(hpet_nm, VMM_DEVTREE_HPET_NODE_FMT, i);
            struct vmm_devtree_node *nnode = vmm_devtree_addnode(cnode, hpet_nm);

            BUG_ON(nnode == NULL);

            if (vmm_devtree_setattr(nnode, VMM_DEVTREE_HPET_ID_ATTR_NAME,
                                    &hpet->tmr_blks[i].asid,
                                    VMM_DEVTREE_ATTRTYPE_UINT32,
                                    sizeof(hpet->tmr_blks[i].asid), FALSE) != VMM_OK) {
                return VMM_EFAIL;
            }

            if (vmm_devtree_setattr(nnode, VMM_DEVTREE_HPET_PADDR_ATTR_NAME,
                                    &hpet->tmr_blks[i].base, VMM_DEVTREE_ATTRTYPE_PHYSADDR,
                                    sizeof(physical_addr_t), FALSE) != VMM_OK) {
                return VMM_EFAIL;
            }
        }
    }

    return VMM_OK;
}
Example #6
0
/**
 * Test that sbuf_add_unum() successfully adds numbers.
 */
static void test_sbuf_add_unum(void)
{
	char nbuf[50];

	sbuf_reset(0);
	sprintf(nbuf, "%lu", ULONG_MAX);
	CU_ASSERT_EQUAL(0, sbuf_add_unum(ULONG_MAX, 0));
	CU_ASSERT_STRING_EQUAL(sbuf, nbuf);
	CU_ASSERT_EQUAL(offset, strlen(nbuf));

	sbuf_reset(0);
	sprintf(nbuf, "%lu", ULONG_MAX >> 1);
	CU_ASSERT_EQUAL(0, sbuf_add_unum(ULONG_MAX >> 1, 0));
	CU_ASSERT_STRING_EQUAL(sbuf, nbuf);
	CU_ASSERT_EQUAL(offset, strlen(nbuf));

	sbuf_reset(0);
	CU_ASSERT_EQUAL(0, sbuf_add_unum(1, 0));
	CU_ASSERT_STRING_EQUAL(sbuf, "1");
	CU_ASSERT_EQUAL(offset, 1);

	sbuf_reset(0);
	CU_ASSERT_EQUAL(0, sbuf_add_unum(0, 0));
	CU_ASSERT_STRING_EQUAL(sbuf, "0");
	CU_ASSERT_EQUAL(offset, 1);
}
Example #7
0
static void Backspace(txt_spincontrol_t *spincontrol)
{
    if (strlen(spincontrol->buffer) > 0)
    {
        spincontrol->buffer[strlen(spincontrol->buffer) - 1] = '\0';
    }
}
void disassemble(char* buf,
                 int buflen,
                 xed_decoded_inst_t* xedd,
                 xed_uint64_t runtime_instruction_address,
                 void* caller_data)
{
    int blen = buflen;
    if(xed_syntax)
    {
        blen = fn_disassemble_xed(XED_SYNTAX_XED, buf, blen,
                                  xedd, runtime_instruction_address,
                                  caller_data);
        if(att_syntax || intel_syntax)
            blen = xed_strncat(buf, " | ", blen);
    }
    if(att_syntax)
    {
        char* xbuf = buf + strlen(buf);
        blen = fn_disassemble_xed(XED_SYNTAX_ATT, xbuf, blen,
                                  xedd, runtime_instruction_address,
                                  caller_data);
        if(intel_syntax)
            blen = xed_strncat(buf, " | ", blen);
    }
    if(intel_syntax)
    {
        char* ybuf = buf + strlen(buf);
        blen = fn_disassemble_xed(XED_SYNTAX_INTEL, ybuf, blen,
                                  xedd, runtime_instruction_address,
                                  caller_data);
    }
}
Example #9
0
/*
 * Allocate workspace and open directory stream. If either one fails,
 * NULL will be returned.
 */
isc_result_t
isc_dir_open(isc_dir_t *dir, const char *dirname) {
	char *p;
	isc_result_t result;

	REQUIRE(dirname != NULL);
	REQUIRE(VALID_DIR(dir) && dir->search_handle == INVALID_HANDLE_VALUE);

	/*
	 * Copy directory name.  Need to have enough space for the name,
	 * a possible path separator, the wildcard, and the final NUL.
	 */
	if (strlen(dirname) + 3 > sizeof(dir->dirname))
		/* XXXDCL ? */
		return (ISC_R_NOSPACE);
	strcpy(dir->dirname, dirname);

	/*
	 * Append path separator, if needed, and "*".
	 */
	p = dir->dirname + strlen(dir->dirname);
	if (dir->dirname < p && *(p - 1) != '\\' && *(p - 1) != ':')
		*p++ = '\\';
	*p++ = '*';
	*p = '\0';

	/*
	 * Open stream.
	 */
	result = start_directory(dir);

	return (result);
}
Example #10
0
    /// Display the list of GMs
    static bool HandleGMListFullCommand(ChatHandler* handler, const char* /*args*/)
    {
        ///- Get the accounts with GM Level >0
        QueryResult result = RealmDB.Query("SELECT a.username,aa.gmlevel FROM account a, account_access aa WHERE a.id=aa.id AND aa.gmlevel > 0");
        if (result)
        {
            handler->SendSysMessage(LANG_GMLIST);
            handler->SendSysMessage("========================");
            ///- Cycle through them. Display username and GM level
            do
            {
                Field *fields = result->Fetch();
                const char* name = fields[0].GetCString();
                uint8 security = fields[1].GetUInt8();
                uint8 max = ((16 - strlen(name)) / 2);
                uint8 max2 = max;
                if (((max)+(max2)+(strlen(name))) == 16)
                    max2 = ((max)-1);
                if (handler->GetSession())
                    handler->PSendSysMessage("|    %s GMLevel %u", name, security);
                else
                    handler->PSendSysMessage("|%*s%s%*s|   %u  |", max, " ", name, max2, " ", security);
            }
            while (result->NextRow());

            handler->SendSysMessage("========================");
        }
        else
            handler->PSendSysMessage(LANG_GMLIST_EMPTY);
        return true;
    }
Example #11
0
static void frontend_psp_exec(const char *path, bool should_load_game)
{
#if defined(HAVE_KERNEL_PRX) || defined(IS_SALAMANDER)

   char argp[512];
   SceSize args = 0;

   argp[0] = '\0';
   strlcpy(argp, eboot_path, sizeof(argp));
   args = strlen(argp) + 1;

#ifndef IS_SALAMANDER
   if (should_load_game && g_extern.fullpath[0] != '\0')
   {
      argp[args] = '\0';
      strlcat(argp + args, g_extern.fullpath, sizeof(argp) - args);
      args += strlen(argp + args) + 1;
   }
#endif

   RARCH_LOG("Attempt to load executable: [%s].\n", path);

   exitspawn_kernel(path, args, argp);

#endif
}
void execmd(char input[])
{
		
                char *token;
                char *result[256];
               
		if(strstr(input,"cd")){
			printf("into cd command\n");
              		char *token = strtok(input," ");
              		token = strtok(NULL," ");
        	        if(chdir(token) < 0){
	                      perror("wrong directory");
	                }       

		}
		else{
		        token = strtok(input," ");
		        result[0] = (char*)malloc(strlen(token)+1);
			strcpy(result[0],token);
		        int i=1;
		        while(token=strtok(NULL," ")){
		               result[i]=(char *)malloc(strlen(token)+1);
		               strcpy(result[i],token);
		               i++;
		        }
		        result[i] = NULL;
			execvp(result[0],result);				
		}

 
}
Example #13
0
/*
 * At any point we should be able to construct an ascii representation of
 * the type descriptor. Including the variable references.
 */
str
getTypeName(malType tpe)
{
	char buf[PATHLENGTH], *s;
	size_t l = PATHLENGTH;
	int k;

	if (tpe == TYPE_any)
		return GDKstrdup("any");
	if (isaBatType(tpe)) {
		snprintf(buf, l, "bat[");
		l -= strlen(buf);
		s = buf + strlen(buf);
		k = getColumnIndex(tpe);
		if (k)
			snprintf(s, l, ":any%c%d]",TMPMARKER,  k);
		else if (getColumnType(tpe) == TYPE_any)
			snprintf(s, l, ":any]");
		else
			snprintf(s, l, ":%s]", ATOMname(getColumnType(tpe)));
		return GDKstrdup(buf);
	}
	if (isAnyExpression(tpe)) {
		strncpy(buf, "any", 4);
		if (isAnyExpression(tpe))
			snprintf(buf + 3, PATHLENGTH - 3, "%c%d",
					TMPMARKER, getColumnIndex(tpe));
		return GDKstrdup(buf);
	}
	return GDKstrdup(ATOMname(tpe));
}
Example #14
0
static void 
GrGetFontListWrapper(void *r)
{
	MWFONTLIST **list;
	int num;
	int i, ttlen, mwlen;

	GrGetFontList(&list, &num);

	GsWriteType(current_fd, GrNumGetFontList);

	/* the number of strings comming in */
	GsWrite(current_fd, &num, sizeof(int));

	if(num != -1) {
		for(i = 0; i < num; i++) {
			ttlen = strlen(list[i]->ttname) + 1;
			mwlen = strlen(list[i]->mwname) + 1;

			GsWrite(current_fd, &ttlen, sizeof(int));
			GsWrite(current_fd, list[i]->ttname, ttlen * sizeof(char));

			GsWrite(current_fd, &mwlen, sizeof(int));
			GsWrite(current_fd, list[i]->mwname, mwlen * sizeof(char));
		}
		
		GrFreeFontList(&list, num);
	}
}
static int get_event_num(char *path, char *index)
{
	struct dirent *dent;
	char *event_num_ptr;
	DIR *inputdir = NULL;

	inputdir = opendir(path);
	if (!inputdir) {
		printf("Error when opening search dir\n");
		return -1;
	}

	while ((dent = readdir(inputdir)) != NULL) {
		if (strcmp(dent->d_name, ".") == 0 ||
		    strcmp(dent->d_name, "..") == 0)
			continue;
		if (memcmp(dent->d_name, event_name, strlen(event_name)) == 0) {
			event_num_ptr = dent->d_name + strlen(event_name);
			*index = *event_num_ptr;
			return 0;
		} else {
			continue;
		}
	}

	return -1;

}
Example #16
0
void setup(void) {
  /*Zero the struct and set the versions and keyframe_granule_shift.*/
  daala_info_init(&di);
  di.pic_width = 176;
  di.pic_height = 144;
  di.pixel_aspect_numerator = 128;
  di.pixel_aspect_denominator = 117;
  di.timebase_numerator = 30000;
  di.timebase_denominator = 1001;
  di.frame_duration = 30;
  di.nplanes = 2;
  dd = daala_encode_create(&di);
  ck_assert(dd != NULL);
  daala_comment_init(&dc);
  dc.comments = 2;
  dc.user_comments = (char **)malloc(sizeof(*dc.user_comments)*2);
  ck_assert(dc.user_comments != NULL);
  dc.comment_lengths = (int *)malloc(sizeof(*dc.comment_lengths)*2);
  ck_assert(dc.comment_lengths != NULL);
  dc.user_comments[0] = make_string("COMMENT=Comment 0");
  ck_assert(dc.user_comments[0] != NULL);
  dc.comment_lengths[0] = strlen(dc.user_comments[0]);
  dc.user_comments[1] = make_string("COMMENT=Comment 1 (this one longer)");
  ck_assert(dc.user_comments[1] != NULL);
  dc.comment_lengths[1] = strlen(dc.user_comments[1]);
}
Example #17
0
unsigned char *EncryptXXTea::decode()
{
    UserData user_d = {10,20,30};
    unsigned char *t_data = (unsigned char *)&user_d;
    const  char *key_s = "YuanfeiTestXXTea";
    xxtea_long key_len = strlen(key_s);
    xxtea_long ret_len;
    unsigned char *bufs=xxtea_encrypt(t_data, sizeof(UserData), (unsigned char*)key_s, key_len, &ret_len);
    
    char t_buf[512];
    memset(&t_buf, 0, 512);
    memcpy(&t_buf, bufs, ret_len+1);
    
    key_s = "YuanfeiTestXXTea";
    key_len = strlen(key_s);
    xxtea_long de_len;
    unsigned char *de_data=xxtea_decrypt(bufs, ret_len, (unsigned char*)key_s, key_len, &de_len);
    memset(&t_buf, 0, 512);
    memcpy(&t_buf, de_data, ret_len+1);
    
    UserData decod;
    memset(&decod, 0, sizeof(UserData));
    memcpy(&decod, de_data, sizeof(UserData));
    return nullptr;

}
Example #18
0
static char *
get_prop_string_array(LibHalContext *hal_ctx, const char *udi, const char *prop)
{
    char **props, *ret, *str;
    int i, len = 0;

    props = libhal_device_get_property_strlist(hal_ctx, udi, prop, NULL);
    if (props) {
        for (i = 0; props[i]; i++)
            len += strlen(props[i]);

        ret = xcalloc(sizeof(char), len + i); /* i - 1 commas, 1 NULL */
        if (!ret) {
            libhal_free_string_array(props);
            return NULL;
        }

        str = ret;
        for (i = 0; props[i]; i++) {
            strcpy(str, props[i]);
            str += strlen(props[i]);
            *str++ = ',';
        }
        *(str-1) = '\0';

        libhal_free_string_array(props);
    }
    else {
        return NULL;
    }

    return ret;
}
Example #19
0
/**
 * Test that sbuf_add_snum() successfully adds numbers.
 */
static void test_sbuf_add_snum(void)
{
	char nbuf[50];

	sbuf_reset(0);
	sprintf(nbuf, "%ld", LONG_MAX);
	CU_ASSERT_EQUAL(0, sbuf_add_snum(LONG_MAX, 0));
	CU_ASSERT_STRING_EQUAL(sbuf, nbuf);
	CU_ASSERT_EQUAL(offset, strlen(nbuf));

	sbuf_reset(0);
	sprintf(nbuf, "%ld", -LONG_MAX);
	CU_ASSERT_EQUAL(0, sbuf_add_snum(-LONG_MAX, 0));
	CU_ASSERT_STRING_EQUAL(sbuf, nbuf);
	CU_ASSERT_EQUAL(offset, strlen(nbuf));

	sbuf_reset(0);
	CU_ASSERT_EQUAL(0, sbuf_add_snum(-1, 0));
	CU_ASSERT_STRING_EQUAL(sbuf, "-1");
	CU_ASSERT_EQUAL(offset, 2);

	sbuf_reset(0);
	CU_ASSERT_EQUAL(0, sbuf_add_snum(0, 0));
	CU_ASSERT_STRING_EQUAL(sbuf, "0");
	CU_ASSERT_EQUAL(offset, 1);
}
Example #20
0
void read_config_file(void)
{
    char *homedir;
    char *filename;
    FILE *file;
    char inputLine[1024];  /* hack: assume each line is less than 1024 chars */
    char *p;
    /* open $HOME/.tortoise */
    homedir = getenv("HOME");
    if (homedir == NULL)
        return;
    filename = (char *)malloc(strlen(homedir)
                              + strlen(CONFIGFILENAME)
                              + strlen(DIRECTORYSEPARATOR) + 1);
    if (filename == NULL)
        return;
    sprintf(filename, "%s%s%s", homedir, DIRECTORYSEPARATOR, CONFIGFILENAME);
    file = fopen(filename, "r");
    free(filename);
    if (file == NULL)
        return;
    /* spin through the file */
    while (1)
    {
        p = fgets(inputLine, sizeof(inputLine), file);
        if (p == NULL)
            break;
        gh_eval_str(p);
    }
    fclose(file);
}
Example #21
0
int main()
{
  char buf[BSZ];

  memset(buf, 'a', BSZ-2);
  buf[BSZ-2] = '\0';
  buf[BSZ-1] = 'X';
  FILE *fp = fmemopen(buf, BSZ, "w+");
  if (fp == NULL)
    err_exit("fmemopen failed");
  printf("initial buffer contents: %s\n", buf);
  fprintf(fp, "hello, world");
  printf("before flush: %s\n", buf);
  fflush(fp);
  printf("after fflush: %s\n", buf);
  printf("len of string in buf = %ld\n", (long)strlen(buf));

  memset(buf, 'b', BSZ-2);
  buf[BSZ-2] = '\0';
  buf[BSZ-1] = 'X';
  fprintf(fp, "hello, world");
  fseek(fp, 0, SEEK_SET);
  printf("after  fseek: %s\n", buf);
  printf("len of string in buf = %ld\n", (long)strlen(buf));

  memset(buf, 'c', BSZ-2);
  buf[BSZ-2] = '\0';
  buf[BSZ-1] = 'X';
  fprintf(fp, "hello, world");
  fclose(fp);
  printf("after fclose: %s\n", buf);
  printf("len of string in buf = %ld\n", (long)strlen(buf));

  return(0);
}
char * config_get_param (char *str) {
  char *ptr;
  int i;

  if (str == NULL) return NULL;
  /** empty string? */
  if (strlen(str) < 1 || str[0] == '\n' || strcmp(str, "\r\n") == 0) return NULL;

  ptr = str;

  /** comments? */
  if (str[0] == '#') return NULL;
  /** first alpha character */
  while (ptr != NULL && ! isalpha(*ptr))
    ptr++;

  /** overwrite alpha chars */
  memset(var_buf, '\0', sizeof(var_buf));
  i = 0;
  while(ptr != NULL && (isalnum(*ptr) || *ptr == '-')) {
    var_buf[i] = *ptr;
    i++;
    ptr++;
  }

  if (strlen(var_buf) < 1) return NULL;
  return var_buf;
}
Example #23
0
bool WebServer::authenticate(const char * username, const char * password)
{
  if(_autorization.length()>0)
  {
    String authReq = _autorization;
    if(authReq.startsWith("Basic")){
      authReq = authReq.substring(6);
      authReq.trim();
      char toencodeLen = strlen(username)+strlen(password)+1;
      char *toencode = new char[toencodeLen + 1];
      if(toencode == NULL){
        return false;
      }
      char *encoded = new char[base64_encode_expected_len(toencodeLen)+1];
      if(encoded == NULL){
        delete[] toencode;
        return false;
      }
      sprintf(toencode, "%s:%s", username, password);
      if(base64_encode_chars(toencode, toencodeLen, encoded) > 0 && authReq.equals(encoded)){
        delete[] toencode;
        delete[] encoded;
        return true;
      }
      delete[] toencode;
      delete[] encoded;
    }
  }
  return false;
}
char * config_get_value (char *str) {
  char *ptr;
  int i = 0;

  if (str == NULL) return NULL;
  if (strlen(str) < 1) return NULL;

  /** find '=' char */
  ptr = str;
  while (ptr != NULL && (*ptr) != '=')
    ptr++;
  ptr++;

  /** skip whitespaces **/
  while (ptr != NULL && ! isgraph(*ptr))
    ptr++;

  /** no value found? */
  if (ptr == NULL) return NULL;

  /** overwrite alpha chars */
  memset(val_buf, '\0', sizeof(val_buf));
  while(ptr != NULL && isgraph(*ptr)) {
    val_buf[i++] = *ptr;
    ptr++;
  }

  if (strlen(val_buf) < 1) return NULL;
  return val_buf;
}
Example #25
0
void ResourceManagerEntry(int argc, char ** argv) {
    // change process name
    char buf[16] = {0};
    prctl(PR_GET_NAME, buf);
    const char name[] = "-resource";
    strncat(buf, name, strlen(name));
    prctl(PR_SET_NAME, buf);
    strncat(argv[0], name, strlen(name));
    LOG(INFO) << "resource manager process begin: " << buf;
    ResourceMgr::Instance()->Init();
    // if temperory directory does not exist then create it
    if (access(FLAGS_work_directory.c_str(), F_OK) < 0)
        mkdir(FLAGS_work_directory.c_str(), S_IRWXU|S_IRWXG|S_IROTH);
    signal(SIGINT, SIG_DFL);
    pthread_t start_executor_t, resoure_info_t, control_executor_t;
    pthread_create(&start_executor_t, NULL, StartExecutorReceiver, NULL);
    pthread_create(&resoure_info_t, NULL, ResourceInfoSender, NULL);
    pthread_create(&control_executor_t, NULL, ExecutorControlReceiver, NULL);
    // wait pid for task execution finished
    pid_t pid;
    int status;
    while (true) {
        if ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
            LOG(ERROR) << "FFF" << pid;
            ContainerPool::ContainerFunc func = bind(&Container::ContainerFinished,
                                                     _1);
            // find the container and deal with the thing
            if(ContainerMgr::Instance()->FindToDo(pid, func))
                // remove the container since it has finished
                ContainerMgr::Instance()->Delete(pid);
        }
        sleep(1);
    }
} 
Example #26
0
static void Par_GetBoundary (void)
  {
   const char *PtrToBoundary;

   /*
   If data are received ==> the environment variable CONTENT_TYPE will hold:
   multipart/form-data; boundary=---------------------------7d13ca2e948
   Gbl.Boundary.StrWithCRLF will be set to:
			  "\r\n-----------------------------7d13ca2e948"
   I.e. 0x0D, 0x0A, '-', '-', and boundary.
   */
   /***** Get pointer to boundary string *****/
   PtrToBoundary = strstr (getenv ("CONTENT_TYPE"),"boundary=") + strlen ("boundary=");

   /***** Check that boundary string is not too long *****/
   if (2 + 2 + strlen (PtrToBoundary) > Par_MAX_BYTES_BOUNDARY_WITH_CR_LF)
      Lay_ShowErrorAndExit ("Delimiter string too long.");

   /***** Create boundary strings *****/
   snprintf (Gbl.Boundary.StrWithoutCRLF,sizeof (Gbl.Boundary.StrWithoutCRLF),
	     "--%s",
	     PtrToBoundary);
   snprintf (Gbl.Boundary.StrWithCRLF,sizeof (Gbl.Boundary.StrWithCRLF),
	     "%c%c%s",
	     0x0D,0x0A,Gbl.Boundary.StrWithoutCRLF);

   /***** Compute lengths *****/
   Gbl.Boundary.LengthWithoutCRLF = strlen (Gbl.Boundary.StrWithoutCRLF);
   Gbl.Boundary.LengthWithCRLF    = 2 + Gbl.Boundary.LengthWithoutCRLF;
  }
Example #27
0
/*
============
idStr::Replace
============
*/
void idStr::Replace( const char *old, const char *nw ) {
	int		oldLen, newLen, i, j, count;
	idStr	oldString( data );

	oldLen = strlen( old );
	newLen = strlen( nw );

	// Work out how big the new string will be
	count = 0;
	for( i = 0; i < oldString.Length(); i++ ) {
		if( !idStr::Cmpn( &oldString[i], old, oldLen ) ) {
			count++;
			i += oldLen - 1;
		}
	}

	if( count ) {
		EnsureAlloced( len + ( ( newLen - oldLen ) * count ) + 2, false );

		// Replace the old data with the new data
		for( i = 0, j = 0; i < oldString.Length(); i++ ) {
			if( !idStr::Cmpn( &oldString[i], old, oldLen ) ) {
				memcpy( data + j, nw, newLen );
				i += oldLen - 1;
				j += newLen;
			} else {
				data[j] = oldString[i];
				j++;
			}
		}
		data[j] = 0;
		len = strlen( data );
	}
}
Example #28
0
uint8_t *av_packet_pack_dictionary(AVDictionary *dict, int *size)
{
    AVDictionaryEntry *t = NULL;
    uint8_t *data = NULL;
    *size = 0;

    if (!dict)
        return NULL;

    while ((t = av_dict_get(dict, "", t, AV_DICT_IGNORE_SUFFIX))) {
        const size_t keylen   = strlen(t->key);
        const size_t valuelen = strlen(t->value);
        const size_t new_size = *size + keylen + 1 + valuelen + 1;
        uint8_t *const new_data = av_realloc(data, new_size);

        if (!new_data)
            goto fail;
        data = new_data;
        if (new_size > INT_MAX)
            goto fail;

        memcpy(data + *size, t->key, keylen + 1);
        memcpy(data + *size + keylen + 1, t->value, valuelen + 1);

        *size = new_size;
    }

    return data;

fail:
    av_freep(&data);
    *size = 0;
    return NULL;
}
Example #29
0
BOOL_ mygetline (BOOL_ required)
/* Lees een regel in
 * Plaats in buffer
 * Negeer lege regels en regels die beginnen met #
 */
{
    int
        i;

    for (;;) {
        if (fgets (buffer, BUFSIZE, fp) == NULL) {
            if (required)
                errit ("Unexpected end of file");
            else
                return FALSE;
        }
        inputline++;
        i = strlen (buffer);
        while (i && isspace ((unsigned char) buffer [i - 1]))
            buffer [--i] = '\0';
        i = 0;
        while (buffer [i] && isspace ((unsigned char) buffer [i]))
            i++;
        if (buffer [i] == '#')
            continue;
        if (buffer [i]) {
            memmove (buffer, buffer + i, strlen (buffer) + 1);
            return TRUE;
        }
    }
}
Example #30
0
static HV  *
plperl_spi_execute_fetch_result(SPITupleTable *tuptable, int processed,
								int status)
{
	HV		   *result;

	result = newHV();

	hv_store(result, "status", strlen("status"),
			 newSVpv((char *) SPI_result_code_string(status), 0), 0);
	hv_store(result, "processed", strlen("processed"),
			 newSViv(processed), 0);

	if (status == SPI_OK_SELECT)
	{
		AV		   *rows;
		SV		   *row;
		int			i;

		rows = newAV();
		for (i = 0; i < processed; i++)
		{
			row = plperl_hash_from_tuple(tuptable->vals[i], tuptable->tupdesc);
			av_push(rows, row);
		}
		hv_store(result, "rows", strlen("rows"),
				 newRV_noinc((SV *) rows), 0);
	}

	SPI_freetuptable(tuptable);

	return result;
}