Exemplo n.º 1
0
const char *
fs_mimetype_get_file_extension_from_filename(const char *filename)
{
	int err;
	unsigned int i, cnt, len;
	char buff[1024], **tab = NULL;
	
	if (filename == NULL || strlen(filename) == 0 || strlen(filename) > 1024)
		return (ERR_PARAM);
	
	if ((err = str_strip(filename, " \t\n\r", (char *)&buff)) != ERR_OK)
		return (err);
	
	if ((err = str_split(filename, ".", &cnt, &tab)) != ERR_OK)
		return (err);
	
	if (cnt > 1) {
		len = strlen(tab[cnt -1]);
		strncpy(&buff, (const char *)tab[cnt -1], len + 1);
		buff[len] = '\0';
	} else 
		*buff = '\0';
	
	strs_free(tab);
	
	return ((const char *)buff);
}
Exemplo n.º 2
0
static int read_from_text(const char *fpath_in, FILE *fout) {
    FILE *fin = fopen(fpath_in, "r");
    if (!fin) return -1;

    char buf[1024];

    while (fgets(buf, sizeof(buf), fin)) {
        if (!*buf || buf[strlen(buf)-1] != '\n') continue;
        char *name = str_strip(buf);
        if (!*name) continue;

        rec_t rec;
        snprintf(rec.name, sizeof(rec.name), "%s", name);
        rec.name_len = strlen(rec.name);

        if (fwrite(&rec, sizeof(rec), 1, fout) != 1) {
            fclose(fin);
            return -1;
        }
    }

    fclose(fin);

    return 0;
}
Exemplo n.º 3
0
Arquivo: config.c Projeto: CingHu/code
bool
load_proxy_config()
{
	if (file_exist(PROXY_CONF)) {

		int i;
		char *line;
		string_list_t *lines;

		lines = sl_load_file(PROXY_CONF);
		if (lines == NULL) {
			fprintf(stderr, "Could not load file %s: %s", PROXY_CONF, strerror(errno));
			return false;
		}

		for (i = 0; i < lines->count; i++) {
			line = str_strip(lines->data[i]);
			if (*line) {
				sl_append(Config.proxy_list, strdup(line));
			}
		}

		string_list_free(lines);

		if (Config.proxy_list->count == 0) {
			fprintf(stderr, "%s has no proxy servers", PROXY_CONF);
			return false;
		}

	} else {
		sl_append(Config.proxy_list, strdup(HOST));
	}

	return true;
}
Exemplo n.º 4
0
static const response* init(void)
{
  const char* path;
  str rule = {0,0,0};
  ibuf in;
  const response* r;
  
  if ((path = getenv("MAILRULES")) == 0) return 0;
  loaded = 1;

  if (!ibuf_open(&in, path, 0)) return &resp_erropen;
  while (ibuf_getstr(&in, &rule, LF)) {
    str_strip(&rule);
    if (rule.len == 0) continue;
    if (rule.s[0] == ':') {
      switch (rule.s[1]) {
      case 's': current_rules = &sender_rules; break;
      case 'r': current_rules = &recip_rules; break;
      default: return &resp_syntax;
      }
    }
    else if ((r = add(rule.s)) != 0)
      return r;
  }
  ibuf_close(&in);
  str_free(&rule);
  return 0;
}
Exemplo n.º 5
0
/* read a string from socket. returns malloc()ed buffer with
 \n\r stripped, or NULL on error */
char *Recv (int sock)
{
    char         buf[1024], *p, *result;
    int          n;

reconsider:
    /* see if we already have string ready in the buffer */
    if (leftover != NULL)
    {
        p = strchr (leftover, '\n');
        if (p != NULL)
        {
            *p = '\0';
            result = strdup (leftover);
            str_strip (result, "\r\n");
            memmove (leftover, p+1, strlen(p+1)+1);
            return result;
        }
    }

    n = recv (sock, buf, sizeof(buf)-1, 0);
    /* check for error reading from socket. note that we discard something
     which could still be in the leftover buffer: every valid input line must
     be terminated with \n */
    if (n <= 0)
    {
        if (leftover != NULL) free (leftover);
        leftover = NULL;
        Close (sock);
        return NULL;
    }
    /* we got something */
    buf[n] = '\0';

    /* check if buffer contains NULLs. if yes we are getting some binary data,
     and this is BAD THING */
    if (n != strlen (buf))
    {
        if (leftover != NULL) free (leftover);
        leftover = NULL;
        Close (sock);
        return NULL;
    }

    /* if leftover is present, we concatenate it with recent input and then
     consider result. otherwise we copy the input to leftover and again
     proceed to buffer re-examination */
    if (leftover != NULL)
    {
        p = str_join (leftover, buf);
        free (leftover);
        leftover = p;
    }
    else
    {
        leftover = strdup (buf);
    }
    goto reconsider;
}
Exemplo n.º 6
0
///////////////////////////////////////////////////////////////////////////////
/// @fn time_t str_to_time(string date)
/// @brief returns a time_t object made from the passed in string
/// @param date is a string in the format MM/DD/YYYY to turn into a time_t
/// @ret time_t ojbect made from the passed in date
///////////////////////////////////////////////////////////////////////////////
time_t validate::str_to_time(string date) {

  // Storage for what we return.
  time_t return_time;

  // Store the current time, too.
  time_t now;
  time(&now);

  // Current tm, too.
  tm now_tm;
  // Yeah, I'm dereferencing a function.
  now_tm = *localtime(&now);

  // tm structure for easier storage.
  // Initialize to "now" for day/month/year, if any are missing.
  tm date_tm(now_tm);

  // We don't need these three values.
  date_tm.tm_hour = 0;
  date_tm.tm_min = 0;
  date_tm.tm_sec = 0;

  // Clear out any ambiguity.
  date = str_strip(date, " ", true, true, true);
  date = str_replace_all(date, "-", "/");
  date = str_replace_all(date, ".", "/");
  date = str_replace_all(date, "\\", "/");
  date = str_replace_all(date, "|", "/");
  date = str_replace_all(date, "_", "/");

  vector<string> values = str_find_lines(date, "/", false);

  if (values.size() >= 1) {

    // tm stores months as 0-11
    date_tm.tm_mon = str_to_int(values[0]) - 1;

  }

  if (values.size() >= 2) {

    date_tm.tm_mday = str_to_int(values[1]);

  }

  if (values.size() >= 3) {

    // tm stores years as the distance from 1900
    date_tm.tm_year = str_to_int(values[2]) - 1900;

  }

  return_time = mktime(&date_tm);

  return return_time;

}
Exemplo n.º 7
0
void load_menu (void)
{
    char    menu_filename[1024], *language;
    
    // find out what language user wants
    if (options.english_menu || cmdline.english)
    {
        language = "english";
    }
    else
    {
        language = cfg_get_string (CONFIG_NFTP, fl_opt.platform_nick, "language");
        str_strip (language, " ");
    }

    // Try $user_libpath directory
    snprintf1 (menu_filename, sizeof (menu_filename),
               "%s/nftp.mnu", paths.user_libpath);
    if (access (menu_filename, R_OK) == 0) goto Found;

    // Try $system_libpath directory
    snprintf1 (menu_filename, sizeof (menu_filename),
               "%s/nftp.mnu", paths.system_libpath);
    if (access (menu_filename, R_OK) == 0) goto Found;

    // Try current directory
    strcpy (menu_filename, "nftp.mnu");
    if (access (menu_filename, R_OK) == 0) goto Found;

    /*
    if (strcmp (language, "english") != 0)
    {
        if (fl_opt.has_console && !fl_opt.initialized)
            fly_ask_ok (0, "Failed to load \"%s.mnu\", trying English.\n", language);
        language = "english";
        goto Rescan;
    }
    */

    fly_error ("Failed to load \"nftp.mnu\".");

Found:

    if (main_menu != NULL)
    {
        menu_unload (main_menu);
    }
    
    if (fl_opt.has_console && !fl_opt.initialized)
        fly_ask_ok (0, "loading %s......\n", menu_filename);
    main_menu = menu_load (menu_filename, options.keytable,
                           sizeof(options.keytable)/sizeof(options.keytable[0]));
}
Exemplo n.º 8
0
struct cgi * init_cgi_table() {
    char buf[BUFFER_SIZE], key[BUFFER_SIZE], val[BUFFER_SIZE];
    struct cgi *ptr = 0, *root = 0;
    FILE *fp = fopen("cgi.conf","r");

    memset(buf, 0, sizeof buf);

    if(fp==0) {
        fprintf(stderr, "Cannot open cgi.conf\n");
        fclose(fp);
        return 0;
    }

    while(fgets(buf, BUFFER_SIZE, fp)!=0) {
        str_strip(buf);
        if(strcmp("[CGI]", buf)!=0) {
            return 0;
        }
        int i;
        if(ptr==0) {
            ptr = (struct cgi*) malloc(sizeof(struct cgi));
            root = ptr;
        } else {
            ptr->next = (struct cgi*) malloc(sizeof(struct cgi));
            ptr = ptr->next;
        }
        ptr->next = 0;
        for(i=0;i<2;i++) {
            if(fgets(buf, BUFFER_SIZE, fp)==0) {
                free(ptr);
                return 0;
            }
            sscanf(buf, "%s %s", key, val);

            if(strcmp("EXTNAME", key)==0) {
                ptr->ext = (char*) malloc(sizeof(char) * (strlen(val)+1));
                memset(ptr->ext, 0, sizeof(char) * (strlen(val)+1));
                strncat(ptr->ext, val, strlen(val));
            } else if(strcmp("CMD", key)==0) {
                ptr->cmd = (char*) malloc(sizeof(char) * (strlen(val)+1));
                memset(ptr->cmd, 0, sizeof(char) * (strlen(val)+1));
                strncat(ptr->cmd, val, strlen(val));
            }
            memset(buf, 0, sizeof buf);
        }
    }

    fclose(fp);
    return root;    
}
Exemplo n.º 9
0
/*
 * Particularly yahoo puts links like this in mails:
 * http:/ /mail.yahoo.com
 * So first step: delete space between / /
 *
 * Next there could be possible links like this:
 * <a href="phishlink">w  w w . e b a y . c o m</a>
 * Here we need to strip spaces to get this picked up.
 *
 * Next there are links like:
 * <a href="www.yahoo.com">Check out yahoo.com</a>
 * Here we add a ., so we get: check.out.yahoo.com (it won't trigger)
 *
 * Old Rule for adding .: if substring from right contains dot, then add dot,
 *	otherwise strip space
 * New Rule: strip all spaces
 *  strip leading and trailing garbage
 *
 */
static void
str_fixup_spaces(char **begin, const char **end)
{
	char* sbegin = *begin;
	const char* send = *end;
	if(!sbegin || !send || send < sbegin)
		return;
	/* strip spaces */
	str_strip(&sbegin, &send, " ",1);
	/* strip leading/trailing garbage */
	while(!isalnum(sbegin[0]) && sbegin <= send) sbegin++;
	while(!isalnum(send[0]) && send >= sbegin) send--;
	*begin = sbegin;
	*end = send;
}
Exemplo n.º 10
0
/* CONFIG */
static __inline int
cfg_parse_line(const char *line, cfg_var_t  **varp)
{        
        int err;
        unsigned int cnt;
        char **tab;
        
        if ((err = str_split(line, "=", &cnt, &tab)) != ERR_OK)
		return (err);
	
	if (cnt == 2) {
		if ((err = cfg_var_init(varp)) == ERR_OK) {
			str_strip(tab[0], " \t\n", (*varp)->name);
			str_strip(tab[1], " \t\n", (*varp)->value);
			//fprintf(stderr, "'%s' = '%s'\n", (*varp)->name, (*varp)->value);
		}
	} else {
		err = ERR_INVALID;
	}
        
	//strs_free(tab);
	
	return (err);
}
Exemplo n.º 11
0
int hdr_add (char *format, ...)
{
    char     buffer[32768], *p;
    va_list  args;

    va_start (args, format);
    vsnprintf1 (buffer, sizeof(buffer), format, args);
    va_end (args);
    /* trying to avoid strings with \r or \n at the end which
     will cause malformed headers */
    str_strip (buffer, "\r\n");

    p = strdup (buffer);
    if (p == NULL) return -1;

    return hdr_addraw (p);
}
Exemplo n.º 12
0
/*
 * Particularly yahoo puts links like this in mails:
 * http:/ /www.example.com
 * So first step: delete space between / /
 *
 * Next there could be possible links like this:
 * <a href="phishlink">w  w w . e b a y . c o m</a>
 * Here we need to strip spaces to get this picked up.
 *
 * Next there are links like:
 * <a href="www.yahoo.com">Check out yahoo.com</a>
 * Here we add a ., so we get: check.out.yahoo.com (it won't trigger)
 *
 * Old Rule for adding .: if substring from right contains dot, then add dot,
 *	otherwise strip space
 * New Rule: strip all spaces
 *  strip leading and trailing garbage
 *
 */
static void
str_fixup_spaces(char **begin, const char **end)
{
	char* sbegin = *begin;
	const char* send = *end;
	if(!sbegin || !send || send < sbegin)
		return;
	/* strip spaces */
	str_strip(&sbegin, &send, " ",1);
	/* strip leading/trailing garbage */
	while(!isalnum(sbegin[0]&0xff) && sbegin <= send) sbegin++;
	while(!isalnum(send[0]&0xff) && send >= sbegin) send--;

	/* keep terminating slash character*/
	if(send[1] == '/') send++;
	*begin = sbegin;
	*end = send;
}
Exemplo n.º 13
0
int dict_load_list(dict* d, const char* filename, int mustexist,
		   int (*xform)(str*))
{
  ibuf in;
  str tmp = {0,0,0};
  int result = 1;
  
  if (!dict_init(d)) return 0;
  if (!ibuf_open(&in, filename, 0)) return !mustexist;
  while (ibuf_getstr(&in, &tmp, '\n')) {
    str_strip(&tmp);
    if (tmp.len > 0 && tmp.s[0] != '#') {
      if (xform != 0) if (!xform(&tmp)) { result = 0; break; }
      if (!dict_add(d, &tmp, 0)) { result = 0; break; }
    }
  }
  str_free(&tmp);
  ibuf_close(&in);
  return result;
}
Exemplo n.º 14
0
int hdr_set_response (int code, char *format, ...)
{
    char     buffer[32768], *p;
    va_list  args;

    if (code < 100 || code > 999) return -1;

    va_start (args, format);
    vsnprintf1 (buffer, sizeof(buffer), format, args);
    va_end (args);
    str_strip (buffer, "\r\n");

    p = strdup (buffer);
    if (p == NULL) return -1;

    reply.resp = code;
    reply.response = p;

    return 0;
}
Exemplo n.º 15
0
/**
 * @details Removes leading and trailing whitespace from every entry
 *          of a Ledger object. Specifically, str_strip is called on
 *          every character string in the "entries" member array of the
 *          Ledger object.
 */
err_t strip_ledger(Ledger *ledger){
  int i, j;
  
  /* Check for NULL input */
  
  if(ledger == NULL)
    return LFAILURE;

  if(ledger->entries == NULL)
    return LSUCCESS;

  /* Call str_strip to remove the leading and trailing whitespace from every entry */

  for(i = 0; i < NFIELDS; ++i)
    for(j = 0; j < ledger->nrows; ++j)
      if(str_strip(ledger->entries[i][j]) == LFAILURE)
        return LFAILURE;
  
  return LSUCCESS;
}
Exemplo n.º 16
0
// .c file
void main(void)
{
	dict *inif[HASHSIZE] = {}; // initialized to NULL 	
	dict *dirs;
	char *dir = str_init(), *d_cpy = str_init();
	char *files[256] = {};
	
	parse_conf(inif, INIFILE);
	dirs = lookup(inif, DIRECT);		
	dir = strtok(dirs->defn, DELIM);
	
	while (dir != NULL) {
		strcpy(d_cpy, dir);
		strcat(d_cpy, BUILD_PATH);
		str_strip(d_cpy);
		ls_dir(files, d_cpy);	   // List files
		
		/*
			do parse here
		*/
		
		dir = strtok(NULL, DELIM); // for each until no more delimiters
	}
}
Exemplo n.º 17
0
int
fsd_conf_init(const char *filepath, fsd_conf_t **cfgp)
{
	int err, debug, base, port;
	unsigned int cnt;
	cfg_t *mcfg = NULL;
	fs_log_t *log = NULL;
	char value[CFG_VALUE_LEN_MAX], host[128], path[256], logfile[256];
	uint64_t salt;
	
	err = fs_log_init(NULL, &log);
	
	if (err == ERR_OK && (err = cfg_init(&mcfg)) != ERR_OK)
		fs_error(log, "[ CONFIG ] Cannot initialize 'cfg'");
	
	if (err == ERR_OK && (err = cfg_read_file(mcfg, filepath)) != ERR_OK) {
		if (filepath != NULL)
			fs_error(log, "[ CONFIG ] Cannot load config file '%s'", filepath);
	}
	
	if (err == ERR_OK && (*cfgp = malloc(sizeof(fsd_conf_t))) == NULL)
		err = ERR_MEMORY;
	
	/* Checking for debug variable */
	if (err == ERR_OK && (err = cfg_get(mcfg, "debug", (char *)&value)) != ERR_OK)
		fs_error(log, "[ CONFIG ] Cannot find 'debug' variable in config file");
	
	if (err == ERR_OK && (err = str2int(value, &debug)) != ERR_OK)
		fs_error(log, "[ CONFIG ] Invalid Type of 'debug' = '%s'. Cardinal is required", value);
	
	if (err == ERR_OK)
		(*cfgp)->debug = debug;
	
	/* Checking for port variable */
	if (err == ERR_OK && (err = cfg_get(mcfg, "port", (char *)&value)) != ERR_OK)
		fs_error(log, "[ CONFIG ] Cannot find 'port' variable in config file");

	if (err == ERR_OK && (err = str2int(value, &port)) != ERR_OK)
		fs_error(log, "[ CONFIG ] Invalid Type of 'port' = '%s'. Cardinal is required", value);
	
	if (err == ERR_OK && (port < 2 || port > (1 << 16))) {
		fs_error(log, "[ CONFIG ] variable 'port' = %d is out of range <1, %d>", port, (1 << 16));
		err = ERR_CONFIG;
	}
	
	if (err == ERR_OK)
		(*cfgp)->port = (uint16_t)port;
	
	/* Checking for host variable */
	if (err == ERR_OK && (err = cfg_get(mcfg, "host", (char *)&host)) != ERR_OK)
		fs_error(log, "[ CONFIG ] Cannot find 'host' variable in config file");
	
	if (err == ERR_OK)
		strncpy((*cfgp)->host, host, strlen(host) + 1);
	
	/* Checking for path variable */
	if (err == ERR_OK && (err = cfg_get(mcfg, "path", (char *)&path)) != ERR_OK)
		fs_error(log, "[ CONFIG ] Cannot find 'path' variable in config file");
	
	if (err == ERR_OK && !fs_dir_exist(path)) {
		fs_error(log, "[ CONFIG ] 'path' = '%s' not exist or no permission", path);
		err = ERR_FILESYSTEM;
	}
	
	if (err == ERR_OK)
		strncpy((*cfgp)->path, path, strlen(path) + 1);
	
	/* Checking for logfile variable */
	if (err == ERR_OK && cfg_get(mcfg, "logfile", (char *)&logfile) == ERR_OK) {
		strncpy((char *)&(*cfgp)->logfile, logfile, strlen(logfile) + 1);
		(*cfgp)->logfile[strlen(logfile)] = '\0';
	} else if (err == ERR_OK) {
		(*cfgp)->logfile[0] = '\0';
	}
	
	/* Checking for salt variable */
	if (err == ERR_OK && cfg_get(mcfg, "salt", (char *)&value) == ERR_OK) {
		if (err == ERR_OK && (err = str2uint64_t(value, &salt)) != ERR_OK)
			fs_error(log, "[ CONFIG ] Invalid Type of 'salt' = '%s'. Long cardinal is required", value);
		else
			(*cfgp)->salt = salt;
	} else 
		(*cfgp)->salt = FS_DEFAULT_SALT;
		
	/* Checking for base variable */
	if (err == ERR_OK && cfg_get(mcfg, "base", (char *)&value) == ERR_OK) {
		if (err == ERR_OK && (err = str2int(value, &base)) != ERR_OK)
			fs_error(log, "[ CONFIG ] Invalid Type of 'base' = '%s'. Cardinal is required", value);
		else {
			if (err == ERR_OK && (base < 2 || base > 62)) {
				fs_error(log, "[ CONFIG ] variable 'base' = %d is out of range <2, 62>", base);
				err = ERR_CONFIG;
			} else 
				(*cfgp)->base = (uint8_t)base;
		}			
	} else
		(*cfgp)->base = FS_DEFAULT_BASE;
	
	/* Checking form allowed_ips variable*/
	cnt = 0;
	if (err == ERR_OK && cfg_get(mcfg, "allowed_ips", (char *)&value) == ERR_OK) {
		if (str_split(value, ",", &cnt, &((*cfgp)->allowed_ips)) == ERR_OK) {
			for (unsigned int j = 0; j < cnt; j++) {
				str_strip((*cfgp)->allowed_ips[j], " \n\t", (char *)&value);
				strncpy((*cfgp)->allowed_ips[j], value, strlen(value));
				(*cfgp)->allowed_ips[j][strlen(value)] = '\0';
			}
		}
	}
	
	if (err == ERR_OK)
		(*cfgp)->allowed_ips_cnt = cnt;
	
	cfg_fini(mcfg);
	fs_log_fini(log);
	
	return (err);
}
/**
 * @details Print a summary of a Ledger object to a file stream.
 *          Set usecolor to 1 to print with command line interface 
 *          color codes defined in the Printing_Macros module. 
 *          Set usecolor to 0 to not use these color codes.
 */
err_t print_summary_to_string(Ledger *ledger, char **s, int usecolor){
  int i, j, l0, l1, l2, any = 0, anyp = 0, nullp;
  char norm[64]; 

  /* Check for bad input */
    
  if(ledger == NULL){
    printf("Ledger is empty.\n");
    return LFAILURE;
  }  
    
  if(ledger->nrows < 1){
    printf("Ledger is empty.\n");
    return LFAILURE;
  }
 
  if(untotaled(ledger) == LYES){
     printf("Account totals have not been calculated. Ledger may be empty.\n");  
     return LFAILURE; 
  }
  
  /* Allocate space for string and test if calloc worked */
    
  *s = calloc((ledger->nrows + 1) * NFIELDS * LINESIZE, sizeof(char));
  if(*s == NULL){
    fprintf(stderr, "Error: calloc failed.\n");
    return LFAILURE;
  }

  /* Print summary to string */

  strncpy(norm, usecolor ? NORMAL_COLOR : "", 63 * sizeof(char));

  /* Print summaries of credit accounts */

  for(i = 0; i < ledger->ncredits; ++i){
    l0 = (small_norm(ledger->credit_totals[i][I_NOT_THERE_YET]) == LNO);
    l1 = (small_norm(ledger->credit_totals[i][I_PENDING]) == LNO);
    l2 = (small_norm(ledger->credit_totals[i][I_CLEARED]) == LNO);
 
    if(l0 || l1 || l2 || (PRINT_EMPTY_ACCOUNTS && strlen(ledger->credits[i]))){
      ++any;
      if(strlen(ledger->credits[i]))
        snprintf(*s, LINESIZE * sizeof(char),"%s\nCredit account: %s\n\n", *s, ledger->credits[i]);
      else
        snprintf(*s, LINESIZE * sizeof(char),"%s\nCredit account with no name:\n\n", *s);
 
      if(l0 || l1){
      
        snprintf(*s, LINESIZE * sizeof(char),"%s          Delayed money:\n", *s);
        if(l0)
          snprintf(*s, LINESIZE * sizeof(char),"%s%s%30.2f%s  not arrived\n", *s, 
                  color(ledger->credit_totals[i][I_NOT_THERE_YET], usecolor), 
                  ledger->credit_totals[i][I_NOT_THERE_YET], usecolor ? norm : ""); 
        if(l1)
          snprintf(*s, LINESIZE * sizeof(char),"%s%s%30.2f%s  pending\n", *s, 
                  color(ledger->credit_totals[i][I_PENDING], usecolor), 
                  ledger->credit_totals[i][I_PENDING], norm);

        snprintf(*s, LINESIZE * sizeof(char), "%s\n          Balances:\n", *s);
        snprintf(*s, LINESIZE * sizeof(char),"%s%s%30.2f%s  \"available\"\n", *s, 
                color(ledger->credit_totals[i][I_CLEARED], usecolor),
                ledger->credit_totals[i][I_CLEARED], norm);
        if(l1 && l0)
          snprintf(*s, LINESIZE * sizeof(char),"%s%s%30.2f%s  pending balance\n", *s,
                  color(ledger->credit_totals[i][I_PENDING_BAL], usecolor),
                  ledger->credit_totals[i][I_PENDING_BAL],
                  norm);
        snprintf(*s, LINESIZE * sizeof(char),"%s%s%30.2f%s  true balance\n", *s, 
                color(ledger->credit_totals[i][I_OVERALL_BAL], usecolor),
                ledger->credit_totals[i][I_OVERALL_BAL], norm);
      } else {
        snprintf(*s, LINESIZE * sizeof(char), "%s          Balances:\n", *s);
        snprintf(*s, LINESIZE * sizeof(char), "%s%s%30.2f%s  true balance\n", *s, 
                color(ledger->credit_totals[i][I_OVERALL_BAL], usecolor), 
                ledger->credit_totals[i][I_OVERALL_BAL], norm); 
        snprintf(*s, LINESIZE * sizeof(char), "%s                                All charges cleared.\n", *s);
      }
    }
  }     

  /* Print summaries of bank accounts */
        
  for(i = 0; i < ledger->nbanks; ++i){
    l0 = (small_norm(ledger->bank_totals[i][I_NOT_THERE_YET]) == LNO);
    l1 = (small_norm(ledger->bank_totals[i][I_PENDING]) == LNO);
    l2 = (small_norm(ledger->bank_totals[i][I_CLEARED]) == LNO) ||      
         filled_partitions(ledger, i); 
  
    if(l0 || l1 || l2 || (PRINT_EMPTY_ACCOUNTS && strlen(ledger->banks[i]))){
      ++any;
      if(strlen(ledger->banks[i]))
        snprintf(*s, LINESIZE * sizeof(char),"%s\nBank account: %s\n\n", *s, ledger->banks[i]);
      else 
        snprintf(*s, LINESIZE * sizeof(char),"%s\nBank account with no name\n\n", *s);
 
      if(l0 || l1){
        snprintf(*s, LINESIZE * sizeof(char),"%s          Delayed money:\n", *s);
        if(l0)
          snprintf(*s, LINESIZE * sizeof(char),"%s%s%30.2f%s  not arrived\n", *s, 
                  color(ledger->bank_totals[i][I_NOT_THERE_YET], usecolor),
                  ledger->bank_totals[i][I_NOT_THERE_YET], norm); 
        if(l1)
          snprintf(*s, LINESIZE * sizeof(char),"%s%s%30.2f%s  pending\n",*s, 
                  color(ledger->bank_totals[i][I_PENDING], usecolor), 
                  ledger->bank_totals[i][I_PENDING], norm); 
        snprintf(*s, LINESIZE * sizeof(char), "%s\n          Balances:\n", *s);
        snprintf(*s, LINESIZE * sizeof(char), "%s%s%30.2f%s  \"available\"\n", *s, 
                color(ledger->bank_totals[i][I_CLEARED], usecolor),
                ledger->bank_totals[i][I_CLEARED], norm);
        if(l1 && l0)
          snprintf(*s, LINESIZE * sizeof(char), "%s%s%30.2f%s  pending balance\n", *s,
                  color(ledger->bank_totals[i][I_PENDING_BAL], usecolor),
                  ledger->bank_totals[i][I_PENDING_BAL], norm);
        snprintf(*s, LINESIZE * sizeof(char), "%s%s%30.2f%s  true balance\n", *s, 
                color(ledger->bank_totals[i][I_OVERALL_BAL], usecolor),
                ledger->bank_totals[i][I_OVERALL_BAL], norm);
      } else {
        snprintf(*s, LINESIZE * sizeof(char), "%s          Balances:\n", *s);
        snprintf(*s, LINESIZE * sizeof(char), "%s%s%30.2f%s  true balance\n", *s,
                color(ledger->bank_totals[i][I_OVERALL_BAL], usecolor),
                ledger->bank_totals[i][I_OVERALL_BAL], norm);
        snprintf(*s, LINESIZE * sizeof(char), "%s                                All charges cleared.\n", *s);
      } 
    }

    anyp = 0;
    for(j = 0; j < ledger->npartitions[i]; ++j)
      if(small_norm(ledger->partition_totals[i][j]) == LNO){
        if(strlen(ledger->partitions[i][j])){
          if(!anyp){
            snprintf(*s, LINESIZE * sizeof(char),"%s\n          Partitions:\n", *s);
            ++anyp;
          }
          snprintf(*s, LINESIZE * sizeof(char),"%s%s%30.2f%s  %s\n", *s, color(ledger->partition_totals[i][j], usecolor), 
                  ledger->partition_totals[i][j], norm, ledger->partitions[i][j]);
        }
      }
      
    nullp = which(ledger->partitions[i], NIL, ledger->npartitions[i]);
    if(anyp && (small_norm(ledger->partition_totals[i][nullp]) == LNO))
      snprintf(*s, LINESIZE * sizeof(char),"%s%s%30.2f%s  unpartitioned\n", *s,
                  color(ledger->partition_totals[i][nullp], usecolor),
                  ledger->partition_totals[i][nullp], norm);
  }
  
  /* Strip the output string of trailing whitespace */
  
  if(str_strip(*s) == LFAILURE)
    return LFAILURE;
  
  /* If all accounts are empty, say so */
  
  if(any)
    snprintf(*s, LINESIZE * sizeof(char), "%s\n\n", *s);
  else
    printf("All accounts are empty.\n");
 
  return LSUCCESS;
}
Exemplo n.º 19
0
void *
check_pop_main (Account *account) {
  char *buf = NULL, *buf2, *buf3;
  C2ResolveNode *resolve;
  int sock;
  int timedout = FALSE;
  struct sockaddr_in server;
  
  int messages = 0, bytes = 0, downloaded_bytes = 0, i = 0, password_errors = 3;
  
  GList *download[DOWNLOAD_LIST_LAST], *uidl_search = NULL, *top_search = NULL;
  GList *list;
  gboolean supports_uidl = FALSE;
  
  mid_t mid;
  
  FILE *index;
  FILE *mail;

  Message message;
  char *mailbox;
  Mailbox *mbox;
  GString *strmsg;
  char *header[HEADER_LAST];
  gboolean reading_header = TRUE;
  gboolean with_attachs = FALSE;
  char *content_type;

  char *row[8];
  GtkStyle *style, *style2;
  gboolean clisted = FALSE;
  
  g_return_val_if_fail (account, NULL);
  g_return_val_if_fail (account->type == C2_ACCOUNT_POP, NULL);

  download[DOWNLOAD_LIST_TOTAL] = NULL;
  download[DOWNLOAD_LIST_UIDL] = NULL;
  download[DOWNLOAD_LIST_TOP] = NULL;  

  resolve = c2_resolve (account->protocol.pop.host, &buf);
  if (buf) {
    gdk_threads_enter ();
    window_checking_report (C2_CHECK_ERR, account->acc_name, buf);
    gdk_threads_leave ();
    return NULL;
  }

  sock = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (sock < 0) {
    gdk_threads_enter ();
    window_checking_report (C2_CHECK_ERR, account->acc_name, _("Failed to create socket"));
    gdk_threads_leave ();
    return NULL;
  }

  server.sin_family	= AF_INET;
  server.sin_port	= htons (account->protocol.pop.host_port);
  server.sin_addr.s_addr= inet_addr (resolve->ip);

  if (connect (sock, (struct sockaddr *)&server, sizeof (server)) < 0) {
    buf = g_strerror (errno);
    gdk_threads_enter ();
    window_checking_report (C2_CHECK_ERR, account->acc_name, buf);
    gdk_threads_leave ();
    return NULL;
  }

  /* Guten Morgen, Herr Server! */
  buf = sock_read (sock, &timedout);
  if (pop_check_answer (buf, account, timedout) < 0) {
    if (timedout) goto run_for_your_life;
    goto bye_bye_server;
  }
  c2_free (buf);

  /* Log In */
  gdk_threads_enter ();
  gtk_progress_set_format_string (GTK_PROGRESS (window_checking->mail_progress),
     		_("Logging in..."));
  gdk_threads_leave ();

retry_login:
  if (sock_printf (sock, "USER %s\r\n", account->protocol.pop.usr_name) < 0) {
    buf = g_strerror (errno);
    gdk_threads_enter ();
    window_checking_report (C2_CHECK_ERR, account->acc_name, buf);
    gdk_threads_leave ();
    goto bye_bye_server;
  }

  buf = sock_read (sock, &timedout);
  if (pop_check_answer (buf, account, timedout) < 0) {
    if (timedout) goto run_for_your_life;
    goto bye_bye_server;
  }
  c2_free (buf);

  if (sock_printf (sock, "PASS %s\r\n", account->protocol.pop.pass) < 0) {
    buf = g_strerror (errno);
    gdk_threads_enter ();
    window_checking_report (C2_CHECK_ERR, account->acc_name, buf);
    gdk_threads_leave ();
    goto bye_bye_server;
  }

  buf = sock_read (sock, &timedout);
  if (strnne (buf, "+OK", 3)) {
    if (--password_errors < 0) {
      if (pop_check_answer (buf, account, timedout) < 0) {
	if (timedout) goto run_for_your_life;
	goto bye_bye_server;
      }
    }
    gdk_threads_enter ();
    if (!gui_ask_password (account)) {
      gdk_threads_leave ();
      if (pop_check_answer (buf, account, timedout) < 0) {
	if (timedout) goto run_for_your_life;
	goto bye_bye_server;
      }
    } else {
      gdk_threads_leave ();
      goto retry_login;
    }
  }
  c2_free (buf);

  /* STAT */
  gdk_threads_enter ();
  gtk_progress_set_format_string (GTK_PROGRESS (window_checking->mail_progress),
      		_("Checking for number of mails in server..."));
  gdk_threads_leave ();

  if (sock_printf (sock, "STAT\r\n") < 0) {
    buf = g_strerror (errno);
    gdk_threads_enter ();
    window_checking_report (C2_CHECK_ERR, account->acc_name, buf);
    gdk_threads_leave ();
    goto bye_bye_server;
  }

  buf = sock_read (sock, &timedout);
  if (pop_check_answer (buf, account, timedout) < 0) {
    if (timedout) goto run_for_your_life;
    goto bye_bye_server;
  }
  sscanf (buf, "+OK %d ", &messages);
  c2_free (buf);
 
  if (!messages) {
    gdk_threads_enter ();
    gtk_progress_set_format_string (GTK_PROGRESS (window_checking->mail_progress),
      		_("No messages in server"));
    window_checking_report (C2_CHECK_OK, account->acc_name, _("No messages to download"));
    gdk_threads_leave ();
    clisted = TRUE;
    goto bye_bye_server;
  }
  else if (messages != 1)
    buf = g_strdup_printf (_("%d messages in server"), messages);
  else
    buf = g_strdup_printf (_("1 message in server"));
  gdk_threads_enter ();
  gtk_progress_set_format_string (GTK_PROGRESS (window_checking->mail_progress),
      		buf);
  gdk_threads_leave ();
  c2_free (buf);

  /* UIDL */
  if (!account->keep_copy) {
dont_use_uidl:
    /* Without UIDL*/
    for (i = 1; i <= messages; i++) {
      buf = g_strdup_printf ("%d", i);
      download[DOWNLOAD_LIST_UIDL] = g_list_append (download[DOWNLOAD_LIST_UIDL], (gpointer) buf);
    }
  } else {
    /* With UIDL */
    if (sock_printf (sock, "UIDL\r\n") < 0) {
      buf = g_strerror (errno);
      gdk_threads_enter ();
      window_checking_report (C2_CHECK_ERR, account->acc_name, buf);
      gdk_threads_leave ();
      goto bye_bye_server;
    }
    
    for (i = 0;; i++) {
      buf = sock_read (sock, &timedout);
      if (!i && strnne (buf, "+OK", 3)) {
	/* UIDL is optional for POP servers,
	 * so I won't complain if server doesn't like it */
	buf2 = g_strdup_printf (_("The POP server of the account %s doesn't support UIDL."),
	    	account->acc_name);
	gdk_threads_enter ();
	gnome_appbar_set_status (GNOME_APPBAR (WMain->appbar), buf2);
	gdk_threads_leave ();
	supports_uidl = FALSE;
	goto dont_use_uidl;
      }
      supports_uidl = TRUE;
      if (!i) continue;
      if (streq (buf, ".\r\n")) break;

      buf2 = str_get_word (1, buf, ' ');
      buf3 = str_strip (buf2, '\r');
      buf2 = str_strip (buf3, '\n');
      if (!uidl_check (buf2, account->acc_name)) {
	download[DOWNLOAD_LIST_UIDL] = g_list_append (download[DOWNLOAD_LIST_UIDL], buf);
      }
    }
  }
 
  /* TOP */
  if (!config->message_bigger) {
    /* Without TOP */
dont_use_list:
dont_use_top:
    for (i = 1; i <= messages; i++)
      	download[DOWNLOAD_LIST_TOP] = g_list_append (download[DOWNLOAD_LIST_TOP], (gpointer) i);
  } else {
    /* With TOP */
    char *subject, *from, *date, *kbytes;
    
    if (sock_printf (sock, "LIST\r\n") < 0) {
      buf = g_strerror (errno);
      gdk_threads_enter ();
      window_checking_report (C2_CHECK_ERR, account->acc_name, buf);
      gdk_threads_leave ();
      goto bye_bye_server;
    }
    
    for (i = 0;; i++) {
      buf = sock_read (sock, &timedout);
      if (!i && strnne (buf, "+OK", 3)) {
	buf2 = g_strdup_printf (_("The POP server of the account %s doesn't support LIST."),
	    	account->acc_name);
	gdk_threads_enter ();
	gnome_appbar_set_status (GNOME_APPBAR (WMain->appbar), buf2);
	gdk_threads_leave ();
	goto dont_use_list;
      }
      if (!i) continue;
      if (streq (buf, ".\r\n")) break;
      buf2 = str_get_word (1, buf, ' ');
      str_strip (buf2, '\r');
      str_strip (buf2, '\n');
      download[DOWNLOAD_LIST_TOP] = g_list_append (download[DOWNLOAD_LIST_TOP], buf);
      c2_free (buf2);
    }

    for (list = download[DOWNLOAD_LIST_TOP]; list; list = list->next) {
      if (sock_printf (sock, "TOP %d 0\r\n", atoi (CHAR (list->data))) < 0) {
	buf = g_strerror (errno);
	gdk_threads_enter ();
	window_checking_report (C2_CHECK_ERR, account->acc_name, buf);
	gdk_threads_leave ();
	goto bye_bye_server;
      }

      strmsg = g_string_new (NULL);
      for (i = 0;; i++) {
	buf = sock_read (sock, &timedout);
	if (!i && strnne (buf, "+OK", 3)) {
	  buf2 = g_strdup_printf (_("The POP server of the account %s doesn't support TOP."),
	      account->acc_name);
	  gdk_threads_enter ();
	  gnome_appbar_set_status (GNOME_APPBAR (WMain->appbar), buf2);
	  gdk_threads_leave ();
	  goto dont_use_top;
	}
	if (!i) continue;
	if (streq (buf, ".\r\n")) break;
	g_string_append (strmsg, buf);
	c2_free (buf);
      }
      subject = message_get_header_field (NULL, strmsg->str, "\nSubject:");
      from = message_get_header_field (NULL, strmsg->str, "From:");
      date = message_get_header_field (NULL, strmsg->str, "\nDate:");
      kbytes = str_get_word (1, CHAR (list->data), ' '); str_strip (kbytes, '\r');str_strip (kbytes, '\n');
      gdk_threads_enter ();
      if ((atoi (kbytes) >= config->message_bigger*1024) &&
	  (!gui_message_big_new (from, subject, date, account->acc_name, kbytes))) {
	gdk_threads_leave ();
	c2_free (list->data);
	list->data = NULL;
	download[DOWNLOAD_LIST_TOP] = g_list_remove_link (download[DOWNLOAD_LIST_TOP], list);
      } else gdk_threads_leave ();
    }
  }

  /* Learn messages to download */
  if (!account->keep_copy && !config->message_bigger) {		/* !UIDL AND !TOP */
    download[DOWNLOAD_LIST_TOTAL] = download[DOWNLOAD_LIST_UIDL];
  }
  else if (account->keep_copy && !config->message_bigger) {	/*  UIDL AND !TOP */
    for (list = download[DOWNLOAD_LIST_UIDL]; list; list = list->next) {
      download[DOWNLOAD_LIST_TOTAL] = g_list_append (download[DOWNLOAD_LIST_TOTAL], 
	 					str_get_word (0, CHAR (list->data), ' '));
    }
  }
  else if (!account->keep_copy && config->message_bigger) {	/* !UIDL AND  TOP */
    download[DOWNLOAD_LIST_TOTAL] = download[DOWNLOAD_LIST_TOP];
  }
  else if (account->keep_copy && config->message_bigger) {	/*  UIDL AND  TOP */
    for (uidl_search = download[DOWNLOAD_LIST_UIDL]; !uidl_search; uidl_search = uidl_search->next) {
      for (top_search = download[DOWNLOAD_LIST_TOP]; !top_search; top_search = top_search->next) {
	printf ("%d %d\n", (int) uidl_search->data, (int) top_search->data); /* TODO */
      }
    }
  }

  messages = g_list_length (download[DOWNLOAD_LIST_TOTAL]);
  gdk_threads_enter ();
  gtk_progress_configure (GTK_PROGRESS (window_checking->mail_progress), 0, 0, messages);
  gtk_progress_set_format_string (GTK_PROGRESS (window_checking->mail_progress),
      				_("%p%% downloaded (%v of %u messages)"));
  gdk_threads_leave ();

  strmsg = g_string_new (NULL);
  message.message = message.header = NULL;
  for (list = download[DOWNLOAD_LIST_TOTAL]; list; list = list->next) {
    buf = str_get_word (0, CHAR (list->data), ' ');
    i = atoi (buf);
    c2_free (buf);
    /* Ask for the mail */
    if (sock_printf (sock, "RETR %d\r\n", i) < 0) {
      buf = g_strerror (errno);
      gdk_threads_enter ();
      window_checking_report (C2_CHECK_ERR, account->acc_name, buf);
      gdk_threads_leave ();
      goto bye_bye_server;
    }

    /* Read the first line */
    buf = sock_read (sock, &timedout);
    if (pop_check_answer (buf, account, timedout) < 0) {
      if (timedout) goto run_for_your_life;
      goto bye_bye_server;
    }
    /* Learn bytes in the messages */
    sscanf (buf, "+OK %d octets\r\n", &bytes);
    if (bytes) {
      gdk_threads_enter ();
      gtk_progress_configure (GTK_PROGRESS (window_checking->bytes_progress), 0, 0, bytes);
      gtk_widget_show (window_checking->bytes_progress);
      gdk_threads_leave ();
    } else {
      gdk_threads_enter ();
      gtk_widget_hide (window_checking->bytes_progress);
      gdk_threads_leave ();
    }
    c2_free (buf);
    
    /* Get the mail */
    reading_header = TRUE;
    for (;;) {
      buf = sock_read (sock, &timedout);
      if (bytes) {
	downloaded_bytes += strlen (buf);
	gdk_threads_enter ();
	gtk_progress_set_value (GTK_PROGRESS (window_checking->bytes_progress), downloaded_bytes);
	gdk_threads_leave ();
      }
      if (streq (buf, ".\r\n")) {
	message.message = g_strdup (strmsg->str);
	g_string_assign (strmsg, "");
	str_strip (message.message, '\r');
	break;
      }
      if (reading_header && strlen (buf) > 2) {
	char *buf2;
	buf2 = decode_8bit (buf);
	c2_free (buf);
	buf = buf2;
      }
      if (reading_header && strlen (buf) == 2) { /* Still reading header and is an empty line */
	buf2 = g_strdup_printf ("X-CronosII-Account: %s\r\n", account->acc_name);
	g_string_append (strmsg, buf2);
	c2_free (buf2);
	reading_header = FALSE;
      }
      g_string_append (strmsg, buf);
    }
    gtk_progress_set_percentage (GTK_PROGRESS (window_checking->bytes_progress), 1);

    /* Write to the mail file */
    mailbox = account->mailbox->name;
#if USE_PLUGINS
    c2_dynamic_module_signal_emit (C2_DYNAMIC_MODULE_MESSAGE_DOWNLOAD_POP, &message,
      				 	&mailbox, NULL, NULL, NULL);
#endif
    mbox = search_mailbox_name (config->mailbox_head, mailbox);
    if (!mbox) {
      /* Mailbox couldn't be found, going with the default */
      mbox = account->mailbox;
    }
    mid = c2_mailbox_get_next_mid (mbox);
    buf = c2_mailbox_mail_path (mailbox, mid);
    if ((mail = fopen (buf, "w")) == NULL) {
      gdk_threads_enter ();
      window_checking_report (C2_CHECK_ERR, account->acc_name,
	  _("Error opening the file where to store the new mail"));
      cronos_error (errno, _("Opening the mail file"), ERROR_WARNING);
      gdk_threads_leave ();
      c2_free (buf);
      continue;
    }
    c2_free (buf);
    fprintf (mail, "%s", message.message);
    fclose (mail);

    /* Write to the index file */
    buf = c2_mailbox_index_path (mailbox);
    if ((index = fopen (buf, "a")) == NULL) {
      gdk_threads_enter ();
      window_checking_report (C2_CHECK_ERR, account->acc_name,
	  _("Error opening the main DB file to store the new mail"));
      cronos_error (errno, _("Opening the main DB file"), ERROR_WARNING);
      gdk_threads_leave ();
      c2_free (buf);
      goto bye_bye_server;
    }
    header[HEADER_SUBJECT]	= message_get_header_field (&message, NULL, "\nSubject:");
    header[HEADER_FROM]		= message_get_header_field (&message, NULL, "\nFrom:");
    header[HEADER_DATE]		= message_get_header_field (&message, NULL, "\nDate:");
    content_type		= message_get_header_field (&message, NULL, "\nContent-Type:");
    with_attachs		= FALSE;
/*    if (content_type) {
      message_mime_parse_content_type (content_type, &type, &subtype, &parameter);
      if (streq (type, "multipart")) {
	GList *s;
	MimeHash *mime;
	message_mime_parse (&message, NULL);
	for (s = message.mime; s != NULL; s = s->next) {
	  mime = MIMEHASH (s->data);
	  if (!mime) continue;
	  if (strneq (mime->disposition, "attachment", 10)) with_attachs = TRUE;
	}
      }
    }*/

    if (!header[HEADER_SUBJECT]) header[HEADER_SUBJECT] = "";
    if (!header[HEADER_FROM]) header[HEADER_FROM] = "";
    if (!header[HEADER_DATE]) header[HEADER_DATE] = "";
    fprintf (index, "N\r\r%s\r%s\r%s\r%s\r%s\r%d\n",
		with_attachs ? "1" : "", header[HEADER_SUBJECT], header[HEADER_FROM], header[HEADER_DATE],
		account->acc_name, mid);
    fclose (index);
    c2_free (message.message);
    c2_free (message.header);
    message.message = message.header = NULL;

    if (!account->keep_copy) {
      /* Delete the message */
      if (sock_printf (sock, "DELE %d\r\n", i) < 0) {
	buf = g_strerror (errno);
	gdk_threads_enter ();
	window_checking_report (C2_CHECK_ERR, account->acc_name, buf);
	gdk_threads_leave ();
	goto bye_bye_server;
      }
      buf = sock_read (sock, &timedout);
      if (pop_check_answer (buf, account, timedout) < 0) {
	if (timedout) goto run_for_your_life;
	goto bye_bye_server;
      }
    }
    
    if (streq (selected_mbox, mailbox)) {
      row[0] = "";
      row[1] = "";
      row[2] = "";
      row[3] = header[HEADER_SUBJECT];
      row[4] = header[HEADER_FROM];
      row[5] = header[HEADER_DATE];
      row[6] = account->acc_name;
      row[7] = g_strdup_printf ("%d", mid);
      
      gdk_threads_enter ();
      gtk_clist_freeze (GTK_CLIST (WMain->clist));
      gtk_clist_append (GTK_CLIST (WMain->clist), row);
      style = gtk_widget_get_style (WMain->clist);
      style2 = gtk_style_copy (style);
      style2->font = font_unread;
      gtk_clist_set_row_style (GTK_CLIST (WMain->clist), GTK_CLIST (WMain->clist)->rows-1, style2);
      gtk_clist_set_pixmap (GTK_CLIST (WMain->clist), GTK_CLIST (WMain->clist)->rows-1, 0, pixmap_unread, mask_unread);
      if (with_attachs) gtk_clist_set_pixmap (GTK_CLIST (WMain->clist), GTK_CLIST (WMain->clist)->rows-1, 2, pixmap_attach, mask_attach);
      new_messages++;
      gtk_clist_thaw (GTK_CLIST (WMain->clist));
      gtk_clist_set_row_data (GTK_CLIST (WMain->clist), GTK_CLIST (WMain->clist)->rows-1, (gpointer) "N");
      update_wm_title ();
      gtk_progress_set_value (GTK_PROGRESS (window_checking->mail_progress), i);
      gdk_threads_leave ();
      clisted = TRUE;
    }
    gdk_threads_enter ();
    gtk_progress_set_value (GTK_PROGRESS (window_checking->mail_progress),
		gtk_progress_get_value (GTK_PROGRESS (window_checking->mail_progress))+1);
    gdk_threads_leave ();
  }
  if (supports_uidl) {
    GList *llist;
    for (llist = download[DOWNLOAD_LIST_UIDL]; llist != NULL; llist = llist->next) {
      char *uidl;
      uidl = CHAR (llist->data);
      buf2 = str_get_word (1, uidl, ' ');
      buf3 = str_strip (buf2, '\r');
      buf2 = str_strip (buf3, '\n');
      if (buf2) {
	uidl_register (buf2, account->acc_name);
      }
    }
  }
        
  if (messages != 1)
    buf = g_strdup_printf (_("%d messages downloaded."), messages);
  else
    buf = g_strdup_printf (_("1 message downloaded."));
  gdk_threads_enter ();
  gtk_progress_configure (GTK_PROGRESS (window_checking->mail_progress), messages, 0, messages);
  gtk_progress_set_format_string (GTK_PROGRESS (window_checking->mail_progress),
      				buf);
  window_checking_report (C2_CHECK_OK, account->acc_name, buf);
  gdk_threads_leave ();
  
bye_bye_server:
  if (sock_printf (sock, "QUIT\r\n") < 0) {
    buf = g_strerror (errno);
  }
  
  buf = sock_read (sock, &timedout);
  if (pop_check_answer (buf, account, timedout) < 0) {
    if (timedout) goto run_for_your_life;
  }
run_for_your_life:
  close (sock);
  return NULL;
}
Exemplo n.º 20
0
//////////////////////////////////////////////////////////////////////
/// @fn string str_strip()
/// @brief -- Overload of the all-string version
//////////////////////////////////////////////////////////////////////
string str_strip(string str, char to_strip, bool leading, bool inner, bool trailing) {

  return str_strip(str, char_to_str(to_strip), leading, inner, trailing);

}
Exemplo n.º 21
0
/* allocates memory */
static int
cleanupURL(struct string *URL,struct string *pre_URL, int isReal)
{
	char *begin = URL->data;
	const char *end;
	size_t len;
	
	clear_msb(begin);
	/*if(begin == NULL)
		return;*/
	/*TODO: handle hex-encoded IPs*/
	while(isspace(*begin))
		begin++;

	len = strlen(begin);
	if(len == 0) {
		string_assign_null(URL);
		string_assign_null(pre_URL);
		return 0;
	}

	end = begin + len - 1;
	/*cli_dbgmsg("%d %d\n", end-begin, len);*/
	if(begin >= end) {
		string_assign_null(URL);
		string_assign_null(pre_URL);
		return 0;
	}
	while(isspace(*end))
		end--;
	/*TODO: convert \ to /, and stuff like that*/
	/* From mailscanner, my comments enclosed in {} */
	if(!strncmp(begin,dotnet,dotnet_len) || !strncmp(begin,adonet,adonet_len) || !strncmp(begin,aspnet,aspnet_len)) {
		string_assign_null(URL);
		string_assign_null(pre_URL);
	}
	else {
		size_t host_len;
		char* host_begin;
		int rc;

		str_replace(begin,end,'\\','/');
		/* some broken MUAs put > in the href, and then
		 * we get a false positive, so remove them */
		str_replace(begin,end,'<',' ');
		str_replace(begin,end,'>',' ');
		str_replace(begin,end,'\"',' ');
		str_replace(begin,end,';',' ');
		str_strip(&begin,&end,lt,lt_len);
		str_strip(&begin,&end,gt,gt_len);
		/* convert hostname to lowercase, but only hostname! */
		host_begin = strchr(begin,':');
		while(host_begin && host_begin[1]=='/') host_begin++;
		if(!host_begin) host_begin=begin;
		else host_begin++;
		host_len = strcspn(host_begin,"/?");
		str_make_lowercase(host_begin,host_len);
		/* convert %xx to real value */
		str_hex_to_char(&begin,&end);
		if(isReal) {
			/* htmlnorm converts \n to space, so we have to strip spaces */
			str_strip(&begin, &end, " ", 1);
		}
		else {
			/* trim space */
			while((begin <= end) && (begin[0]==' '))  begin++;
			while((begin <= end) && (end[0]==' ')) end--;
		}
		if (( rc = string_assign_dup(isReal ? URL : pre_URL,begin,end+1) )) {
			string_assign_null(URL);
			return rc;
		}
		if(!isReal) {
			str_fixup_spaces(&begin,&end);
			if (( rc = string_assign_dup(URL,begin,end+1) )) {
				return rc;
			}
		}
		/*cli_dbgmsg("%p::%s\n",URL->data,URL->data);*/
	}
	return 0;
}
Exemplo n.º 22
0
/**
 * @brief 分析客户端输入的数据
 *
 * @param cli     客户端数据结构
 * @param input   输入的数据
 *
 * @return 
 */
int client_parse_input(ChatClient *cli, char *input)
{
    int ret = 0;
    int file_flag = 0;

    input = str_strip(input);    //去掉字符串首尾的空格
    if(input == NULL)
    {
        return -1;
    }

    char *to = NULL;
    char *msg = NULL;
    ServerCmd cmd = CMD_LAST;
    packet_free(cli->pktsnd);  //清空发送数据包
    cli->pktsnd = NULL;

    if(strncmp("to ", input, 3) == 0) //比较前三个字符
    {
        input += 3;
        if(line_parse(input, ':', &to, &msg) == 0)   //以:为分隔符,将字符串分成两段
        {
            cli->pktsnd = packet_new(cli->name, to);
        }
    }
    else if(strncmp("file to ", input, 8) == 0)
    {
        input += 8;
        if(line_parse(input, ':', &to, &msg) == 0)   //以:为分隔符,将字符串分成两段
        {
            cli->pktsnd = packet_new(cli->name, to);
        }
        file_flag = 1;
    }
    else if(strcmp(input, "whoison") == 0)
    {
        cli->pktsnd = packet_new(cli->name, SERV_NAME);
        cmd = CMD_WHOISON;
        msg = (char *) g_cmd[cmd];
    }
    else if(strcmp(input, "showuser") == 0)
    {
        cli->pktsnd = packet_new(cli->name, SERV_NAME);
        cmd = CMD_SHOWUSER;
        msg = (char *) g_cmd[cmd];
    }
    else if(strcmp(input, "help") == 0)
    {
        printf("\rto usr: msg            --------- send msg to 'usr'\n");
        printf("file to usr: filepath  --------- send file to 'usr'\n");
        printf("whoison                --------- check server who is online\n");
        printf("howuser                --------- check all users who are registered\n");
        printf("logout/bye/exit        --------- logout and exit client\n");

        return 0;
    }
    else if(strcmp(input, "logout") == 0 ||
            strcmp(input, "exit")   == 0 ||
            strcmp(input, "bye")    == 0)
    {
        cli->pktsnd = packet_new(cli->name, SERV_NAME);
        cmd = CMD_LOGOUT;
        msg = (char *) g_cmd[cmd];
    }

    if(file_flag)
    {
        cli->pktsnd->type = get_msg_type(MSG_FILE_SEND);    //设置发送的是文件类型
        packet_add_msg(cli->pktsnd, msg);

        FILE *fp = fopen(msg, "r");
        char buffer[MAXLEN];

		if (fp == NULL)
		{
			printf("File: %s Not Found!\n", msg);
		}
        else
        {
            bzero(buffer, MAXLEN);
            while(fgets(buffer, MAXLEN, fp) != NULL)
			{
                packet_add_msg(cli->pktsnd, buffer);
                bzero(buffer, MAXLEN);
			}
			fclose(fp);
			printf("File:\t%s Transfer Finished!\n", msg);
        }
        ret = client_flush(cli);
    }
    if(msg && cli->pktsnd)
    {
        cli->pktsnd->type = get_msg_type(MSG_TEXT_SEND);    //设置发送的是文字类型
        packet_add_msg(cli->pktsnd, msg);
        ret = client_flush(cli);
        if(cmd==CMD_LOGOUT)
        {
            exit(0);
        }
    }
    return ret;
}
Exemplo n.º 23
0
int handle_request(const struct mime *mime_tbl, const struct cgi *cgi_tbl, const char *path_prefix, const char *default_page, const int sockfd) {
    char buf[BUFFER_SIZE], local_path[BUFFER_SIZE];
    char basic_request[3][BUFFER_SIZE], *content_type=0, *query=0;
    struct request req;
    static time_t t;
    t = time(0);
    memset(buf, 0, sizeof buf);
    memset(local_path, 0, sizeof local_path);
    memset(&req, 0, sizeof(struct request));

    read_line(buf, sockfd);
    sscanf(buf, "%s %s %s", basic_request[METHOD], basic_request[PATH], basic_request[PROC]);

    const int type = parse_request_type(basic_request[METHOD]);

    query = has_query_string(basic_request[PATH]);
    if(query) {
        *query = 0;
        ++query;
    }

    /* Add default page */
    if(strlen(basic_request[PATH])==1&&basic_request[PATH][0]=='/') {
        strcat(basic_request[PATH], default_page);
    }

    strncat(local_path, path_prefix, BUFFER_SIZE-1);
    strncat(local_path, basic_request[PATH], BUFFER_SIZE-1);

    req.type = type;
    req.uri = basic_request[PATH];
    req.local_path = local_path;
    req.query_string = query;

    fprintf(stderr, "[%s] %s %s\n", str_strip(ctime(&t)), basic_request[METHOD], basic_request[PATH]);

    write_socket(STR_PROC, strlen(STR_PROC), sockfd);
    if(type==GET) {
        FILE *fp = fopen(local_path, "r");
        if(fp==0) {
            /* File doesn't exist */
            write_socket(RES_404, strlen(RES_404), sockfd);
            write_socket("\r\n", 2, sockfd);
        } else {
            write_socket(RES_200, strlen(RES_200), sockfd);
            if(handle_cgi(&req, cgi_tbl, sockfd)==0) {
                content_type = find_content_type(mime_tbl, determine_ext(req.local_path));
                write_socket(FLD_CONTENT_TYPE, strlen(FLD_CONTENT_TYPE), sockfd);
                write_socket(content_type, strlen(content_type), sockfd);
                write_socket("\r\n", 2, sockfd);
                write_socket("\r\n", 2, sockfd);
                send_file(local_path, sockfd);
            }
        }
        fclose(fp);
    } else if(type==POST) {
        if(handle_cgi(&req, cgi_tbl, sockfd)==0) {
            return -1;
        }
    } else {
        write_socket(RES_400, strlen(RES_400), sockfd);
        write_socket("\r\n", 2, sockfd);
        write_socket("\r\n", 2, sockfd);
    }
    return 0;
}
Exemplo n.º 24
0
int settings_set_variable(const char* key, const char* val, settings_t* sttngs)
{
	char* _key = str_strip(key);
	upper_case(_key);
	char* _val = str_strip(val);
	int rv = 0;
	if (strcmp(_key, "START_OBSERVATION")==0)
	{
		sttngs->start += _atotime(_val, &rv);
		if (rv==-1)
			rv=0;
	} else if (strcmp(_key, "END_OBSERVATION")==0)
	{
		sttngs->stop += _atotime(_val, &rv);
		if (rv==-1)
			rv=0;
	} else if (strcmp(_key, "MAG")==0)
	{
		sttngs->mag_min = _atof(_val, &rv);
	} else if (strcmp(_key, "UM")==0)
	{
		sttngs->um_min = _atof(_val, &rv);
	} else if (strcmp(_key, "RA_RATE_MIN")==0)
	{
		sttngs->ra_rate_min = _atof(_val, &rv);
	} else if (strcmp(_key, "RA_RATE_MAX")==0)
	{
		sttngs->ra_rate_max = _atof(_val, &rv);
	} else if (strcmp(_key, "DECL_RATE_MIN")==0)
	{
		sttngs->decl_rate_min = _atof(_val, &rv);
	} else if (strcmp(_key, "DECL_RATE_MAX")==0)
	{
		sttngs->decl_rate_max =  _atof(_val, &rv);
	} else if (strcmp(_key, "DAY")==0)
	{
		sttngs->start += _atodate(_val, &rv);
		sttngs->stop += _atodate(_val, &rv);
	} else if (strcmp(_key, "EFEM_DIR")==0)
	{
		sttngs->dir = strdup(_val);
	} else if (strcmp(_key, "BLACK_LIST")==0)
	{
		int i=0;
		char* str = _val;
		char* tmp;
		int len = strlen(_val);
		int flag=1;
		while (++i<len)
		{
			if (_val[i]==' ' || _val[i]=='\t' || _val[i]=='\n')
			{
				if (flag)
				{
					_val[i]='\0';
					tmp = str_strip(str);
					if (strlen(tmp))
					{
						vec_add((void **)&sttngs->black_list, (void *)&tmp);
						str = &(_val[i])+1;
						flag=0;
					}
					else
					{
						free(tmp);
					}
				}
			}
			else
			{
				flag=1;
			}
		}
		tmp = str_strip(str);
		if (strlen(tmp))
		{
			vec_add((void **)&sttngs->black_list, (void *)&tmp);
		}
		else
		{
			free(tmp);
		}
	} else if (strcmp(_key, "RA_POSITION_MIN")==0)
	{
		sttngs->ra_position_min = _ra(_val, &rv);
	} else if (strcmp(_key, "RA_POSITION_MAX")==0)
	{
		sttngs->ra_position_max = _ra(_val, &rv);
	} else if (strcmp(_key, "REPORT_TYPE")==0)
	{
		if (strcmp(_val, "HTML")==0)
		{
			sttngs->report_type = report_type_html;
		}
	} else if (strcmp(_key, "REPORT_HTML_FONT_SIZE")==0)
	{
		sttngs->report_html_font_size = strdup(_val);
	} else if (strcmp(_key, "USE_ORB_FILE")==0)
	{
		sttngs->use_orb_file = (strcmp(_val, "NO")!=0);
	} else if (strcmp(_key, "ORB_FILE")==0)
	{
		sttngs->orb_file = strdup(_val);
	}
	sfree(_val);
	sfree(_key);
	return rv;
}
Exemplo n.º 25
0
int main (int argc, char *argv[])
{
    int res;
    char **list, buffer[8192];
    double t1;
    fastlist_t *fl;
   /* fast_catlist_t *cl; */

    if (argc != 2) error1 ("usage: %s exclude-file\n", argv[0]);

    warning1 ("reading ruleset\n");
    list = read_list (argv[1]);
    if (list == NULL) error1 ("failed to load pattern list from %s\n", argv[1]);

    fl = prepare_fastlist (list);
    /*
    printf ("shortest simple rule: %d\n", fl->shortest);
    for (i=0; i<fl->n_simple; i++)
    {
        printf ("%d %d %s\n",
                fl->rules[fl->simple[i]].type,
                fl->rules[fl->simple[i]].category,
                fl->rules[fl->simple[i]].rule);
    }
    */
    /*
    for (i=0; i<fl->n; i++)
    {
        printf ("%d %d %s\n", fl->rules[i].type, fl->rules[i].category,
                fl->rules[i].rule);
                }
                */
   /* for (i=0; i<fl->n_simple; i++) printf ("SIMPLE: %s\n", fl->simple[i]); */
   /* for (i=0; i<fl->n_complex; i++) printf ("COMPLEX: %s\n", fl->complex[i]); */

   /* cl = prepare_catlist (list); */
    /*
    for (i=0; i<cl->n_simple; i++)
        printf ("SIMPLE: %d.%s\n", cl->simple[i].category, cl->simple[i].rule);
    for (i=0; i<cl->n_coll; i++)
    {
        printf ("COMPLEX: %d (%d rules)\n",
                cl->colls[i].coll_id, cl->colls[i].nrules);
        for (j=0; j<cl->colls[i].nrules; j++)
        {
            printf ("  %s\n", cl->colls[i].rules[j]);
        }
    }
    */
    /*
    printf ("slow:\n");
    t1 = clock1 ();
    res = check_list (list, argv[2]);
    t1 = clock1 () - t1;

    if (res)
        printf ("%s is included (%.3f sec)\n", argv[2], t1);
    else
        printf ("%s is excluded (%.3f sec)\n", argv[2], t1);
        */

    while ((fgets (buffer, sizeof(buffer), stdin) != NULL))
    {
        str_strip (buffer, " \r\n");
        if (normalize_url2 (buffer) < 0)
        {
            printf ("bad url: %s\n", buffer);
            continue;
        }
        t1 = clock1 ();
        res = check_fastlist (fl, buffer);
        t1 = clock1 () - t1;

        if (res)
            printf ("%s is included (%.3f sec)\n", buffer, t1);
        else
            printf ("%s is excluded (%.3f sec)\n", buffer, t1);
    }

    return 0;
}
Exemplo n.º 26
0
/**
 * @brief 分析收到的数据类型并存储到客户端数据结构中
 *
 * @param cli   客户端数据结构
 * @param head  受到的原始数据
 *
 * @return 
 */
int client_parse_head(ChatClient *cli, char *head)
{
    char *str = NULL;
    str = str_strip(head);
    if(str == NULL)
    {
        return 0;
    }

    char *data = "";
    HeadType type = packet_head_parse(str);
    if(type != HEAD_START && type != HEAD_END)
    {
        data = packet_head_getdata(type, str);
    }

    switch(type)
    {
        case HEAD_START:
            if(cli->pktget)
            {
                printf("Packet is not empty!\n");
                return -1;
            }
            cli->pktstat = PKT_READ;
            cli->pktget = packet_new(NULL, NULL);
            break;
        case HEAD_TO:
            cli->pktget->to = strdup(data);
            break;
        case HEAD_FROM:
            cli->pktget->from = strdup(data);
            break;
        case HEAD_TYPE:
            cli->pktget->type = strdup(data);
            break;
        case HEAD_MSG:
            packet_add_msg(cli->pktget, data);
            break;
        case HEAD_TIME:
            cli->pktget->time = strdup(data);
            break;
        case HEAD_FDBK:
            cli->pktget->fdbk = strdup(data);
            break;
        case HEAD_END:
            //if(cli->pktget->fdbk==NULL && cli->pktget->nmsg==0)
            //if(cli->pktget->fdbk==NULL)
            //{
                //return -1;
            //}

            if(cli->pktget->from == NULL)
            {
                cli->pktget->from = strdup(cli->name);
            }
            if (cli->pktget->time==NULL){
                cli->pktget->time = gettime();
            }
            cli->pktstat = PKT_RDFULL;
            break;
        default:
            break; 
    }

    return 0;
}
Exemplo n.º 27
0
int handle_cgi(const struct request *req, const struct cgi *cgi, const int sockfd) {
    char *cmd;
    char buf[BUFFER_SIZE];
    int cp[2], fork_stat;

    if(cgi==0) return 0;

    cmd = find_cgi_command(cgi, determine_ext(req->local_path));
    if(cmd==0) return 0;

    build_cgi_env(req);

    if(req->type==GET) {
        if(req->query_string) {
            setenv("CONTENT_LENGTH", "", 1);
            setenv("QUERY_STRING", req->query_string, 1);
        }

        if(pipe(cp)<0) {
            fprintf(stderr, "Cannot pipe\n");
            return -1;
        }

        pid_t pid;
        if((pid = vfork()) == -1) {
            fprintf(stderr, "Failed to fork new process\n");
            return -1;
        }

        if(pid==0) {
            close(sockfd);
            close(cp[0]);
            dup2(cp[1], STDOUT_FILENO);
            execlp(cmd, cmd, req->local_path, (char*) 0);
            exit(0);
        } else {
            close(cp[1]);
            int len;
            while((len=read(cp[0], buf, BUFFER_SIZE))>0) {
                buf[len] = '\0';
                str_strip(buf);
                len = strlen(buf);
                write_socket(buf, len, sockfd);
            }
            close(cp[0]);
            waitpid((pid_t)pid, &fork_stat, 0);
        }
    } else if(req->type==POST) {
        int post_pipe[2];
        char content_len[BUFFER_SIZE];
        write_socket(RES_200, strlen(RES_200), sockfd);
        memset(buf, 0, sizeof buf);

        while(read_line(buf, sockfd)) {
            if(buf[0]=='\r') break;
            char *ptr = buf;
            while(*ptr!=':') ++ptr;
            *ptr = 0;
            if(strcmp("Content-Type", buf)==0) {
                setenv("CONTENT_TYPE", str_strip(ptr+=2), 1);
            }
            memset(buf, 0, sizeof buf);
        }

        memset(buf, 0, sizeof buf);
        read_socket(buf, BUFFER_SIZE, sockfd);
        sprintf(content_len, "%d", (int) strlen(buf));
        setenv("CONTENT_LENGTH", content_len, 1);

        setenv("QUERY_STRING", buf, 1);

        if(pipe(cp)<0||pipe(post_pipe)<0) {
            fprintf(stderr, "Cannot pipe\n");
            return -1;
        }

        pid_t pid;
        if((pid = vfork()) == -1) {
            fprintf(stderr, "Failed to fork new process\n");
            return -1;
        }

        if(pid==0) {
            close(sockfd);
            close(cp[0]);
            close(post_pipe[1]);
            dup2(post_pipe[0], STDIN_FILENO);
            close(post_pipe[0]);
            dup2(cp[1], STDOUT_FILENO);
            execlp(cmd, cmd, req->local_path, (char*) 0);
            exit(0);
        } else {
            close(post_pipe[0]);
            close(cp[1]);
            write(post_pipe[1], buf, strlen(buf)+1);
            close(post_pipe[1]);
            memset(buf, 0, sizeof buf);
            int len;
            while((len=read(cp[0], buf, BUFFER_SIZE))>0) {
                buf[len] = '\0';
                str_strip(buf);
                len = strlen(buf);
                write_socket(buf, len, sockfd);
            }
            waitpid((pid_t)pid, &fork_stat, 0);
            close(cp[0]);
            write_socket("\r\n", 2, sockfd);
            write_socket("\r\n", 2, sockfd);
        }

    }

    return 1;
}
Exemplo n.º 28
0
/* allocates memory */
static int
cleanupURL(struct string *URL,struct string *pre_URL, int isReal)
{
	char *begin = URL->data;
	const char *end;
	size_t len;

	clear_msb(begin);
	/*if(begin == NULL)
		return;*/
	/*TODO: handle hex-encoded IPs*/
	while(isspace(*begin))
		begin++;

	len = strlen(begin);
	if(len == 0) {
		string_assign_null(URL);
		string_assign_null(pre_URL);
		return 0;
	}

	end = begin + len - 1;
	/*cli_dbgmsg("%d %d\n", end-begin, len);*/
	if(begin >= end) {
		string_assign_null(URL);
		string_assign_null(pre_URL);
		return 0;
	}
	while(isspace(*end))
		end--;
	/* From mailscanner, my comments enclosed in {} */
	if(!strncmp(begin,dotnet,dotnet_len) || !strncmp(begin,adonet,adonet_len) || !strncmp(begin,aspnet,aspnet_len)) {
		string_assign_null(URL);
		string_assign_null(pre_URL);
	}
	else {
		size_t host_len;
		char* host_begin;
		int rc;

		str_replace(begin,end,'\\','/');
		/* find beginning of hostname, because:
		 * - we want to keep only protocol, host, and 
		 *  strip path & query parameter(s) 
		 * - we want to make hostname lowercase*/
		host_begin = strchr(begin,':');
		while(host_begin && (host_begin < end) && (host_begin[1] == '/'))  host_begin++;
		if(!host_begin) host_begin=begin;
		else host_begin++;
		host_len = strcspn(host_begin,":/?");
	        if(host_begin + host_len > end + 1) {
			/* prevent hostname extending beyond end, it can happen
			 * if we have spaces at the end, we don't want those part of 
			 * the hostname */
			host_len = end - host_begin + 1;
		} else {
			/* cut the URL after the hostname */
			/* @end points to last character we want to be part of the URL */
			end = host_begin + host_len - 1;
		}
		host_begin[host_len] = '\0';
		/* convert hostname to lowercase, but only hostname! */
		str_make_lowercase(host_begin, host_len);
		/* some broken MUAs put > in the href, and then
		 * we get a false positive, so remove them */
		str_replace(begin,end,'<',' ');
		str_replace(begin,end,'>',' ');
		str_replace(begin,end,'\"',' ');
		str_replace(begin,end,';',' ');
		str_strip(&begin,&end,lt,lt_len);
		str_strip(&begin,&end,gt,gt_len);
		/* convert %xx to real value */
		str_hex_to_char(&begin,&end);
		if(isReal) {
			/* htmlnorm converts \n to space, so we have to strip spaces */
			str_strip(&begin, &end, " ", 1);
		}
		else {
			/* trim space */
			while((begin <= end) && (begin[0]==' '))  begin++;
			while((begin <= end) && (end[0]==' ')) end--;
		}
		if (( rc = string_assign_dup(isReal ? URL : pre_URL,begin,end+1) )) {
			string_assign_null(URL);
			return rc;
		}
		if(!isReal) {
			str_fixup_spaces(&begin,&end);
			if (( rc = string_assign_dup(URL, begin, end+1) )) {
				return rc;
			}
		}
	}
	return 0;
}
Exemplo n.º 29
0
void list_append_split_bin(list *l, char *value, int value_length,
	char *split_key, byte skip_space){
	#if NULL_ARG_CHECK
	if (value == NULL){
		fprintf(stderr, "[error] list_append_split_bin: value == NULL\n");
		return;
	}
	if (split_key == NULL){
		fprintf(stderr, "[error] list_append_split_bin: split_key == NULL\n");
		return;
	}
	#endif
	str *string = new_str_p(NULL);
	int split_key_length = strlen(split_key);
	char *word = malloc(sizeof(char)*(value_length+1));
	int i;
	int word_i = 0;
	int split_key_i = 0;
	char j;
	for (i=0; i<value_length; i++){
		j = value[i];
		//if ((skip_space != 0) && (j == ' ' || j == '\t')){
		//	continue;
		//}
		word[word_i] = j;
		//word[word_i+1] = '\x00';
		word_i += 1;
		if (j == split_key[split_key_i]){
			split_key_i += 1;
		}
		else{
			split_key_i = 0;
		}
		if (split_key[split_key_i] == '\x00'){
			if (skip_space != 0){
				str_set_bin(string, word, word_i-split_key_length);
				str_strip(string);
				list_append_str(l, string);
			}
			else{
				list_append_bin(l, word, word_i-split_key_length);
			}
			word_i = 0;
			split_key_i = 0;
			word[0] = '\x00';
		}
		//printf("j %c split_key[split_key_i] %c split_key_i %d\n",
		//	j, split_key[split_key_i], split_key_i);
	}
	if (skip_space != 0){
		str_set_bin(string, word, word_i);
		str_strip(string);
		list_append_str(l, string);
	}
	else{
		list_append_bin(l, word, word_i);
	}
	str_reset(string);
	free(word);
	free(string);
	word = NULL;
	string = NULL;
}
Exemplo n.º 30
0
/*delete space before and after in the same data*/
void str_strip_inplace(char* tostrip) {

  char* local = str_strip(tostrip);
  strcpy(tostrip,local);
  free(local);
}