Beispiel #1
0
const char *whichwhois(const char *s)
{
    unsigned long ip;
    unsigned int i;

    /* IPv6 address */
    if (strchr(s, ':')) {
	if (strncmp(s, "2001:",  5) == 0) {
	    unsigned long v6net = strtol(s + 5, NULL, 16);
	    v6net = v6net & 0xfe00;	/* we care about the first 7 bits */
	    for (i = 0; ip6_assign[i].serv; i++)
		if (v6net == ip6_assign[i].net)
		    return ip6_assign[i].serv;
	    return "\x06";			/* unknown allocation */
	} else if (strncasecmp(s, "3ffe:", 5) == 0)
	    return "whois.6bone.net";
	/* RPSL hierarchical object like AS8627:fltr-TRANSIT-OUT */
	else if (strncasecmp(s, "as", 2) == 0 && isasciidigit(s[2]))
	    return whereas(atoi(s + 2));
	else
	    return "\x05";
    }

    /* email address */
    if (strchr(s, '@'))
	return "\x05";

    /* no dot and no hyphen means it's a NSI NIC handle or ASN (?) */
    if (!strpbrk(s, ".-")) {
	const char *p;

	for (p = s; *p; p++);			/* go to the end of s */
	if (strncasecmp(s, "as", 2) == 0 &&	/* it's an AS */
		(isasciidigit(s[2]) || s[2] == ' '))
	    return whereas(atoi(s + 2));
	else if (strncasecmp(p - 2, "jp", 2) == 0) /* JP NIC handle */
	    return "whois.nic.ad.jp";
	if (*s == '!')	/* NSI NIC handle */
	    return "whois.networksolutions.com";
	else
	    return "\x05";	/* probably a unknown kind of nic handle */
    }

    /* smells like an IP? */
    if ((ip = myinet_aton(s))) {
	for (i = 0; ip_assign[i].serv; i++)
	    if ((ip & ip_assign[i].mask) == ip_assign[i].net)
		return ip_assign[i].serv;
	return "\x05";			/* not in the unicast IPv4 space */
    }

    /* check the TLDs list */
    for (i = 0; tld_serv[i]; i += 2)
	if (domcmp(s, tld_serv[i]))
	    return tld_serv[i + 1];

    /* no dot but hyphen */
    if (!strchr(s, '.')) {
	/* search for strings at the start of the word */
	for (i = 0; nic_handles[i]; i += 2)
	    if (strncasecmp(s, nic_handles[i], strlen(nic_handles[i])) == 0)
		return nic_handles[i + 1];
	/* it's probably a network name */
	return "";
    }

    /* has dot and maybe a hyphen and it's not in tld_serv[], WTF is it? */
    /* either a TLD or a NIC handle we don't know about yet */
    return "\x05";
}
Beispiel #2
0
static int ChangeReg(lua_State * L) {
	if(lua_gettop(L) != 3) {
        luaL_error(L, "bad argument count to 'ChangeReg' (3 expected, got %d)", lua_gettop(L));
        lua_settop(L, 0);
        lua_pushnil(L);
        return 1;
    }

    if(lua_type(L, 1) != LUA_TSTRING || lua_type(L, 3) != LUA_TNUMBER) {
        luaL_checktype(L, 1, LUA_TSTRING);
        luaL_checktype(L, 3, LUA_TNUMBER);
		lua_settop(L, 0);
		lua_pushnil(L);
        return 1;
    }

    size_t szNickLen, szPassLen = 0;
    char * sNick = (char *)lua_tolstring(L, 1, &szNickLen);
    char * sPass = NULL;

    if(lua_type(L, 2) == LUA_TSTRING) {
        char * sPass = (char *)lua_tolstring(L, 2, &szPassLen);
        if(szPassLen == 0 || szPassLen > 64 || strpbrk(sPass, "|") != NULL) {
            lua_settop(L, 0);
            lua_pushnil(L);
            return 1;
        }
    } else if(lua_type(L, 2) != LUA_TNIL) {
        luaL_checktype(L, 2, LUA_TSTRING);
		lua_settop(L, 0);
		lua_pushnil(L);
        return 1;
    }

#if LUA_VERSION_NUM < 503
	uint16_t i16Profile = (uint16_t)lua_tonumber(L, 3);
#else
	uint16_t i16Profile = (uint16_t)lua_tounsigned(L, 3);
#endif

	if(i16Profile > clsProfileManager::mPtr->iProfileCount-1 || szNickLen == 0 || szNickLen > 64 || strpbrk(sNick, " $|") != NULL) {
		lua_settop(L, 0);
		lua_pushnil(L);
        return 1;
    }

	RegUser *reg = clsRegManager::mPtr->Find(sNick, szNickLen);

    if(reg == NULL) {
		lua_settop(L, 0);
		lua_pushnil(L);
        return 1;
    }

    clsRegManager::mPtr->ChangeReg(reg, sPass, i16Profile);

    lua_settop(L, 0);

    lua_pushboolean(L, 1);
    return 1;
}
Beispiel #3
0
static int parse_commitment_line(char *line,
				 const char *host, size_t host_len,
				 const char *service, size_t service_len,
				 time_t now, const gnutls_datum_t * skey)
{
	char *p, *kp;
	char *savep = NULL;
	size_t kp_len, phash_size;
	time_t expiration;
	int ret;
	const mac_entry_st *hash_algo;
	uint8_t phash[MAX_HASH_SIZE];
	uint8_t hphash[MAX_HASH_SIZE * 2 + 1];

	/* read host */
	p = strtok_r(line, "|", &savep);
	if (p == NULL)
		return gnutls_assert_val(GNUTLS_E_PARSING_ERROR);

	if (p[0] != '*' && host != NULL && strcmp(p, host) != 0)
		return gnutls_assert_val(GNUTLS_E_PARSING_ERROR);

	/* read service */
	p = strtok_r(NULL, "|", &savep);
	if (p == NULL)
		return gnutls_assert_val(GNUTLS_E_PARSING_ERROR);

	if (p[0] != '*' && service != NULL && strcmp(p, service) != 0)
		return gnutls_assert_val(GNUTLS_E_PARSING_ERROR);

	/* read expiration */
	p = strtok_r(NULL, "|", &savep);
	if (p == NULL)
		return gnutls_assert_val(GNUTLS_E_PARSING_ERROR);

	expiration = (time_t) atol(p);
	if (expiration > 0 && now > expiration)
		return gnutls_assert_val(GNUTLS_E_EXPIRED);

	/* read hash algorithm */
	p = strtok_r(NULL, "|", &savep);
	if (p == NULL)
		return gnutls_assert_val(GNUTLS_E_PARSING_ERROR);

	hash_algo = mac_to_entry(atol(p));
	if (_gnutls_digest_get_name(hash_algo) == NULL)
		return gnutls_assert_val(GNUTLS_E_PARSING_ERROR);

	/* read hash */
	kp = strtok_r(NULL, "|", &savep);
	if (kp == NULL)
		return gnutls_assert_val(GNUTLS_E_PARSING_ERROR);

	p = strpbrk(kp, "\n \r\t|");
	if (p != NULL)
		*p = 0;

	/* hash and hex encode */
	ret =
	    _gnutls_hash_fast((gnutls_digest_algorithm_t)hash_algo->id,
				skey->data, skey->size, phash);
	if (ret < 0)
		return gnutls_assert_val(ret);

	phash_size = _gnutls_hash_get_algo_len(hash_algo);

	p = _gnutls_bin2hex(phash, phash_size, (void *) hphash,
			    sizeof(hphash), NULL);
	if (p == NULL)
		return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);

	kp_len = strlen(kp);
	if (kp_len != phash_size * 2)
		return
		    gnutls_assert_val(GNUTLS_E_CERTIFICATE_KEY_MISMATCH);

	if (memcmp(kp, hphash, kp_len) != 0)
		return
		    gnutls_assert_val(GNUTLS_E_CERTIFICATE_KEY_MISMATCH);

	/* key found and matches */
	return 0;
}
Beispiel #4
0
/*
 * name can be defined
 */
int Vstat(PCStr(file),PVStr(path),PVStr(name),int isDGV,int lev,FileStat *st){
	refQStr(dp,path);
	refQStr(ep,name);
	FILE *fp;
	CStr(line,4096);
	CStr(facts,4096);
	CStr(fact1,128);
	const char *fcp;
	int rcc;
	int isdgv;

	if( 8 < lev ){
		return -1;
	}
	if( isDGV ){
		dp = 0;
	}else{
		dp = strrchr(path,'.');
		if( dp == 0 || !strcaseeq(dp,VNODE_EXT) )
			return -2;
	}
	if( (fp = fopen(path,"r+")) == 0 ){
		return -3;
	}
	truncVStr(facts);
	while( fgets(line,sizeof(line),fp) != NULL ){
		if( strncaseeq(line,"MLST-Facts:",11) ){
			lineScan(line+11,facts);
			break;
		}
		if( *line == ' ' && strcasestr(line,"Type=") ){
			lineScan(line+1,facts);
			break;
		}
	}

	if( lev == 0 ){
		FileStat vst;

		if( dp ){
			setVStrEnd(dp,0);
		}
		strcpy(name,file);
		if( ep = strrchr(name,'.') )
			setVStrEnd(ep,0);
		bzero(st,sizeof(FileStat));
		st->st_mode |= S_IFDIR;
		st->st_nlink = 1;
		if( stat(path,&vst) == 0 ){
			st->st_dev = vst.st_dev;
			st->st_ino = vst.st_ino;
		}
	}

	isdgv = 0;
	for( fcp = facts; *fcp; ){
		refQStr(f1,fact1);
		fcp = scan_ListElem1(fcp,';',AVStr(fact1));
		if( f1 = strpbrk(fact1,"\r\n") )
			setVStrEnd(f1,0);
		if( *fact1 == ' ' ){
			break;
		}else
		if( strncaseeq(fact1,"x-ref=",6) ){
			CStr(xpath,1024);
			refQStr(xp,xpath);
			strcpy(xpath,path);
			if( xp = strrpbrk(xpath,"/\\") ){
				truncVStr(xp);
			}
			chdir_cwd(AVStr(xpath),fact1+6,0);
			if( File_is(xpath) ){
				if( isdgv ){
fprintf(stderr,"--->>>> dgv ... %s\n",xpath);
				Vstat(file,AVStr(xpath),BVStr(name),1,lev+1,st);
				}else
				stat(xpath,st);
			}else{
				strcat(xpath,VNODE_EXT);
				Vstat(file,AVStr(xpath),BVStr(name),1,lev+1,st);
			}
		}else
		if( strncaseeq(fact1,"type=",5) ){
			if( strcaseeq(fact1+5,"file") )
				st->st_mode |= S_IFREG;
			else
			if( strcaseeq(fact1+5,"dir") )
				st->st_mode |= S_IFDIR;
			else
			if( strcaseeq(fact1+5,"vno") )
				isdgv = 1;
			else
			if( strcaseeq(fact1+5,"MLST") )
				isdgv = 2;
		}else
		if( strncaseeq(fact1,"perm=",5) ){
			st->st_mode |= permMode(fact1+5);
		}else
		if( strncaseeq(fact1,"size=",5) ){
			st->st_size = atoi(fact1+5);
		}else
		if( strncaseeq(fact1,"modify=",7) ){
			st->st_mtime = scanYmdHMS_GMT(fact1+7);
		}
	}
	fclose(fp);
	return 0;
}
int main(int argc, char **argv)
{
    int err;
    int hasSetLogFormat = 0;
    int clearLog = 0;
    int getLogSize = 0;
    int mode = O_RDONLY;
    const char *forceFilters = NULL;
    log_device_t* devices = NULL;
    log_device_t* dev;
    bool needBinary = false;

    g_logformat = android_log_format_new();

    if (argc == 2 && 0 == strcmp(argv[1], "--test")) {
        logprint_run_tests();
        exit(0);
    }

    if (argc == 2 && 0 == strcmp(argv[1], "--help")) {
        android::show_help(argv[0]);
        exit(0);
    }

    for (;;) {
        int ret;

        ret = getopt(argc, argv, "cdt:gsQf:r::n:v:b:B");

        if (ret < 0) {
            break;
        }

        switch(ret) {
            case 's': 
                // default to all silent
                android_log_addFilterRule(g_logformat, "*:s");
            break;

            case 'c':
                clearLog = 1;
                mode = O_WRONLY;
            break;

            case 'd':
                g_nonblock = true;
            break;

            case 't':
                g_nonblock = true;
                g_tail_lines = atoi(optarg);
            break;

            case 'g':
                getLogSize = 1;
            break;

            case 'b': {
                char* buf = (char*) malloc(strlen(LOG_FILE_DIR) + strlen(optarg) + 1);
                strcpy(buf, LOG_FILE_DIR);
                strcat(buf, optarg);

                bool binary = strcmp(optarg, "events") == 0;
                if (binary) {
                    needBinary = true;
                }

                if (devices) {
                    dev = devices;
                    while (dev->next) {
                        dev = dev->next;
                    }
                    dev->next = new log_device_t(buf, binary, optarg[0]);
                } else {
                    devices = new log_device_t(buf, binary, optarg[0]);
                }
                android::g_devCount++;
            }
            break;

            case 'B':
                android::g_printBinary = 1;
            break;

            case 'f':
                // redirect output to a file

                android::g_outputFileName = optarg;

            break;

            case 'r':
                if (optarg == NULL) {                
                    android::g_logRotateSizeKBytes 
                                = DEFAULT_LOG_ROTATE_SIZE_KBYTES;
                } else {
                    long logRotateSize;
                    char *lastDigit;

                    if (!isdigit(optarg[0])) {
                        fprintf(stderr,"Invalid parameter to -r\n");
                        android::show_help(argv[0]);
                        exit(-1);
                    }
                    android::g_logRotateSizeKBytes = atoi(optarg);
                }
            break;

            case 'n':
                if (!isdigit(optarg[0])) {
                    fprintf(stderr,"Invalid parameter to -r\n");
                    android::show_help(argv[0]);
                    exit(-1);
                }

                android::g_maxRotatedLogs = atoi(optarg);
            break;

            case 'v':
                err = setLogFormat (optarg);
                if (err < 0) {
                    fprintf(stderr,"Invalid parameter to -v\n");
                    android::show_help(argv[0]);
                    exit(-1);
                }

                hasSetLogFormat = 1;
            break;

            case 'Q':
                /* this is a *hidden* option used to start a version of logcat                 */
                /* in an emulated device only. it basically looks for androidboot.logcat=      */
                /* on the kernel command line. If something is found, it extracts a log filter */
                /* and uses it to run the program. If nothing is found, the program should     */
                /* quit immediately                                                            */
#define  KERNEL_OPTION  "androidboot.logcat="
#define  CONSOLE_OPTION "androidboot.console="
                {
                    int          fd;
                    char*        logcat;
                    char*        console;
                    int          force_exit = 1;
                    static char  cmdline[1024];

                    fd = open("/proc/cmdline", O_RDONLY);
                    if (fd >= 0) {
                        int  n = read(fd, cmdline, sizeof(cmdline)-1 );
                        if (n < 0) n = 0;
                        cmdline[n] = 0;
                        close(fd);
                    } else {
                        cmdline[0] = 0;
                    }

                    logcat  = strstr( cmdline, KERNEL_OPTION );
                    console = strstr( cmdline, CONSOLE_OPTION );
                    if (logcat != NULL) {
                        char*  p = logcat + sizeof(KERNEL_OPTION)-1;;
                        char*  q = strpbrk( p, " \t\n\r" );;

                        if (q != NULL)
                            *q = 0;

                        forceFilters = p;
                        force_exit   = 0;
                    }
                    /* if nothing found or invalid filters, exit quietly */
                    if (force_exit)
                        exit(0);

                    /* redirect our output to the emulator console */
                    if (console) {
                        char*  p = console + sizeof(CONSOLE_OPTION)-1;
                        char*  q = strpbrk( p, " \t\n\r" );
                        char   devname[64];
                        int    len;

                        if (q != NULL) {
                            len = q - p;
                        } else
                            len = strlen(p);

                        len = snprintf( devname, sizeof(devname), "/dev/%.*s", len, p );
                        fprintf(stderr, "logcat using %s (%d)\n", devname, len);
                        if (len < (int)sizeof(devname)) {
                            fd = open( devname, O_WRONLY );
                            if (fd >= 0) {
                                dup2(fd, 1);
                                dup2(fd, 2);
                                close(fd);
                            }
                        }
                    }
                }
                break;

            default:
                fprintf(stderr,"Unrecognized Option\n");
                android::show_help(argv[0]);
                exit(-1);
            break;
        }
    }

    if (!devices) {
        devices = new log_device_t(strdup("/dev/"LOGGER_LOG_MAIN), false, 'm');
        android::g_devCount = 1;
        int accessmode =
                  (mode & O_RDONLY) ? R_OK : 0
                | (mode & O_WRONLY) ? W_OK : 0;
        // only add this if it's available
        if (0 == access("/dev/"LOGGER_LOG_SYSTEM, accessmode)) {
            devices->next = new log_device_t(strdup("/dev/"LOGGER_LOG_SYSTEM), false, 's');
            android::g_devCount++;
        }
    }

    if (android::g_logRotateSizeKBytes != 0 
        && android::g_outputFileName == NULL
    ) {
        fprintf(stderr,"-r requires -f as well\n");
        android::show_help(argv[0]);
        exit(-1);
    }

    android::setupOutput();

    if (hasSetLogFormat == 0) {
        const char* logFormat = getenv("ANDROID_PRINTF_LOG");

        if (logFormat != NULL) {
            err = setLogFormat(logFormat);

            if (err < 0) {
                fprintf(stderr, "invalid format in ANDROID_PRINTF_LOG '%s'\n", 
                                    logFormat);
            }
        }
    }

    if (forceFilters) {
        err = android_log_addFilterString(g_logformat, forceFilters);
        if (err < 0) {
            fprintf (stderr, "Invalid filter expression in -logcat option\n");
            exit(0);
        }
    } else if (argc == optind) {
        // Add from environment variable
        char *env_tags_orig = getenv("ANDROID_LOG_TAGS");

        if (env_tags_orig != NULL) {
            err = android_log_addFilterString(g_logformat, env_tags_orig);

            if (err < 0) { 
                fprintf(stderr, "Invalid filter expression in" 
                                    " ANDROID_LOG_TAGS\n");
                android::show_help(argv[0]);
                exit(-1);
            }
        }
    } else {
        // Add from commandline
        for (int i = optind ; i < argc ; i++) {
            err = android_log_addFilterString(g_logformat, argv[i]);

            if (err < 0) { 
                fprintf (stderr, "Invalid filter expression '%s'\n", argv[i]);
                android::show_help(argv[0]);
                exit(-1);
            }
        }
    }

    dev = devices;
    while (dev) {
        dev->fd = open(dev->device, mode);
        if (dev->fd < 0) {
            fprintf(stderr, "Unable to open log device '%s': %s\n",
                dev->device, strerror(errno));
            exit(EXIT_FAILURE);
        }

        if (clearLog) {
            int ret;
            ret = android::clearLog(dev->fd);
            if (ret) {
                perror("ioctl");
                exit(EXIT_FAILURE);
            }
        }

        if (getLogSize) {
            int size, readable;

            size = android::getLogSize(dev->fd);
            if (size < 0) {
                perror("ioctl");
                exit(EXIT_FAILURE);
            }

            readable = android::getLogReadableSize(dev->fd);
            if (readable < 0) {
                perror("ioctl");
                exit(EXIT_FAILURE);
            }

            printf("%s: ring buffer is %dKb (%dKb consumed), "
                   "max entry is %db, max payload is %db\n", dev->device,
                   size / 1024, readable / 1024,
                   (int) LOGGER_ENTRY_MAX_LEN, (int) LOGGER_ENTRY_MAX_PAYLOAD);
        }

        dev = dev->next;
    }

    if (getLogSize) {
        return 0;
    }
    if (clearLog) {
        return 0;
    }

    //LOG_EVENT_INT(10, 12345);
    //LOG_EVENT_LONG(11, 0x1122334455667788LL);
    //LOG_EVENT_STRING(0, "whassup, doc?");

    if (needBinary)
        android::g_eventTagMap = android_openEventTagMap(EVENT_TAG_MAP_FILE);

    android::readLogLines(devices);

    return 0;
}
Beispiel #6
0
/* Format of _o:  column1 [ASC|DESC], column2 [ASC|DESC], ... */
int dbt_parse_orderbyclause(db_key_t **_o_k, char **_o_op, int *_o_n, db_key_t _o)
{
	char *_po, *_ps, *_pe;
	char _c = '\0';
	char _d[8];
	int _n;
	int _i;
	str *_s;

	/* scan _o, count ',' -> upper bound for no of columns */
	_n = 1;
	for (_i=0; _i < _o->len; _i++)
		if (_o->s[_i] == ',')
			_n++;

    /* *_o_k will include the db_key_ts, the strs, a copy of _o and \0 */
	*_o_k = pkg_malloc((sizeof(db_key_t)+sizeof(str)) * _n + _o->len + 1);
	if (!*_o_k)
		return -1;
	_s = (str *)((char *)(*_o_k) + sizeof(db_key_t) * _n);
	for (_i=0; _i < _n; _i++)
	    (*_o_k)[_i] = &_s[_i];
	_po = (char *)(*_o_k) + (sizeof(db_key_t) + sizeof(str)) * _n;
	memcpy(_po, _o->s, _o->len);
	*(_po+_o->len) = '\0';

	*_o_op = pkg_malloc(sizeof(char) * _n);
	if (!*_o_op)
	{
		pkg_free(*_o_k);
		return -1;
	}

	*_o_n = 0;
	_ps = _po;
	while (*_o_n < _n)
	{
		while (*_ps == ' ') _ps++;
		if (*_ps == '\0')
			break;
		strcpy(_d, " \f\n\r\t\v,"); /* isspace() and comma */
		if (*_ps == '"' || *_ps == '\'') /* detect quote */
		{
			_d[0] = *_ps;
			_d[1] = '\0';
			_ps++;
		}
		_pe = strpbrk(_ps, _d); /* search quote, space, comma or eos */
		if (!_pe && _d[0] == ' ') /* if token is last token in string */
			_pe = _po + _o->len; /* point to end of string */
		if (! _pe) /* we were looking for quote but found none */
			goto parse_error;

		/* _ps points to start of column-name,
		 * _pe points after the column-name, on quote, space, comma, or '\0' */
		_c = *_pe;
		*_pe = '\0';
		(*_o_k)[*_o_n]->s = _ps;
		(*_o_k)[*_o_n]->len = _pe - _ps;
		(*_o_op)[*_o_n] = '<'; /* default */
		(*_o_n)++;

		if (_c == '\0')
			break;

		/* go beyond current token */
		_ps = _pe + 1;
		if (_c == ',')
			continue;
		while (*_ps == ' ') _ps++;
		if (*_ps == ',')
		{
			_ps++;
			continue;
		}
		if (*_ps == '\0')
			break;

		/* there is ASC OR DESC qualifier */
		if (strncasecmp(_ps, "DESC", 4) == 0)
		{
			(*_o_op)[*_o_n-1] = '>';
			_ps += 4;
		} else if (strncasecmp(_ps, "ASC", 3) == 0)
		{
			_ps += 3;
		} else goto parse_error;

		/* point behind qualifier */
		while (*_ps == ' ') _ps++;
		if (*_ps == ',')
		{
			_ps++;
			continue;
		}
		if (*_ps == '\0')
			break;
		goto parse_error;
	}

	if (*_ps != '\0' && _c != '\0')   /* that means more elements than _tbc->nrcols */
		goto parse_error;

	if (*_o_n == 0) /* there weren't actually any columns */
	{
		pkg_free(*_o_k);
		pkg_free(*_o_op);
		*_o_op = NULL;
		*_o_k = NULL;
		return 0; /* return success anyway */
	}

	return 0;

parse_error:
	pkg_free(*_o_k);
	pkg_free(*_o_op);
	*_o_op = NULL;
	*_o_k = NULL;
	*_o_n = 0;
	return -1;
}
Beispiel #7
0
static int
pw_set_passwd(struct passwd *pwd, int fd, bool precrypted, bool update)
{
	int		 b, istty;
	struct termios	 t, n;
	login_cap_t	*lc;
	char		line[_PASSWORD_LEN+1];
	char		*p;

	if (fd == '-') {
		if (!pwd->pw_passwd || *pwd->pw_passwd != '*') {
			pwd->pw_passwd = "*";	/* No access */
			return (1);
		}
		return (0);
	}

	if ((istty = isatty(fd))) {
		if (tcgetattr(fd, &t) == -1)
			istty = 0;
		else {
			n = t;
			n.c_lflag &= ~(ECHO);
			tcsetattr(fd, TCSANOW, &n);
			printf("%s%spassword for user %s:",
			    update ? "new " : "",
			    precrypted ? "encrypted " : "",
			    pwd->pw_name);
			fflush(stdout);
		}
	}
	b = read(fd, line, sizeof(line) - 1);
	if (istty) {	/* Restore state */
		tcsetattr(fd, TCSANOW, &t);
		fputc('\n', stdout);
		fflush(stdout);
	}

	if (b < 0)
		err(EX_IOERR, "-%c file descriptor",
		    precrypted ? 'H' : 'h');
	line[b] = '\0';
	if ((p = strpbrk(line, "\r\n")) != NULL)
		*p = '\0';
	if (!*line)
		errx(EX_DATAERR, "empty password read on file descriptor %d",
		    fd);
	if (precrypted) {
		if (strchr(line, ':') != NULL)
			errx(EX_DATAERR, "bad encrypted password");
		pwd->pw_passwd = strdup(line);
	} else {
		lc = login_getpwclass(pwd);
		if (lc == NULL ||
				login_setcryptfmt(lc, "sha512", NULL) == NULL)
			warn("setting crypt(3) format");
		login_close(lc);
		pwd->pw_passwd = pw_pwcrypt(line);
	}
	return (1);
}
Beispiel #8
0
/*
 * fill the addr and mask fields in the instruction as appropriate from av.
 * Update length as appropriate.
 * The following formats are allowed:
 *     any     matches any IP6. Actually returns an empty instruction.
 *     me      returns O_IP6_*_ME
 *
 *     03f1::234:123:0342		single IP6 addres
 *     03f1::234:123:0342/24	    address/mask
 *     03f1::234:123:0342/24,03f1::234:123:0343/	       List of address
 *
 * Set of address (as in ipv6) not supported because ipv6 address
 * are typically random past the initial prefix.
 * Return 1 on success, 0 on failure.
 */
static int
fill_ip6(ipfw_insn_ip6 *cmd, char *av)
{
	int len = 0;
	struct in6_addr *d = &(cmd->addr6);
	/*
	 * Needed for multiple address.
	 * Note d[1] points to struct in6_add r mask6 of cmd
	 */

       cmd->o.len &= ~F_LEN_MASK;	/* zero len */

       if (strcmp(av, "any") == 0)
	       return (1);


       if (strcmp(av, "me") == 0) {	/* Set the data for "me" opt*/
	       cmd->o.len |= F_INSN_SIZE(ipfw_insn);
	       return (1);
       }

       if (strcmp(av, "me6") == 0) {	/* Set the data for "me" opt*/
	       cmd->o.len |= F_INSN_SIZE(ipfw_insn);
	       return (1);
       }

       av = strdup(av);
       while (av) {
		/*
		 * After the address we can have '/' indicating a mask,
		 * or ',' indicating another address follows.
		 */

		char *p;
		int masklen;
		char md = '\0';

		if ((p = strpbrk(av, "/,")) ) {
			md = *p;	/* save the separator */
			*p = '\0';	/* terminate address string */
			p++;		/* and skip past it */
		}
		/* now p points to NULL, mask or next entry */

		/* lookup stores address in *d as a side effect */
		if (lookup_host6(av, d) != 0) {
			/* XXX: failed. Free memory and go */
			errx(EX_DATAERR, "bad address \"%s\"", av);
		}
		/* next, look at the mask, if any */
		masklen = (md == '/') ? atoi(p) : 128;
		if (masklen > 128 || masklen < 0)
			errx(EX_DATAERR, "bad width \"%s\''", p);
		else
			n2mask(&d[1], masklen);

		APPLY_MASK(d, &d[1])   /* mask base address with mask */

		/* find next separator */

		if (md == '/') {	/* find separator past the mask */
			p = strpbrk(p, ",");
			if (p != NULL)
				p++;
		}
		av = p;

		/* Check this entry */
		if (masklen == 0) {
			/*
			 * 'any' turns the entire list into a NOP.
			 * 'not any' never matches, so it is removed from the
			 * list unless it is the only item, in which case we
			 * report an error.
			 */
			if (cmd->o.len & F_NOT && av == NULL && len == 0)
				errx(EX_DATAERR, "not any never matches");
			continue;
		}

		/*
		 * A single IP can be stored alone
		 */
		if (masklen == 128 && av == NULL && len == 0) {
			len = F_INSN_SIZE(struct in6_addr);
			break;
		}

		/* Update length and pointer to arguments */
		len += F_INSN_SIZE(struct in6_addr)*2;
		d += 2;
	} /* end while */
Beispiel #9
0
int parse_variable_list(
  job_data_container *dest_hash, /* This is the dest hashmap for vars found */
  job_data_container *user_env,  /* This is the source hashmap */
  int                var_type,  /* Type for vars not pulled from the source hash */
  int                op_type,   /* Op for vars not pulled from the source hash */
  char               *the_list)  /* name=value,name1=value1,etc to be parsed */

  {
  int             alloc_size = 0;
  std::string     job_env = "";
  char            name[JOB_ENV_START_SIZE];
  char           *s = NULL;
  char           *c = NULL;
  char           *delim = NULL;

  s = the_list;

  while (s)
    {
    delim = strpbrk(s, "=,");

    if (delim == s)
      {
      fprintf(stderr, "invalid -v syntax\n");
      return(3);
      }

    /* If delim is ','or NULL we have no value. Get the environment variable in s */ 
    /* If delim is '=' and delim+1 is ',' or NULL we also need to get 
       the environment variable in s */
    if (delim == NULL || *delim == ',' ||
       ((*delim == '=') && (*(delim + 1) == ',')) ||
       ((*delim == '=') && ((delim + 1) == NULL)))
      {
      if (delim == NULL)
        alloc_size = strlen(s);
      else
        alloc_size = delim - s;

      memcpy(name, s, alloc_size);
      name[alloc_size] = '\0';
      c = getenv(name);

      if (c != NULL)
        {
        job_env += name;
        job_env += "=";
        job_env += c;
        if (delim == NULL)
          s = NULL;
        else
          {
          job_env += ",";
          s = delim + 1;
          if (*s == ',') /* This ended in '='. Move one more */
            s++;
          }
        }
      else
        {
        /* No environment variable set for this name. Pass it on with value "" */
        if (delim == NULL)
          {
          snprintf(name, sizeof(name), "%s", s);
          job_env += "name";
          job_env += "=";
          s = NULL;
          }
        else
          {
          memcpy(name, s, delim - s);
          name[delim - s] = '\0';
          job_env += name;
          job_env += "=,";
          s = delim + 1;
          }
        }
      }
    else
      {
      /* We have a key value pair */
      delim = strchr(s, ',');
      if (delim == NULL)
        {
        alloc_size = strlen(s);
        /* we are at the end */
        job_env += s;
        s = NULL;
        }
      else
        {
        /* We have another variable in the list. Take care of the current one */
        alloc_size = delim - s;
        memcpy(name, s, alloc_size);
        name[alloc_size] = '\0';
        job_env += name;
        job_env += ",";
        s = delim + 1;
        }
      }
    }

  hash_add_or_exit(dest_hash, ATTR_v, job_env.c_str(), ENV_DATA);

  return(PBSE_NONE);
  } /* END parse_variable_list() */ 
Beispiel #10
0
/*
 * Read an ascii label in from FILE f,
 * in the same format as that put out by display(),
 * and fill in lp.
 */
int
getasciilabel(FILE *f, struct disklabel *lp)
{
	char **cpp, *cp;
	const char *errstr;
	struct partition *pp;
	char *tp, *s, line[BUFSIZ];
	int lineno = 0, errors = 0;
	u_int32_t v, fsize;
	u_int64_t lv;

	lp->d_version = 1;
	lp->d_bbsize = BBSIZE;				/* XXX */
	lp->d_sbsize = SBSIZE;				/* XXX */
	while (fgets(line, sizeof(line), f)) {
		lineno++;
		if ((cp = strpbrk(line, "#\r\n")))
			*cp = '\0';
		cp = skip(line);
		if (cp == NULL)
			continue;
		tp = strchr(cp, ':');
		if (tp == NULL) {
			warnx("line %d: syntax error", lineno);
			errors++;
			continue;
		}
		*tp++ = '\0', tp = skip(tp);
		if (!strcmp(cp, "type")) {
			if (tp == NULL)
				tp = "unknown";
			else if (strcasecmp(tp, "IDE") == 0)
				tp = "ESDI";
			cpp = dktypenames;
			for (; cpp < &dktypenames[DKMAXTYPES]; cpp++)
				if ((s = *cpp) && !strcasecmp(s, tp)) {
					lp->d_type = cpp - dktypenames;
					goto next;
				}
			v = GETNUM(lp->d_type, tp, 0, &errstr);
			if (errstr || v >= DKMAXTYPES)
				warnx("line %d: warning, unknown disk type: %s",
				    lineno, tp);
			lp->d_type = v;
			continue;
		}
		if (!strcmp(cp, "flags")) {
			for (v = 0; (cp = tp) && *cp != '\0';) {
				tp = word(cp);
				if (!strcmp(cp, "badsect"))
					v |= D_BADSECT;
				else if (!strcmp(cp, "vendor"))
					v |= D_VENDOR;
				else {
					warnx("line %d: bad flag: %s",
					    lineno, cp);
					errors++;
				}
			}
			lp->d_flags = v;
			continue;
		}
		if (!strcmp(cp, "drivedata")) {
			int i;

			for (i = 0; (cp = tp) && *cp != '\0' && i < NDDATA;) {
				v = GETNUM(lp->d_drivedata[i], cp, 0, &errstr);
				if (errstr)
					warnx("line %d: bad drivedata %s",
					   lineno, cp);
				lp->d_drivedata[i++] = v;
				tp = word(cp);
			}
			continue;
		}
		if (sscanf(cp, "%d partitions", &v) == 1) {
			if (v == 0 || v > MAXPARTITIONS) {
				warnx("line %d: bad # of partitions", lineno);
				lp->d_npartitions = MAXPARTITIONS;
				errors++;
			} else
				lp->d_npartitions = v;
			continue;
		}
		if (tp == NULL)
			tp = "";
		if (!strcmp(cp, "disk")) {
			strncpy(lp->d_typename, tp, sizeof (lp->d_typename));
			continue;
		}
		if (!strcmp(cp, "label")) {
			strncpy(lp->d_packname, tp, sizeof (lp->d_packname));
			continue;
		}
		if (!strcmp(cp, "duid")) {
			if (duid_parse(lp, tp) != 0) {
				warnx("line %d: bad %s: %s", lineno, cp, tp);
				errors++;
			}
			continue;
		}
		if (!strcmp(cp, "bytes/sector")) {
			v = GETNUM(lp->d_secsize, tp, 1, &errstr);
			if (errstr || (v % 512) != 0) {
				warnx("line %d: bad %s: %s", lineno, cp, tp);
				errors++;
			} else
				lp->d_secsize = v;
			continue;
		}
		if (!strcmp(cp, "sectors/track")) {
			v = GETNUM(lp->d_nsectors, tp, 1, &errstr);
			if (errstr) {
				warnx("line %d: bad %s: %s", lineno, cp, tp);
				errors++;
			} else
				lp->d_nsectors = v;
			continue;
		}
		if (!strcmp(cp, "sectors/cylinder")) {
			v = GETNUM(lp->d_secpercyl, tp, 1, &errstr);
			if (errstr) {
				warnx("line %d: bad %s: %s", lineno, cp, tp);
				errors++;
			} else
				lp->d_secpercyl = v;
			continue;
		}
		if (!strcmp(cp, "tracks/cylinder")) {
			v = GETNUM(lp->d_ntracks, tp, 1, &errstr);
			if (errstr) {
				warnx("line %d: bad %s: %s", lineno, cp, tp);
				errors++;
			} else
				lp->d_ntracks = v;
			continue;
		}
		if (!strcmp(cp, "cylinders")) {
			v = GETNUM(lp->d_ncylinders, tp, 1, &errstr);
			if (errstr) {
				warnx("line %d: bad %s: %s", lineno, cp, tp);
				errors++;
			} else
				lp->d_ncylinders = v;
			continue;
		}

		/* Ignore fields that are no longer in the disklabel. */
		if (!strcmp(cp, "rpm") ||
		    !strcmp(cp, "interleave") ||
		    !strcmp(cp, "trackskew") ||
		    !strcmp(cp, "cylinderskew") ||
		    !strcmp(cp, "headswitch") ||
		    !strcmp(cp, "track-to-track seek"))
			continue;

		/* Ignore fields that are forcibly set when label is read. */
		if (!strcmp(cp, "total sectors") ||
		    !strcmp(cp, "boundstart") ||
		    !strcmp(cp, "boundend"))
			continue;

		if ('a' <= *cp && *cp <= 'z' && cp[1] == '\0') {
			unsigned int part = *cp - 'a';

			if (part >= lp->d_npartitions) {
				if (part >= MAXPARTITIONS) {
					warnx("line %d: bad partition name: %s",
					    lineno, cp);
					errors++;
					continue;
				} else {
					lp->d_npartitions = part + 1;
				}
			}
			pp = &lp->d_partitions[part];
#define NXTNUM(n, field, errstr) { \
	if (tp == NULL) {					\
		warnx("line %d: too few fields", lineno);	\
		errors++;					\
		break;						\
	} else							\
		cp = tp, tp = word(cp), (n) = GETNUM(field, cp, 0, errstr); \
}
			NXTNUM(lv, lv, &errstr);
			if (errstr) {
				warnx("line %d: bad partition size: %s",
				    lineno, cp);
				errors++;
			} else {
				DL_SETPSIZE(pp, lv);
			}
			NXTNUM(lv, lv, &errstr);
			if (errstr) {
				warnx("line %d: bad partition offset: %s",
				    lineno, cp);
				errors++;
			} else {
				DL_SETPOFFSET(pp, lv);
			}
			if (tp == NULL) {
				pp->p_fstype = FS_UNUSED;
				goto gottype;
			}
			cp = tp, tp = word(cp);
			cpp = fstypenames;
			for (; cpp < &fstypenames[FSMAXTYPES]; cpp++)
				if ((s = *cpp) && !strcasecmp(s, cp)) {
					pp->p_fstype = cpp - fstypenames;
					goto gottype;
				}
			if (isdigit((unsigned char)*cp))
				v = GETNUM(pp->p_fstype, cp, 0, &errstr);
			else
				v = FSMAXTYPES;
			if (errstr || v >= FSMAXTYPES) {
				warnx("line %d: warning, unknown filesystem type: %s",
				    lineno, cp);
				v = FS_UNUSED;
			}
			pp->p_fstype = v;
	gottype:
			switch (pp->p_fstype) {

			case FS_UNUSED:				/* XXX */
				if (tp == NULL)	/* ok to skip fsize/bsize */
					break;
				NXTNUM(fsize, fsize, &errstr);
				if (fsize == 0)
					break;
				NXTNUM(v, v, &errstr);
				pp->p_fragblock =
				    DISKLABELV1_FFS_FRAGBLOCK(fsize, v / fsize);
				break;

			case FS_BSDFFS:
				NXTNUM(fsize, fsize, &errstr);
				if (fsize == 0)
					break;
				NXTNUM(v, v, &errstr);
				pp->p_fragblock =
				    DISKLABELV1_FFS_FRAGBLOCK(fsize, v / fsize);
				NXTNUM(pp->p_cpg, pp->p_cpg, &errstr);
				break;

			default:
				break;
			}
			continue;
		}
		warnx("line %d: unknown field: %s", lineno, cp);
		errors++;
	next:
		;
	}
	errors += checklabel(lp);
	return (errors > 0);
}
Beispiel #11
0
int bbfile(pMesh mesh) {
  FILE      *in;
  pSolution  ps;
  double     a,b,c,lambda[3],eigv[3][3],m[6],vp[2][2];
  float      dummy;
  int        j,k,l,dim,np,nfield,nf,i1,i2,i3,i4,err,iord;
  char      *ptr,data[128],tmp[128];
  ubyte      bigbb;

  /* default */
  strcpy(tmp,mesh->name);
  ptr = (char *)strstr(tmp,".mesh");
  if ( ptr ) *ptr = '\0';

  sprintf(data,"%s.bb",tmp);
  in = fopen(data,"r");
  bigbb = 0;
  if ( !in ) {
    sprintf(data,"%s.pbb",tmp);
    in = fopen(data,"r");
  }  
  if ( !in ) {
    bigbb = 1;
    sprintf(data,"%s.BB",tmp);
    in = fopen(data,"r");  
    if ( !in ) { /* hack FH pour le mac */
      sprintf(data,"%s.gbb",tmp);
      in = fopen(data,"r");
    }
    
  }
  if ( !in )    
    return(0);
  
  /* if ( !quiet )  fprintf(stdout,"  Reading %s\n",data); */
  i1=i2=i3=i4=-1;
  /* read file format */
  err=0;
  fscanf(in,"%d",&dim);
  if(EatSpace(in)) err++;
  fscanf(in,"%d",&i1);
  if(EatSpace(in)) err++;
  fscanf(in,"%d",&i2);
  if(EatSpace(in)) err++;
  fscanf(in,"%d",&i3);
  bigbb=  (EatSpace(in)==0); /* not nl after the 4 integer => BB */

  if ( !quiet )
    if(bigbb)  fprintf(stdout,"  Reading BB file %s\n",data);
    else  fprintf(stdout,"  Reading bb file %s\n",data);

  if ( dim < 2 || dim > 3 || err ) {
    fprintf(stderr,"  %%%% Wrong file (dim=%d) (err=%d). Ignored\n",dim,err);
    return(0);
  }
  /* read number of field(s) */
  nf = 0;

  if ( bigbb ) {
    /* get only 1st field */
    /* fscanf(in,"%d",&nfield);*/
    nfield=i1;
    /*fscanf(in,"%d",&mesh->nfield);*/
    mesh->nfield = i2;
    if (nfield>1) 
      {
	nf += i3;
	for (k=1; k<nfield-1; k++) {
	  fscanf(in,"%d",&np);
	  nf += np;
	}
	fscanf(in,"%d",&np);
      }
    else 
      np = i3;
    /* read file type */
    fscanf(in,"%d",&mesh->typage);
    printf(" np= %d, type= %d\n",np,mesh->typage);
  }
  else {
   /* fscanf(in,"%d",&mesh->nfield);
      fscanf(in,"%d",&np);*/
    /* read file type */
    /* fscanf(in,"%d",&mesh->typage);*/
    mesh->nfield=i1;
    np=i2;
    mesh->typage=i3;
  }  
  

  if ( mesh->typage == 2 ) {
    if ( np < mesh->np ) {
      fprintf(stderr,"  %%%% Wrong solution number (%d , %d). Ignored\n",np,mesh->np);
      fclose(in);
      return(0);
    }
    mesh->nbb = mesh->np;
  }
  else if ( mesh->typage == 1 ) {
    if ( np < mesh->ne ) {
      fprintf(stderr,"  %%%% Wrong solution number (%d , %d). Ignored\n",np,mesh->ne);
      fclose(in);
      return(0);
    }
    mesh->nbb = mesh->ne;
  }
  else {
    fprintf(stderr,"  %%%% Wrong typage (%d). Ignored\n",mesh->typage);
    fclose(in);
    return(0);
  }

  /* read solutions */
  mesh->bbmin  =  1.e10;
  mesh->bbmax  = -1.e10;

  /* allocate memory */
  if ( !zaldy2(mesh) ) {
    mesh->nbb = 0;
    fclose(in);
    return(0);
  }

  /* scalar field */
  if ( mesh->nfield == 1 ) {
    if ( ddebug )  printf("   scalar (isotropic) field\n");
    for (k=1; k<=mesh->nbb; k++) {
      ps = &mesh->sol[k];
      ps->bb = 0.0;
      if ( fscanf(in,"%s",data) != 1 )  continue;
      if ( ptr = strpbrk(data,"dD") ) *ptr = 'E';
      sscanf(data,"%f",&ps->bb);
      if ( ps->bb < mesh->bbmin )  mesh->bbmin = ps->bb;
      if ( ps->bb > mesh->bbmax )  mesh->bbmax = ps->bb;
      for (j=1; j<=nf; j++)  fscanf(in,"%f",&dummy);
    }
  }

  /* vector field */
  else if ( mesh->nfield == mesh->dim ) {
    if ( ddebug )  fprintf(stdout,"   vector field \n");
    for (k=1; k<=mesh->nbb; k++) {
      ps = &mesh->sol[k];
      ps->bb = 0.0;
      for (l=0; l<mesh->dim; l++) {
        if ( fscanf(in,"%s",data) != 1 )  continue;
        if ( ptr = strpbrk(data,"dD") ) *ptr = 'E';
        sscanf(data,"%f",&ps->m[l]);
        ps->bb += ps->m[l]*ps->m[l];
      }
      ps->bb = sqrt(ps->bb);
      if ( ps->bb < mesh->bbmin )  mesh->bbmin = ps->bb;
      if ( ps->bb > mesh->bbmax )
        mesh->bbmax = ps->bb;
      for (j=1; j<nf; j++)  fscanf(in,"%f",&dummy);
    }
    fclose(in);
    return(0);
  }
  else if ( dim == 2 && mesh->nfield == 3 ) {
    if ( ddebug )  fprintf(stdout,"   2D metric field\n");
    for (k=1; k<=mesh->np; k++) {
      ps = &mesh->sol[k];
      fscanf(in,"%lf %lf %lf",&a,&b,&c);
      ps->m[0] = a;
      ps->m[1] = b;
      ps->m[2] = c;
      m[0] = a;
      m[1] = b;
      m[2] = c;
      eigen2(m,lambda,vp);
      ps->bb = MEDIT_MIN(lambda[0],lambda[1]);
      if ( ps->bb < mesh->bbmin )  mesh->bbmin = ps->bb;
      if ( ps->bb > mesh->bbmax )  mesh->bbmax = ps->bb;
      for (j=1; j<nf; j++)  fscanf(in,"%f",&dummy);
    }
  }
  else if ( dim == 3 && mesh->nfield == 6 ) {
    if ( ddebug )  fprintf(stdout,"   3D metric field\n");
    for (k=1; k<=mesh->np; k++) {
      ps = &mesh->sol[k];
      ps->bb = 0.0f;
      for (l=0; l<6; l++) {
        if ( fscanf(in,"%s",data) != 1 )  continue;
        if ( ptr = strpbrk(data,"dD") ) *ptr = 'E';
        sscanf(data,"%f",&dummy);
        m[l] = dummy;
      }
      ps->m[0] = m[0];
      ps->m[1] = m[1];
      ps->m[2] = m[3];
      ps->m[3] = m[2];
      ps->m[4] = m[4];
      ps->m[5] = m[5];

      m[2] = ps->m[2];
      m[3] = ps->m[3];
      iord = eigenv(1,m,lambda,eigv);
      if ( iord ) {
        ps->bb = lambda[0];
        ps->bb = MEDIT_MAX(ps->bb,lambda[1]);
        ps->bb = MEDIT_MAX(ps->bb,lambda[2]);
        if ( ps->bb < mesh->bbmin )  mesh->bbmin = ps->bb;
        if ( ps->bb > mesh->bbmax )  mesh->bbmax = ps->bb;
      }
      else {
        fprintf(stdout,"  ## Eigenvalue problem.\n");
      }
      
      for (j=1; j<nf; j++)  fscanf(in,"%f",&dummy);
    }
  }
  else {
    fprintf(stderr," %%%% Solution not suitable. Ignored\n");
    mesh->nbb = 0;
  }

  fclose(in);
  return(np);
}
Beispiel #12
0
static int
parsespec(const char *spec)
{
	char *p;
	const char *q;
	int count;
	priv_set_t ***toupd;
	priv_set_t *upd;
	int i;
	boolean_t freeupd = B_TRUE;

	if (pri == NULL)
		loadprivinfo();

	p = strpbrk(spec, "+-=");

	if (p == NULL || p - spec > pri->priv_nsets)
		badspec(spec);

	if (p[1] == '\0' || (upd = priv_str_to_set(p + 1, ",", NULL)) == NULL)
		badspec(p + 1);

	count = p - spec;
	switch (*p) {
	case '+':
		toupd = &add;
		break;
	case '-':
		toupd = &rem;
		priv_inverse(upd);
		break;
	case '=':
		toupd = &assign;
		break;
	}

	/* Update all sets? */
	if (count == 0 || *spec == 'a' || *spec == 'A') {
		count = pri->priv_nsets;
		q = sets;
	} else
		q = spec;

	for (i = 0; i < count; i++) {
		int ind = strindex(q[i], sets);

		if (ind == -1)
			badspec(spec);

		/* Assign is mutually exclusive with add/remove and itself */
		if (((toupd == &rem || toupd == &add) && assign[ind] != NULL) ||
		    (toupd == &assign && (assign[ind] != NULL ||
		    rem[ind] != NULL || add[ind] != NULL))) {
			(void) fprintf(stderr, "%s: conflicting spec: %s\n",
			    command, spec);
			exit(1);
		}
		if ((*toupd)[ind] != NULL) {
			if (*p == '-')
				priv_intersect(upd, (*toupd)[ind]);
			else
				priv_union(upd, (*toupd)[ind]);
		} else {
			(*toupd)[ind] = upd;
			freeupd = B_FALSE;
		}
	}
	if (freeupd)
		priv_freeset(upd);
	return (0);
}
Beispiel #13
0
static bool IgnoreDeprecated;
static bool NameOnly;
static bool PrintName;
static bool PrintNewline;
static bool IgnoreError;
static bool Quiet;
static char *pattern;

/* Function prototypes. */
static int pattern_match(const char *string, const char *pat);
static int DisplayAll(const char *restrict const path);

static void slashdot(char *restrict p, char old, char new)
{
	int warned = 1;
	p = strpbrk(p, "/.");
	if (!p)
		/* nothing -- can't be, but oh well */
		return;
	if (*p == new)
		/* already in desired format */
		return;
	while (p) {
		char c = *p;
		if ((*(p + 1) == '/' || *(p + 1) == '.') && warned) {
			xwarnx(_("separators should not be repeated: %s"), p);
			warned = 0;
		}
		if (c == old)
			*p = new;
		if (c == new)
Beispiel #14
0
int
pkg_perform(char **pkgs)
{
    static const char *home;
    char *pkg = *pkgs;		/* Only one arg to create */
    char *cp;
    FILE *pkg_in, *fp;
    Package plist;
    int len;
    const char *suf;

    /* Preliminary setup */
    if (InstalledPkg == NULL)
	sanity_check();
    if (Verbose && !PlistOnly)
	printf("Creating package %s\n", pkg);

    /* chop suffix off if already specified, remembering if we want to compress  */
    len = strlen(pkg);
    if (len > 4) {
	if (!strcmp(&pkg[len - 4], ".tbz")) {
	    Zipper = BZIP2;
	    pkg[len - 4] = '\0';
	}
	else if (!strcmp(&pkg[len - 4], ".tgz")) {
	    Zipper = GZIP;
	    pkg[len - 4] = '\0';
	}
	else if (!strcmp(&pkg[len - 4], ".txz")) {
	    Zipper = XZ;
	    pkg[len - 4] = '\0';
	}
	else if (!strcmp(&pkg[len - 4], ".tar")) {
	    Zipper = NONE;
	    pkg[len - 4] = '\0';
	}
    }
    if (Zipper == BZIP2) {
	suf = "tbz";
	setenv("BZIP2", "--best", 0);
    } else if (Zipper == GZIP) {
	suf = "tgz";
	setenv("GZIP", "-9", 0);
    } else if (Zipper == XZ) {
	suf = "txz";
    } else
	suf = "tar";

    if (InstalledPkg != NULL) {
	char *pkgglob[] = { InstalledPkg, NULL };
	char **matched, **pkgs;
	int i, error;

	pkgs = pkgglob;
	if (MatchType != MATCH_EXACT) {
		matched = matchinstalled(MatchType, pkgs, &error);
		if (!error && matched != NULL)
			pkgs = matched;
		else if (MatchType != MATCH_GLOB)
	    		errx(1, "no packages match pattern");
	}
	/*
	 * Is there is only one installed package matching the pattern,
	 * we need to respect the optional pkg-filename parameter.  If,
	 * however, the pattern matches several packages, this parameter
	 * makes no sense and is ignored.
	 */
	if (pkgs[1] == NULL) {
	    if (pkg == InstalledPkg)
		pkg = *pkgs;
	    InstalledPkg = *pkgs;
	    if (!Recursive)
		return (create_from_installed(InstalledPkg, pkg, suf));
	    return (create_from_installed_recursive(pkg, suf));
	}
	for (i = 0; pkgs[i] != NULL; i++) {
	    InstalledPkg = pkg = pkgs[i];
	    if (!Recursive)
		create_from_installed(pkg, pkg, suf);
	    else
	        create_from_installed_recursive(pkg, suf);
	}
	return TRUE;
    }

    get_dash_string(&Comment);
    get_dash_string(&Desc);
    if (!strcmp(Contents, "-"))
	pkg_in = stdin;
    else {
	pkg_in = fopen(Contents, "r");
	if (!pkg_in) {
	    cleanup(0);
	    errx(2, "%s: unable to open contents file '%s' for input",
		__func__, Contents);
	}
    }
    plist.head = plist.tail = NULL;

    /* Stick the dependencies, if any, at the top */
    if (Pkgdeps) {
	char **deps, *deporigin;
	int i;
	int ndeps = 0;

	if (Verbose && !PlistOnly)
	    printf("Registering depends:");

	/* Count number of dependencies */
	for (cp = Pkgdeps; cp != NULL && *cp != '\0';
			   cp = strpbrk(++cp, " \t\n")) {
	    ndeps++;
	}

	if (ndeps != 0) {
	    /* Create easy to use NULL-terminated list */
	    deps = alloca(sizeof(*deps) * ndeps + 1);
	    if (deps == NULL) {
		errx(2, "%s: alloca() failed", __func__);
		/* Not reached */
	    }
	    for (i = 0; Pkgdeps;) {
		cp = strsep(&Pkgdeps, " \t\n");
		if (*cp) {
		    deps[i] = cp;
		    i++;
		}
	    }
	    ndeps = i;
	    deps[ndeps] = NULL;

	    sortdeps(deps);
	    for (i = 0; i < ndeps; i++) {
		deporigin = strchr(deps[i], ':');
		if (deporigin != NULL) {
		    *deporigin = '\0';
		    add_plist_top(&plist, PLIST_DEPORIGIN, ++deporigin);
		}
		add_plist_top(&plist, PLIST_PKGDEP, deps[i]);
		if (Verbose && !PlistOnly)
		    printf(" %s", deps[i]);
	    }
	}

	if (Verbose && !PlistOnly)
	    printf(".\n");
    }

    /* Put the conflicts directly after the dependencies, if any */
    if (Conflicts) {
	if (Verbose && !PlistOnly)
	    printf("Registering conflicts:");
	while (Conflicts) {
	   cp = strsep(&Conflicts, " \t\n");
	   if (*cp) {
		add_plist(&plist, PLIST_CONFLICTS, cp);
		if (Verbose && !PlistOnly)
		    printf(" %s", cp);
	   }
	}
	if (Verbose && !PlistOnly)
	    printf(".\n");
    }

    /* If a SrcDir override is set, add it now */
    if (SrcDir) {
	if (Verbose && !PlistOnly)
	    printf("Using SrcDir value of %s\n", SrcDir);
	add_plist(&plist, PLIST_SRC, SrcDir);
    }

    /* Slurp in the packing list */
    read_plist(&plist, pkg_in);

    /* Prefix should add an @cwd to the packing list */
    if (Prefix) {
	if (Prefix[0] != '/') {
		char resolved_prefix[PATH_MAX];
		if (realpath(Prefix, resolved_prefix) == NULL)
		    err(EXIT_FAILURE, "couldn't resolve path for prefix: %s", Prefix);
		add_plist_top(&plist, PLIST_CWD, resolved_prefix);
	} else {
		add_plist_top(&plist, PLIST_CWD, Prefix);
	}
    }

    /* Add the origin if asked, at the top */
    if (Origin)
	add_plist_top(&plist, PLIST_ORIGIN, Origin);

    /*
     * Run down the list and see if we've named it, if not stick in a name
     * at the top.
     */
    if (find_plist(&plist, PLIST_NAME) == NULL)
	add_plist_top(&plist, PLIST_NAME, basename(pkg));

    if (asprintf(&cp, "PKG_FORMAT_REVISION:%d.%d", PLIST_FMT_VER_MAJOR,
		 PLIST_FMT_VER_MINOR) == -1) {
	errx(2, "%s: asprintf() failed", __func__);
    }
    add_plist_top(&plist, PLIST_COMMENT, cp);
    free(cp);

    /*
     * We're just here for to dump out a revised plist for the FreeBSD ports
     * hack.  It's not a real create in progress.
     */
    if (PlistOnly) {
	check_list(home, &plist);
	write_plist(&plist, stdout);
	exit(0);
    }

    /* Make a directory to stomp around in */
    home = make_playpen(PlayPen, 0);
    signal(SIGINT, cleanup);
    signal(SIGHUP, cleanup);

    /* Make first "real contents" pass over it */
    check_list(home, &plist);
    (void) umask(022);	/*
			 * Make sure gen'ed directories, files don't have
			 * group or other write bits.
			 */
    /* copy_plist(home, &plist); */
    /* mark_plist(&plist); */

    /* Now put the release specific items in */
    if (!Prefix) {
	add_plist(&plist, PLIST_CWD, ".");
    }
    write_file(COMMENT_FNAME, Comment);
    add_plist(&plist, PLIST_IGNORE, NULL);
    add_plist(&plist, PLIST_FILE, COMMENT_FNAME);
    add_cksum(&plist, plist.tail, COMMENT_FNAME);
    write_file(DESC_FNAME, Desc);
    add_plist(&plist, PLIST_IGNORE, NULL);
    add_plist(&plist, PLIST_FILE, DESC_FNAME);
    add_cksum(&plist, plist.tail, DESC_FNAME);

    if (Install) {
	copy_file(home, Install, INSTALL_FNAME);
	add_plist(&plist, PLIST_IGNORE, NULL);
	add_plist(&plist, PLIST_FILE, INSTALL_FNAME);
	add_cksum(&plist, plist.tail, INSTALL_FNAME);
    }
    if (PostInstall) {
	copy_file(home, PostInstall, POST_INSTALL_FNAME);
	add_plist(&plist, PLIST_IGNORE, NULL);
	add_plist(&plist, PLIST_FILE, POST_INSTALL_FNAME);
	add_cksum(&plist, plist.tail, POST_INSTALL_FNAME);
    }
    if (DeInstall) {
	copy_file(home, DeInstall, DEINSTALL_FNAME);
	add_plist(&plist, PLIST_IGNORE, NULL);
	add_plist(&plist, PLIST_FILE, DEINSTALL_FNAME);
	add_cksum(&plist, plist.tail, DEINSTALL_FNAME);
    }
    if (PostDeInstall) {
	copy_file(home, PostDeInstall, POST_DEINSTALL_FNAME);
	add_plist(&plist, PLIST_IGNORE, NULL);
	add_plist(&plist, PLIST_FILE, POST_DEINSTALL_FNAME);
	add_cksum(&plist, plist.tail, POST_DEINSTALL_FNAME);
    }
    if (Require) {
	copy_file(home, Require, REQUIRE_FNAME);
	add_plist(&plist, PLIST_IGNORE, NULL);
	add_plist(&plist, PLIST_FILE, REQUIRE_FNAME);
	add_cksum(&plist, plist.tail, REQUIRE_FNAME);
    }
    if (Display) {
	copy_file(home, Display, DISPLAY_FNAME);
	add_plist(&plist, PLIST_IGNORE, NULL);
	add_plist(&plist, PLIST_FILE, DISPLAY_FNAME);
	add_cksum(&plist, plist.tail, DISPLAY_FNAME);
	add_plist(&plist, PLIST_DISPLAY, DISPLAY_FNAME);
    }
    if (Mtree) {
	copy_file(home, Mtree, MTREE_FNAME);
	add_plist(&plist, PLIST_IGNORE, NULL);
	add_plist(&plist, PLIST_FILE, MTREE_FNAME);
	add_cksum(&plist, plist.tail, MTREE_FNAME);
	add_plist(&plist, PLIST_MTREE, MTREE_FNAME);
    }

    /* Finally, write out the packing list */
    fp = fopen(CONTENTS_FNAME, "w");
    if (!fp) {
	cleanup(0);
	errx(2, "%s: can't open file %s for writing",
	    __func__, CONTENTS_FNAME);
    }
    write_plist(&plist, fp);
    if (fclose(fp)) {
	cleanup(0);
	errx(2, "%s: error while closing %s",
	    __func__, CONTENTS_FNAME);
    }

    /* And stick it into a tar ball */
    make_dist(home, pkg, suf, &plist);

    /* Cleanup */
    free(Comment);
    free(Desc);
    free_plist(&plist);
    leave_playpen();
    return TRUE;	/* Success */
}
Beispiel #15
0
int custom_expand (char * param, char ***argvptr, int *argcptr)
{
	int     count,sl;
	size_t  bufsize;
	char    *filenamebuf;
	char    *ptr,*safeptr;

	/*
	 *  Check to see if we should do wild card expansion.
	 *  We only perform wildcard expansion if the parameter
	 *  was not a string and if it contains one of the
	 *  wild card characters.
	 *
	 *  We also do not expand any option that starts with '-'
	 *  as we then assume that it is a unix stylew option.
	 */
	if ((*param == '-') ||  (strpbrk (param,"*?") == NULL) ) {
	    return 0;
	}

	if ((filenamebuf = malloc (bufsize = FILEBUF_INIT)) == NULL) {
	    return -1;
	}
TRYAGAIN:
	count = getfnl (param, filenamebuf, bufsize, QDR_ALL);
	if (count == -1  && errno == ENOMEM) {
	    /*
	     *  We have overflowed the buffer, so we try
	     *  to get a bigger buffer and try again.
	     */
	    bufsize += FILEBUF_INCR;
	    if ((filenamebuf = realloc (filenamebuf, bufsize)) == NULL) {
	        return -1;
	    } else {
	        goto TRYAGAIN;
	    }
	}
	/*
	 *  If no files were found, then return unexpanded.
	 */
	if (count == 0) {
	    free (filenamebuf);
	    return 0;
	}
	/*
	 *  Files were found, so add these to the list instead
	 *  of the original parameter typed by the user.
	 */
	for ( ptr=filenamebuf ; count > 0 ; count -- ) {
		*argvptr = (char **) realloc (*argvptr, (size_t) (((*argcptr) + 2) * sizeof (char *)));
		safeptr= (char *) malloc ((size_t) (sl=strlen (ptr) + 1));
		if (safeptr == NULL || *argvptr == NULL) {
			return -1;
		}
		(void) memcpy (safeptr,ptr, (size_t) sl);
		(*argvptr) [*argcptr] = safeptr;
		*argcptr += 1;
		ptr += sl;
	}
	free (filenamebuf);
	return *argcptr;
}
Beispiel #16
0
void KFMExec::slotMimeType( const char *_type )
{
    // A dirty hack for passing the character set
    char *typestr=0;
    const char *aType=0;
    const char *aCharset=0;
    if ( _type )
    {
        typestr=new char[strlen(_type)+1];
        strcpy(typestr,_type);
	aType=strtok(typestr," ;\t\n");
	char *tmp;
	while((tmp=strtok(0," ;\t\n"))){
            if ( strncmp(tmp,"charset=",8)==0 ) aCharset=tmp+8;
	}    
	if ( aCharset != 0 )
	{
	    tmp=strpbrk((char*)aCharset," ;\t\n");
	    if ( tmp != 0 ) *tmp=0;
	}    
    }  
    
    // Stop browsing. We need an application
    job->stop();
    // delete job;
    // job = 0L;
    
    // GZIP
    if ( aType && strcmp( aType, "application/x-gzip" ) == 0L )
    {
	job->stop();
	tryURL += "#gzip:/";
	openURL( tryURL );
    }
    // TAR
    else if ( aType && strcmp( aType, "application/x-tar" ) == 0L )
    {
	// Is this tar file perhaps hosted in a gzipped file ?
	KURL u( tryURL );
	// ... then we already have a 'gzip' subprotocol
	if ( u.hasSubProtocol() )
	{
	    KURL u2( u.nestedURL() );
	    if ( strcmp( u2.protocol(), "gzip" ) == 0 )
	    {
		// Remove the 'gzip' protocol. It will only slow down the process,
		// since two subprotocols '#gzip:/#tar:/' are not very fast
		// right now.
		tryURL = u.parentURL();
	    }
	}
	
	job->stop();
	tryURL += "#tar:/";
	openURL( tryURL );
    }
    // No HTML ?
    else if ( aType == 0L || strcmp( aType, "text/html" ) != 0L )
    {
      bool bdone = false;
      // Do we know the mime type ?
      if ( aType != 0L )
      {
	KMimeType *mime = KMimeType::findByName( aType );
	// Try to run the URL if we know the mime type
	if ( mime && mime->run( tryURL ) )
	{
	  // We are a zombie now
	  prepareToDie();
	  bdone = true;
	}
      }
		
      if ( !bdone )
      {    
	// Ask the user what we should do
	OpenWithDlg l( klocale->translate("Open With:"), "", 0L, true );
	if ( l.exec() )
	{
	  KMimeBind *bind = l.mimeBind();
	  if ( bind )
	  {
	    bind->runBinding( tryURL );
	  }
	  else
	  {
	    QString pattern = l.getText();
	    // The user did not something ?
	    if ( !pattern.isEmpty() )
	    {
	      QStrList list;
	      list.append( tryURL );
	      openWithOldApplication( pattern, list );
	    }

	    // We are a zombie now
	    prepareToDie();
	  }	
	}
      }
    }
    // It is HTML
    else
    {
	// Ok, lets open a new window
	KfmGui *m = new KfmGui( 0L, 0L, tryURL );
	if ( aCharset != 0 ) m->setCharset(aCharset);
	if ( dlg )
	  {
	    delete dlg;
	    dlg = 0L;
	  }
	m->show();
	
	// We are a zombie now
	prepareToDie();
    }
    delete typestr;
}
Beispiel #17
0
//------------------------------------------------------------------------------
static void quote_matches(char** matches)
{
    // The least disruptive way to inject quotes into the command line is do it
    // at the last possible moment. Either the first match (the lcd) needs a
    // quote, or the next character the user may type needs quoting

    char** m;
    int need_quote;
    int lcd_length;
    int lcd_needs_quote;

    // Does the lcd have a quote char? Readline will add the quote if it thinks
    // it's completing file names.
    lcd_needs_quote = strpbrk(matches[0], rl_filename_quote_characters) != NULL;
    if (lcd_needs_quote && (rl_filename_completion_desired != 0))
    {
        return;
    }

    if (rl_completion_quote_character == '\"')
    {
        return;
    }

    if (rl_completion_suppress_quote)
    {
        return;
    }

    // Check other matches for characters that need quoting.
    need_quote = lcd_needs_quote;
    lcd_length = (int)strlen(matches[0]);
    m = matches + 1;
    while (*m && !need_quote)
    {
        int i;

        i = strlen(*m);
        if (i > lcd_length)
        {
            int c = *(*m + lcd_length);
            need_quote = strchr(rl_filename_quote_characters, c) != NULL;
        }

        ++m;
    }

    // So... do we need to prepend a quote?
    if (need_quote)
    {
        char* c = malloc(strlen(matches[0]) + 8);
        strcpy(c + 1, matches[0]);
        free(matches[0]);

        c[0] = '\"';
        matches[0] = c;

        // If there's a single match then there should be a closing quote.
        if (m - matches == 1)
        {
            strcat(c, "\"");
        }
    }
}
Beispiel #18
0
int main(int argc, char *argv[])
{   
	/* System call shell command */
    
	system("ls -l >> assignment.txt");
    
    /* Read shell command results */

    char temp_hold[LENGTH];
    char permission_hold[LENGTH];
    char *filesize_hold;
    int permission_check = 0;
    int filesize_check = 0;
    char *delim = " ";
    int loop_control;
    char *permission_argv;
    int condition = 0;
    char *filesize_temp;
    int temp_int = 0;
    int flag = 0;


	FILE *fp;
	fp = fopen("./assignment.txt", "r");
    if(fp == NULL)
    {
    	printf("No Such File !!!\n");
    }
    fgets(temp_hold, STRING, fp);
    


	char *num = "1234567890";
	char *p;
    if(argc == 2)
    {  
       p = strpbrk(argv[1], num);
       if(!p)
       {  
          //Only Permission Check
       	  while(!feof(fp))
          {  
             flag = 2;
             fgets(temp_hold, STRING, fp);
             strcpy(permission_hold, strtok(temp_hold, delim));
             permission_argv = strndup(permission_hold+1, 9);
             condition = check_permission(permission_argv, argv[1]);
             if(condition == 1)
             {
                permission_check += 1;
             }

          }
       }
       else
       {  
          //Only Filesize Check
          while(!feof(fp))
          { 
            flag = 1;
            loop_control = 0;
            fgets(temp_hold, STRING, fp);
            filesize_hold = strtok_r(temp_hold, " ", &filesize_temp);
            while(filesize_hold != NULL)
            {   
                if(loop_control == 4)
                {
                   break;
                }
                filesize_hold = strtok_r(NULL, " ", &filesize_temp);
                loop_control++;
            }
            if(filesize_hold)
            {
                temp_int = atoi(filesize_hold);
                if(temp_int >= atoi(argv[1]))
                {
                    filesize_check += 1;

                }
            }
            
          }
       }
    }
    else if(argc == 3)
    {
         while(!feof(fp))
          {
            loop_control = 0;
            fgets(temp_hold, STRING, fp);
            filesize_hold = strtok_r(temp_hold, " ", &filesize_temp);
            while (filesize_hold != NULL)
            {   
                if(loop_control == 4)
                {
                   break;
                }
                filesize_hold = strtok_r(NULL, " ", &filesize_temp);
                loop_control++;
            }
            if(filesize_hold)
            {
                temp_int = atoi(filesize_hold);
                if(temp_int >= atoi(argv[1]))
                {
                    filesize_check += 1;

                }
            }
            
          }

        fclose(fp);

        FILE *fptr;
        fptr = fopen("./assignment.txt", "r");
        if(fptr == NULL)
        {
            printf("No Such File !!!\n");
        }
        fgets(temp_hold, STRING, fptr);
        while(!feof(fptr))
        {  
             fgets(temp_hold, STRING, fptr);
             strcpy(permission_hold, strtok(temp_hold, delim));
             permission_argv = strndup(permission_hold+1, 9);
             condition = check_permission(permission_argv, argv[2]);
             if(condition == 1)
             {
                permission_check += 1;
             }

        }
        fclose(fptr);

    }
    else if(argc == 1)
    {
    	printf("No argument !!\n");
    }
    permission_check = permission_check - 1;
    if(argc == 2)
    {
        if(flag == 1)
        {
           printf("%d \n", filesize_check);
        }
        if(flag == 2)
        {
           printf("%d \n", permission_check);
        }
    }
    if(argc == 3)
    {   
        if(filesize_check > permission_check)
        {
            printf("%d \n", permission_check);
        }
        else
        {
            printf("%d \n", filesize_check);
        }
    }

    return 0;
}
Beispiel #19
0
void SetupDebug(void)
{
    char var[256];

    kprintf("** codesets.library %s (%s) startup ****************************\n", LIB_REV_STRING, LIB_DATE);
    kprintf("Initializing runtime debugging:\n");

    if(GetVar("codesets.library.debug", var, sizeof(var), 0) > 0)
    {
        char *s = var;

        // static list of our debugging classes tokens.
        // in the yamdebug variable these classes always start with a @
        static struct {
            const char *token;
            unsigned long flag;
        } dbclasses[] =
        {
            { "ctrace",  DBC_CTRACE   },
            { "report",  DBC_REPORT   },
            { "assert",  DBC_ASSERT   },
            { "timeval", DBC_TIMEVAL  },
            { "debug",   DBC_DEBUG    },
            { "error",   DBC_ERROR    },
            { "warning", DBC_WARNING  },
            { "all",     DBC_ALL      },
            { NULL,      0            }
        };

        static struct {
            const char *token;
            unsigned long flag;
        } dbflags[] =
        {
            { "always",   DBF_ALWAYS  },
            { "startup",  DBF_STARTUP },
            { "utf",      DBF_UTF     },
            { "all",      DBF_ALL     },
            { NULL,       0           }
        };

        // we parse the env variable token-wise
        while(*s)
        {
            ULONG i;
            char *e;

            if((e = strpbrk(s, " ,;")) == NULL)
                e = s+strlen(s);

            // check if the token is class definition or
            // just a flag definition
            if(s[0] == '@')
            {
                // skip the '@'
                s++;
                // check if this call is a negation or not
                if(s[0] == '!')
                {
                    // skip the '!'
                    s++;
                    // search for the token and clear the flag
                    for(i=0; dbclasses[i].token; i++)
                    {
                        if(strnicmp(s, dbclasses[i].token, strlen(dbclasses[i].token)) == 0)
                        {
                            kprintf("clear '%s' debug class flag.\n", dbclasses[i].token);
                            CLEAR_FLAG(debug_classes, dbclasses[i].flag);
                        }
                    }
                }
                else
                {
                    // search for the token and set the flag
                    for(i=0; dbclasses[i].token; i++)
                    {
                        if(strnicmp(s, dbclasses[i].token, strlen(dbclasses[i].token)) == 0)
                        {
                            kprintf("set '%s' debug class flag\n", dbclasses[i].token);
                            SET_FLAG(debug_classes, dbclasses[i].flag);
                        }
                    }
                }
            }
            else
            {
                // check if this call is a negation or not
                if(s[0] == '!')
                {
                    // skip the '!'
                    s++;
                    for(i=0; dbflags[i].token; i++)
                    {
                        if(strnicmp(s, dbflags[i].token, strlen(dbflags[i].token)) == 0)
                        {
                            kprintf("clear '%s' debug flag\n", dbflags[i].token);
                            CLEAR_FLAG(debug_flags, dbflags[i].flag);
                        }
                    }
                }
                else
                {
                    // check if the token was "ansi" and if so enable the ANSI color
                    // output
                    if(strnicmp(s, "ansi", 4) == 0)
                    {
                        kprintf("ansi output enabled\n");
                        ansi_output = TRUE;
                    }
                    else
                    {
                        for(i=0; dbflags[i].token; i++)
                        {
                            if(strnicmp(s, dbflags[i].token, strlen(dbflags[i].token)) == 0)
                            {
                                kprintf("set '%s' debug flag\n", dbflags[i].token);
                                SET_FLAG(debug_flags, dbflags[i].flag);
                            }
                        }
                    }
                }
            }

            // set the next start to our last search
            if(*e)
                s = ++e;
            else
                break;
        }
    }

    kprintf("set debug classes/flags (env:codesets.library.debug): %08lx/%08lx\n", debug_classes, debug_flags);
    kprintf("** Normal processing follows ***************************************\n");
}
Beispiel #20
0
/* EAM Nov 2012:
 * Unbelievably, the count parameter has been silently ignored or
 * improperly applied ever since this routine was introduced back
 * in version 3.7.  Now fixed to prevent buffer overflow.
 */
void
gprintf(
    char *outstring,
    size_t count,
    char *format,
    double log10_base,
    double x)
{
    char tempdest[MAX_LINE_LEN + 1];
    char temp[MAX_LINE_LEN + 1];
    char *t;
    TBOOLEAN seen_mantissa = FALSE; /* remember if mantissa was already output */
    double stored_power_base = 0;   /* base for the last mantissa output*/
    int stored_power = 0;	/* power matching the mantissa output earlier */
    TBOOLEAN got_hash = FALSE;

    char *dest  = &tempdest[0];
    char *limit = &tempdest[MAX_LINE_LEN];
#define remaining_space (size_t)(limit-dest)

    *dest = '\0';

    set_numeric_locale();

    /* Oct 2013 - default format is now expected to be "%h" */
    if (((term->flags & TERM_IS_LATEX)) && !strcmp(format, DEF_FORMAT))
	format = DEF_FORMAT_LATEX;

    for (;;) {
	/*{{{  copy to dest until % */
	while (*format != '%')
	    if (!(*dest++ = *format++) || (remaining_space == 0)) {
		goto done;
	    }
	/*}}} */

	/*{{{  check for %% */
	if (format[1] == '%') {
	    *dest++ = '%';
	    format += 2;
	    continue;
	}
	/*}}} */

	/*{{{  copy format part to temp, excluding conversion character */
	t = temp;
	*t++ = '%';
	if (format[1] == '#') {
	    *t++ = '#';
	    format++;
	    got_hash = TRUE;
	}
	/* dont put isdigit first since side effect in macro is bad */
	while (*++format == '.' || isdigit((unsigned char) *format)
	       || *format == '-' || *format == '+' || *format == ' '
	       || *format == '\'')
	    *t++ = *format;
	/*}}} */

	/*{{{  convert conversion character */
	switch (*format) {
	    /*{{{  x and o */
	case 'x':
	case 'X':
	case 'o':
	case 'O':
	    if (fabs(x) >= (double)INT_MAX) {
		t[0] = 'l';
		t[1] = 'l';
		t[2] = *format;
		t[3] = '\0';
		snprintf(dest, remaining_space, temp, (long long) x);
	    } else {
		t[0] = *format;
		t[1] = '\0';
		snprintf(dest, remaining_space, temp, (int) x);
	    }
	    break;
	    /*}}} */
	    /*{{{  e, f and g */
	case 'e':
	case 'E':
	case 'f':
	case 'F':
	case 'g':
	case 'G':
	    t[0] = *format;
	    t[1] = 0;
	    snprintf(dest, remaining_space, temp, x);
	    break;
	case 'h':
	case 'H':
	    /* g/G with enhanced formating (if applicable) */
	    t[0] = (*format == 'h') ? 'g' : 'G';
	    t[1] = 0;

	    if ((term->flags & (TERM_ENHANCED_TEXT | TERM_IS_LATEX)) == 0) {
		/* Not enhanced, not latex, just print it */
		snprintf(dest, remaining_space, temp, x);

	    } else if (table_mode) {
		/* Tabular output should contain no markup */
		snprintf(dest, remaining_space, temp, x);

	    } else {
		/* in enhanced mode -- convert E/e to x10^{foo} or *10^{foo} */
#define LOCAL_BUFFER_SIZE 256
		char tmp[LOCAL_BUFFER_SIZE];
		char tmp2[LOCAL_BUFFER_SIZE];
		int i,j;
		TBOOLEAN bracket_flag = FALSE;
		snprintf(tmp, 240, temp, x); /* magic number alert: why 240? */
		for (i=j=0; tmp[i] && (i < LOCAL_BUFFER_SIZE); i++) {
		    if (tmp[i]=='E' || tmp[i]=='e') {
			if ((term-> flags & TERM_IS_LATEX)) {
			    if (*format == 'h') {
				strcpy(&tmp2[j], "\\times");
				j+= 6;
			    } else {
				strcpy(&tmp2[j], "\\cdot");
				j+= 5;
			    }
			} else if (encoding == S_ENC_UTF8) {
			    strcpy(&tmp2[j], "\xc3\x97"); /* UTF character '×' */
			    j+= 2;
			} else if (encoding == S_ENC_CP1252) {
			    tmp2[j++] = (*format=='h') ? 0xd7 : 0xb7;
			} else {
			    tmp2[j++] = (*format=='h') ? 'x' : '*';
			}
			strcpy(&tmp2[j], "10^{");
			j += 4;
			bracket_flag = TRUE;

			/* Skip + and leading 0 in exponent */
			i++; /* skip E */
			if (tmp[i] == '+')
			    i++;
			else if (tmp[i] == '-') /* copy sign */
			    tmp2[j++] = tmp[i++];
			while (tmp[i] == '0')
			    i++;
			i--; /* undo following loop increment */
		    } else {
			tmp2[j++] = tmp[i];
		    }
		}
		if (bracket_flag)
		    tmp2[j++] = '}';
		tmp2[j] = '\0';
		strncpy(dest, tmp2, remaining_space);
#undef LOCAL_BUFFER_SIZE
	    }

	    break;

	    /*}}} */
	    /*{{{  l --- mantissa to current log base */
	case 'l':
	    {
		double mantissa;

		t[0] = 'f';
		t[1] = 0;
		stored_power_base = log10_base;
		mant_exp(stored_power_base, x, FALSE, &mantissa,
				&stored_power, temp);
		seen_mantissa = TRUE;
		snprintf(dest, remaining_space, temp, mantissa);
		break;
	    }
	    /*}}} */
	    /*{{{  t --- base-10 mantissa */
	case 't':
	    {
		double mantissa;

		t[0] = 'f';
		t[1] = 0;
		stored_power_base = 1.0;
		mant_exp(stored_power_base, x, FALSE, &mantissa,
				&stored_power, temp);
		seen_mantissa = TRUE;
		snprintf(dest, remaining_space, temp, mantissa);
		break;
	    }
	    /*}}} */
	    /*{{{  s --- base-1000 / 'scientific' mantissa */
	case 's':
	    {
		double mantissa;

		t[0] = 'f';
		t[1] = 0;
		stored_power_base = 1.0;
		mant_exp(stored_power_base, x, TRUE, &mantissa,
				&stored_power, temp);
		seen_mantissa = TRUE;
		snprintf(dest, remaining_space, temp, mantissa);
		break;
	    }
	    /*}}} */
	    /*{{{  b --- base-1024 mantissa */
	case 'b':
	    {
		double mantissa;

		t[0] = 'f';
		t[1] = 0;
		stored_power_base = log10(1024);
		mant_exp(stored_power_base, x, FALSE, &mantissa,
				&stored_power, temp);
		seen_mantissa = TRUE;
		snprintf(dest, remaining_space, temp, mantissa);
		break;
	    }
	    /*}}} */
	    /*{{{  L --- power to current log base */
	case 'L':
	    {
		int power;

		t[0] = 'd';
		t[1] = 0;
		if (seen_mantissa)
		    if (stored_power_base == log10_base)
			power = stored_power;
		    else
			int_error(NO_CARET, "Format character mismatch: %%L is only valid with %%l");
		else
		    stored_power_base = log10_base;
		    mant_exp(log10_base, x, FALSE, NULL, &power, "%.0f");
		snprintf(dest, remaining_space, temp, power);
		break;
	    }
	    /*}}} */
	    /*{{{  T --- power of ten */
	case 'T':
	    {
		int power;

		t[0] = 'd';
		t[1] = 0;
		if (seen_mantissa)
		    if (stored_power_base == 1.0)
			power = stored_power;
		    else
			int_error(NO_CARET, "Format character mismatch: %%T is only valid with %%t");
		else
		    mant_exp(1.0, x, FALSE, NULL, &power, "%.0f");
		snprintf(dest, remaining_space, temp, power);
		break;
	    }
	    /*}}} */
	    /*{{{  S --- power of 1000 / 'scientific' */
	case 'S':
	    {
		int power;

		t[0] = 'd';
		t[1] = 0;
		if (seen_mantissa)
		    if (stored_power_base == 1.0)
			power = stored_power;
		    else
			int_error(NO_CARET, "Format character mismatch: %%S is only valid with %%s");
		else
		    mant_exp(1.0, x, TRUE, NULL, &power, "%.0f");
		snprintf(dest, remaining_space, temp, power);
		break;
	    }
	    /*}}} */
	    /*{{{  c --- ISO decimal unit prefix letters */
	case 'c':
	    {
		int power;

		t[0] = 'c';
		t[1] = 0;
		if (seen_mantissa)
		    if (stored_power_base == 1.0)
			power = stored_power;
		    else
			int_error(NO_CARET, "Format character mismatch: %%c is only valid with %%s");
		else
		    mant_exp(1.0, x, TRUE, NULL, &power, "%.0f");

		if (power >= -24 && power <= 24) {
		    /* -18 -> 0, 0 -> 6, +18 -> 12, ... */
		    /* HBB 20010121: avoid division of -ve ints! */
		    power = (power + 24) / 3;
		    snprintf(dest, remaining_space, temp, "yzafpnum kMGTPEZY"[power]);
		} else {
		    /* please extend the range ! */
		    /* name  power   name  power
		       -------------------------
		       yocto  -24    yotta  24
		       zepto  -21    zetta  21
		       atto   -18    Exa    18
		       femto  -15    Peta   15
		       pico   -12    Tera   12
		       nano    -9    Giga    9
		       micro   -6    Mega    6
		       milli   -3    kilo    3   */

		    /* fall back to simple exponential */
		    snprintf(dest, remaining_space, "e%+02d", power);
		}
		break;
	    }
	    /*}}} */
	    /*{{{  B --- IEC 60027-2 A.2 / ISO/IEC 80000 binary unit prefix letters */
	case 'B':
	    {
		int power;

		t[0] = 'c';
		t[1] = 'i';
		t[2] = 0;
		if (seen_mantissa)
		    if (stored_power_base == log10(1024))
			power = stored_power;
		    else
			int_error(NO_CARET, "Format character mismatch: %%B is only valid with %%b");
		else
			mant_exp(log10(1024), x, FALSE, NULL, &power, "%.0f");

		if (power > 0 && power <= 8) {
		    /* name  power
		       -----------
		       Yobi   8
		       Zebi   7
		       Exbi   9
		       Pebi   5
		       Tebi   4
		       Gibi   3
		       Mebi   2
		       kibi   1   */
		    snprintf(dest, remaining_space, temp, " kMGTPEZY"[power]);
		} else if (power > 8) {
		    /* for the larger values, print x2^{10}Gi for example */
		    snprintf(dest, remaining_space, "x2^{%d}Yi", power-8);
		} else if (power < 0) {
		    snprintf(dest, remaining_space, "x2^{%d}", power*10);
		}

		break;
	    }
	    /*}}} */
	    /*{{{  P --- multiple of pi */
	case 'P':
	    {
		t[0] = 'f';
		t[1] = 0;
		snprintf(dest, remaining_space, temp, x / M_PI);
		break;
	    }
	    /*}}} */
	default:
	   reset_numeric_locale();
	   int_error(NO_CARET, "Bad format character");
	} /* switch */
	/*}}} */

	if (got_hash && (format != strpbrk(format,"oeEfFgG"))) {
	   reset_numeric_locale();
	   int_error(NO_CARET, "Bad format character");
	}

    /* change decimal '.' to the actual entry in decimalsign */
	if (decimalsign != NULL) {
	    char *dotpos1 = dest;
	    char *dotpos2;
	    size_t newlength = strlen(decimalsign);

	    /* dot is the default decimalsign we will be replacing */
	    int dot = *get_decimal_locale();

	    /* replace every dot by the contents of decimalsign */
	    while ((dotpos2 = strchr(dotpos1,dot)) != NULL) {
		if (newlength == 1) {	/* The normal case */
		    *dotpos2 = *decimalsign;
		    dotpos1++;
		} else {		/* Some multi-byte decimal marker */
		    size_t taillength = strlen(dotpos2);
		    dotpos1 = dotpos2 + newlength;
		    if (dotpos1 + taillength > limit)
			int_error(NO_CARET,
				  "format too long due to decimalsign string");
		    /* move tail end of string out of the way */
		    memmove(dotpos1, dotpos2 + 1, taillength);
		    /* insert decimalsign */
		    memcpy(dotpos2, decimalsign, newlength);
		}
	    }
	}

	/* this was at the end of every single case, before: */
	dest += strlen(dest);
	++format;
    } /* for ever */

done:

#if (0)
    /* Oct 2013 - Not safe because it fails to recognize LaTeX macros.	*/
    /* For LaTeX terminals, if the user has not already provided a   	*/
    /* format in math mode, wrap whatever we got by default in $...$ 	*/
    if (((term->flags & TERM_IS_LATEX)) && !strchr(tempdest, '$')) {
	*(outstring++) = '$';
	strcat(tempdest, "$");
	count -= 2;
    }
#endif

    /* Copy as much as fits */
    safe_strncpy(outstring, tempdest, count);

    reset_numeric_locale();
}
Beispiel #21
0
void test_str(void) {
	char	v1[128], *sep, *p;

	pr("strlen");
	if (strlen("\0") != 0) fail("strlen-1");
	if (strlen("0123456789abcdef") != 16) fail("strlen-2");

	pr("strcmp");
	if (strcmp("\0", "\0")) fail("strcmp-1");
	if (strcmp("abcdef", "abcdef")) fail("strcmp-2");
	if (strcmp("abcdef", "abcdefg") >= 0) fail("strcmp-3");
	if (strcmp("abcdefg", "abcdef") <= 0) fail("strcmp-4");
	if (strcmp("abcdef0", "abcdef3") >= 0) fail("strcmp-5");

	pr("strcpy");
	strcpy(v1, "0123456789ABCDEF");
	if (strcmp(v1, "0123456789ABCDEF")) fail("strcpy-1");
	strcpy(v1, "ABCDEF");
	if (strcmp(v1, "ABCDEF")) fail("strcpy-2");
	if (v1[7] != '7') fail("strcpy-3");

	pr("strcat");
	strcpy(v1, "abcXXXXX"); v1[3] = 0;
	strcat(v1, "DEF");
	if (strcmp(v1, "abcDEF")) fail("strcat-1");
	if (v1[7] != 'X') fail("strcat-2");

	pr("strncmp");
	if (strncmp("abcdef", "abcdef", 6)) fail("strncmp-1");
	if (strncmp("abcdxx", "abcdyy", 4)) fail("strncmp-2");
	if (strncmp("abcdx0", "abcdy9", 5) >= 0) fail("strncmp-3");
	if (strncmp("abcdy0", "abcdx9", 5) <= 0) fail("strncmp-4");
	if (strncmp("abcdef", "abcdef", 10)) fail("strncmp-5");
	if (strncmp("abcdefg", "abcdef", 7) <= 0) fail("strncmp-6");
	if (strncmp("abcdef", "abcdefg", 7) >= 0) fail("strncmp-7");
	if (strncmp("abcdefg", "abcdef", 10) <= 0) fail("strncmp-8");
	if (strncmp("abcdef", "abcdefg", 10) >= 0) fail("strncmp-9");

	pr("strncpy");
	strcpy(v1, "0123456789");
	strncpy(v1, "abcdef", 6);
	if (strcmp(v1, "abcdef6789")) fail("strncpy-1");
	strcpy(v1, "0123456789");
	strncpy(v1, "0123", 5);
	if (memcmp(v1, "0123\00056789", 10)) fail("strncpy-2");
	strncpy(v1, "0123", 10);
	if (memcmp(v1, "0123\0\0\0\0\0\0", 10)) fail("strncpy-3");

	pr("strncat");
	strcpy(v1, "012345");
	strncat(v1, "6789", 5);
	if (strcmp(v1, "0123456789")) fail("strncat-1");
	strncat(v1, "abcdef0000", 6);
	if (strcmp(v1, "0123456789abcdef")) fail("strncat-2");

	pr("strspn");
	if (strspn("abcdefg", "abc") != 3) fail("strspn-1");
	if (strspn("abcabcabcdefg", "abc") != 9) fail("strspn-2");
	if (strspn("abcdefg", "") != 0) fail("strspn-3");

	pr("strcspn");
	if (strcspn("abcdefg", "def") != 3) fail("strcspn-1");
	if (strcspn("abcabcabcdefg", "def") != 9) fail("strcspn-2");
	if (strcspn("abcdefg", "") != 7) fail("strcspn-2");
	if (strcspn("abcdefg", "xyz") != 7) fail("strcspn-3");

	pr("strpbrk");
	strcpy(v1, "abcdef");
	if (strpbrk(v1, "def") != v1 + 3) fail("strpbrk-1");
	strcpy(v1, "abcabcabcdef");
	if (strpbrk(v1, "def") != v1 + 9) fail("strpbrk-2");
	if (strpbrk("abcdef", "") != NULL) fail("strpbrk-2");
	if (strpbrk("abcdef", "xyz") != NULL) fail("strpbrk-3");

	pr("strtok");
	sep = "+-*";
	strcpy(v1, "foo++bar---baz*goo");
	if (!(p = strtok(v1, sep)) || strcmp(p, "foo")) fail("strtok-1");
	if (!(p = strtok(NULL, sep)) || strcmp(p, "bar")) fail("strtok-2");
	if (!(p = strtok(NULL, sep)) || strcmp(p, "baz")) fail("strtok-3");
	if (!(p = strtok(NULL, sep)) || strcmp(p, "goo")) fail("strtok-4");
	if (strtok(NULL, sep) != NULL) fail("strtok-5");
	if (strtok(NULL, sep) != NULL) fail("strtok-6");
}
/* ------------------------------------------------------------------------ */
short mtn_cfg_ReadConfigString(char *p_blockname, char *p_config,
    char *p_parameter)
{
    char buffer[BUFSIZ+1];
    char *ptr;
    short status;
    short ii, ll, blkno;

    status = OPENERR;
    blkno = -1;

	/* search through the cfg_table for block identified by <p_blockname>	*/
    for (ii=0; ii<cfg_count; ii++)
    {
        if (strcmp(p_blockname, cfg_table[ii].prf_blk_name) == 0)
        {
            blkno = ii;
            break; // ii = cfg_count + 1;, once find the first, donot continue to search and waist time, 20080915
        }
    }

    status = OPENERR;
	if (blkno != -1)
    {
        status = OPENERR;
		/* the desired block found, now, move the file pointer to the		*/
		/* starting line for that block 									*/
        fseek(fp_config, cfg_table[blkno].start_file_pos, 0);

		/* try to locate the configuration string within the number of line */
		/* of the block, and then read it value 							*/
        for (ll=0; ll<cfg_table[blkno].num_of_lines && status == OPENERR; ll++)
        {
            if (fgets(buffer, BUFSIZ, fp_config) != NULL)
            {
                //  Added 30Oct2003
                ptr = &buffer[0];
                while(ptr[0] == ' ') // skip the space at the beginning
                    ptr++;

                if (*ptr != '#' && *ptr != ';') // if the line starts with '#' or ';', the line is a comment line
                {
					/* this is not a remark line, locate the desired string */
					/* if string found, check for equal sign then read the	*/
					/* parameter											*/
                    ptr = strstr(ptr, p_config);
                    if (ptr != NULL)
                    {
                        ptr = ptr + strlen(p_config);

                        //  Added 5Jan2004 to exactly match the config string
                        //  seperation string can only be one of followings 20080915
						// ' ': space, 
						// '=': equality,
						// '\t': Tab
                        if (ptr[0] != ' ' && ptr[0] != '=' && ptr[0] != '\t')  // 20080915
                        {
                            continue;
                        }

						/* look for equal sign */
						ptr = strpbrk(ptr, "=");
                        if (ptr != NULL)
                        {
                            ptr++;
                            while (*ptr == ' ')
                                ptr++;

                            if (*ptr == '\"') // ignore the string starting and ending: "
                            {
                                ptr++;
                                ii=0;
                                while (*(ptr+ii) != '\"')
                                    ii++;
                                *(ptr+ii) = 0;
                                strcpy(p_parameter,  ptr); // MTN_API_MAX_STRLEN_FEATURENAME,
                                status = READOK;
                            }
                            //@a, add one more case. // can read a block structure
                            else if (*ptr == '<')
                            {
                                ptr++;
                                ii=0;
                                while (*(ptr+ii) != '>')
                                    ii++;
                                *(ptr+ii) = 0;
                                strcpy(p_parameter, ptr);
                                status = READOK;
                            }
                            else
                            {
                                ii=0;
                                while ((*(ptr+ii) != ' ')  &&
                                       (*(ptr+ii) != '#')  &&
                                       (*(ptr+ii) != '\n') &&
                                       (*(ptr+ii) != '\r') &&
									   (*(ptr+ii) != '\t') &&  // 20080915
                                       (*(ptr+ii) != 0) )
                                    ii++;
								*(ptr+ii) = 0;	/* end the string */
                                strcpy(p_parameter, ptr);
                                status = READOK;
							}	/* is it string or number */
						}	/* if equal sign found */
					}	/* if string found */
				}	/* if not remark line */
            }   /* if fgets ... */
        }   /* for loop */
    }
    return (status);
}
Beispiel #23
0
void dir2ls(PCStr(dirpath),FileStat *stp,PCStr(opt),xPVStr(fmt),FILE *fp)
{	const char *op;
	const char *dp;
	int onow;
	int flags;
	char sortspec;
	LsArg lsa;
	CStr(fmt_s,256);
	CStr(fmt_a,256);
	CStr(line,2048);
	int f_l,f_s;
	CStr(fmt_b,256);
	CStr(spath,1024);
	const char *vbase = 0;
	CStr(vbaseb,1024);

	CStr(xpath,1024);
	if( pathnorm("sort_ls",dirpath,AVStr(xpath)) ){
		dirpath = xpath;
	}

	if( opt == NULL )
		opt = "";

	bzero(&lsa,sizeof(lsa));
	lsa.l_tfmt = getenv("LSTFMT");
	flags = 0;

	for( op = opt; *op; op++ ){
		switch( *op ){
			case 'a':
				lsa.l_all = 1;
				break;
			case 'l':
				flags |= O_FORM_L;
				break;
			case 's':
				flags |= O_FORM_S;
				break;
			case 'L':
				lsa.l_reflink = 1;
				break;
			case 'V':
				lsa.l_virtual = 1;
				break;
			case 'd':
				flags |= O_PUTSELF;
				break;
			case 't':
				flags |= O_TIMESORT;
				break;
			case 'z':
				flags |= O_SIZESORT;
				break;
			case 'u':
				flags |= O_BYATIME;
				break;
			case '*':
				flags |= O_REXP;
				break;
			case '/':
				flags |= O_VBASE;
				vbase = op + 1;
				while( op[1] ) *op++; /* skip remaining */
				if( strpbrk(vbase,"*?[") ){
/* vbase is "const" */
					strcpy(vbaseb,vbase);
					vbase = vbaseb;
					if( dp = strrchr(vbase,'/') )
						((char*)dp)[1] = 0;
					else	Xstrcpy(QVStr((char*)vbase,vbaseb),"");
				}
				break;
		}
	}
	if( (DoFileRexp || (flags & O_REXP)) && strpbrk(dirpath,"*?[") ){
		strcpy(spath,dirpath);
		dirpath = spath;
		if( dp = strrchr(dirpath,'/') ){
			lsa.l_maskrexp = frex_create(dp + 1);
			truncVStr(dp);
		}else{
			lsa.l_maskrexp = frex_create(dirpath);
			dirpath = ".";
		}
	}

	if( fmt == NULL ){
		cpyQStr(fmt,fmt_b);
		setVStrEnd(fmt,0);

		if( flags & O_FORM_S )
			strcat(fmt,"%4K ");
		if( flags & O_FORM_L )
			strcat(fmt,"%T%M %2L %-8O %8S %D ");
			/*
			strcat(fmt,"%T%M%3L %-8O %8S %D ");
			*/

		if( flags & O_VBASE )
			strcat(fmt,"%V");
		else	strcat(fmt,"%N");
	}

	if( flags & O_TIMESORT ){
		if( flags & O_BYATIME )
			sortspec = 'a';
		else	sortspec = 'm';
		sprintf(fmt_s,"%%%c%s",sortspec,fmt);
		fmt = fmt_s;
	}
	if( flags & O_SIZESORT ){
		sprintf(fmt_s,"%%%c%s",'z',fmt);
		fmt = fmt_s;
	}
	if( flags & O_BYATIME ){
		strcpy(fmt_a,fmt);
		fmt = fmt_a;
		if( dp = strstr(fmt,"%D") )
			((char*)dp)[1] = 'U';
	}

	lsa.l_dir = dirpath;
	lsa.l_vbase = (char*)vbase;
	lsa.l_stp = stp;
	lsa.l_fmt = (char*)fmt;
	lsa.l_out = fp;
	setQStr(lsa.l_buf,line,sizeof(line));
	line[0] = 0;

	onow = TIME_NOW;
	TIME_NOW = time(0);
	setpwent();

	if( !(flags & O_PUTSELF) && fileIsdir(dirpath) )
		sort_ls(dirpath,&lsa);
	else{
		lsa.l_dir = "";
		lsa.l_all = 1;
		ls1(dirpath,&lsa);
		fprintf(fp,"%s\r\n",lsa.l_buf);
	}

	endpwent();
	TIME_NOW = onow;

	if( lsa.l_maskrexp )
		frex_free(lsa.l_maskrexp);
	return;
}
Beispiel #24
0
void dmstk_combine_filters( char *inString, char *filter )
{
  char region[MAX_ITEM_SIZE];

  char *tok;
  int bin, col, ext, filt;

  bin=0; col=0; ext=0; filt=0;


  tok = strtok( inString, "[]");
  while ( tok != NULL)
    {

      bin += ( strstr( tok, "bin " ) || strstr(tok, "BIN ") );
      col += ( strstr( tok, "cols ") || strstr(tok, "COLS ") ||
	       strstr( tok, "columns ") || strstr(tok, "COLUMNS ") );
      
      filt += ( !bin & (strpbrk( tok, "<=>:" ) != NULL));

      
      if ( !bin && !col && !filt ) ext+=1;



      if ( filt && !bin  )
	{
	  sprintf( region, "%s[%s,%s]", region, tok, filter );
	}
      else if ( !filt && bin )
	{
	  sprintf( region, "%s[%s][%s]", region, filter, tok );
	  filt =1;
	}
      else if ( !filt && col )
	{
	  sprintf( region, "%s[%s][%s]", region, filter, tok );
	  filt =1;
	}
      else if ( !filt && ( ext > 2 ) )
	{
	  sprintf( region, "%s[%s][%s]", region, filter, tok );      
	  filt = 1;
	}
      else if ( tok == inString )
	{
	  strcpy(region, tok );
	}
      else if ( ext <= 2 )
	{
	  sprintf( region, "%s[%s]", region, tok );
	}
      else
	{
	  sprintf( region, "%s[%s]", region, filter );
	}

      tok = strtok( NULL, "[]");
    }

  if ( !filt )
	  sprintf( region, "%s[%s]", region, filter );    

  strcpy( inString, region );
      
  return;

}
Beispiel #25
0
static int AddReg(lua_State * L) {
	if(lua_gettop(L) == 3) {
        if(lua_type(L, 1) != LUA_TSTRING || lua_type(L, 2) != LUA_TSTRING || lua_type(L, 3) != LUA_TNUMBER) {
            luaL_checktype(L, 1, LUA_TSTRING);
            luaL_checktype(L, 2, LUA_TSTRING);
            luaL_checktype(L, 3, LUA_TNUMBER);
            lua_settop(L, 0);
            lua_pushnil(L);
            return 1;
        }

        size_t szNickLen, szPassLen;
        char *sNick = (char *)lua_tolstring(L, 1, &szNickLen);
        char *sPass = (char *)lua_tolstring(L, 2, &szPassLen);

#if LUA_VERSION_NUM < 503
		uint16_t i16Profile = (uint16_t)lua_tonumber(L, 3);
#else
        uint16_t i16Profile = (uint16_t)lua_tounsigned(L, 3);
#endif

        if(i16Profile > clsProfileManager::mPtr->iProfileCount-1 || szNickLen == 0 || szNickLen > 64 || szPassLen == 0 || szPassLen > 64 || strpbrk(sNick, " $|") != NULL || strchr(sPass, '|') != NULL) {
            lua_settop(L, 0);
            lua_pushnil(L);
            return 1;
        }

        bool bAdded = clsRegManager::mPtr->AddNew(sNick, sPass, i16Profile);

        lua_settop(L, 0);

        if(bAdded == false) {
            lua_pushnil(L);
            return 1;
        }

        lua_pushboolean(L, 1);
        return 1;
    } else if(lua_gettop(L) == 2) {
        if(lua_type(L, 1) != LUA_TSTRING || lua_type(L, 2) != LUA_TNUMBER) {
            luaL_checktype(L, 1, LUA_TSTRING);
            luaL_checktype(L, 2, LUA_TNUMBER);
            lua_settop(L, 0);
            lua_pushnil(L);
            return 1;
        }

        size_t szNickLen;
        char *sNick = (char *)lua_tolstring(L, 1, &szNickLen);

#if LUA_VERSION_NUM < 503
		uint16_t ui16Profile = (uint16_t)lua_tonumber(L, 2);
#else
        uint16_t ui16Profile = (uint16_t)lua_tounsigned(L, 2);
#endif

        if(ui16Profile > clsProfileManager::mPtr->iProfileCount-1 || szNickLen == 0 || szNickLen > 64 || strpbrk(sNick, " $|") != NULL) {
            lua_settop(L, 0);
            lua_pushnil(L);
            return 1;
        }

        // check if user is registered
        if(clsRegManager::mPtr->Find(sNick, szNickLen) != NULL) {
            lua_settop(L, 0);
            lua_pushnil(L);
            return 1;
        }

        User * pUser = clsHashManager::mPtr->FindUser(sNick, szNickLen);
        if(pUser == NULL) {
            lua_settop(L, 0);
            lua_pushnil(L);
            return 1;
        }

        if(pUser->uLogInOut == NULL) {
            pUser->uLogInOut = new LoginLogout();
            if(pUser->uLogInOut == NULL) {
                pUser->ui32BoolBits |= User::BIT_ERROR;
                pUser->Close();

                AppendDebugLog("%s - [MEM] Cannot allocate new pUser->uLogInOut in RegMan.AddReg\n", 0);
                lua_settop(L, 0);
                lua_pushnil(L);
                return 1;
            }
        }

        pUser->SetBuffer(clsProfileManager::mPtr->ProfilesTable[ui16Profile]->sName);
        pUser->ui32BoolBits |= User::BIT_WAITING_FOR_PASS;

        int iMsgLen = sprintf(clsServerManager::sGlobalBuffer, "<%s> %s.|$GetPass|", clsSettingManager::mPtr->sPreTexts[clsSettingManager::SETPRETXT_HUB_SEC], clsLanguageManager::mPtr->sTexts[LAN_YOU_WERE_REGISTERED_PLEASE_ENTER_YOUR_PASSWORD]);
        if(CheckSprintf(iMsgLen, clsServerManager::szGlobalBufferSize, "RegMan.AddReg1") == true) {
            pUser->SendCharDelayed(clsServerManager::sGlobalBuffer, iMsgLen);
        }

        lua_settop(L, 0);
        lua_pushboolean(L, 1);
        return 1;
    } else {
        luaL_error(L, "bad argument count to 'RegMan.AddReg' (2 or 3 expected, got %d)", lua_gettop(L));
        lua_settop(L, 0);
        lua_pushnil(L);
        return 1;
    }
}
Beispiel #26
0
/*
 * Ensure that any exponent, if present, is at least MIN_EXPONENT_DIGITS
 * in length.
 */
static void
_ensure_minimum_exponent_length(char* buffer, size_t buf_size)
{
    char *p = strpbrk(buffer, "eE");
    if (p && (*(p + 1) == '-' || *(p + 1) == '+')) {
        char *start = p + 2;
        int exponent_digit_cnt = 0;
        int leading_zero_cnt = 0;
        int in_leading_zeros = 1;
        int significant_digit_cnt;

        /* Skip over the exponent and the sign. */
        p += 2;

        /* Find the end of the exponent, keeping track of leading zeros. */
        while (*p && isdigit(Py_CHARMASK(*p))) {
            if (in_leading_zeros && *p == '0') {
                ++leading_zero_cnt;
            }
            if (*p != '0') {
                in_leading_zeros = 0;
            }
            ++p;
            ++exponent_digit_cnt;
        }

        significant_digit_cnt = exponent_digit_cnt - leading_zero_cnt;
        if (exponent_digit_cnt == MIN_EXPONENT_DIGITS) {
            /*
             * If there are 2 exactly digits, we're done,
             * regardless of what they contain
             */
        }
        else if (exponent_digit_cnt > MIN_EXPONENT_DIGITS) {
            int extra_zeros_cnt;

            /*
             * There are more than 2 digits in the exponent.  See
             * if we can delete some of the leading zeros
             */
            if (significant_digit_cnt < MIN_EXPONENT_DIGITS) {
                significant_digit_cnt = MIN_EXPONENT_DIGITS;
            }
            extra_zeros_cnt = exponent_digit_cnt - significant_digit_cnt;

            /*
             * Delete extra_zeros_cnt worth of characters from the
             * front of the exponent
             */
            assert(extra_zeros_cnt >= 0);

            /*
             * Add one to significant_digit_cnt to copy the
             * trailing 0 byte, thus setting the length
             */
            memmove(start, start + extra_zeros_cnt, significant_digit_cnt + 1);
        }
        else {
            /*
             * If there are fewer than 2 digits, add zeros
             * until there are 2, if there's enough room
             */
            int zeros = MIN_EXPONENT_DIGITS - exponent_digit_cnt;
            if (start + zeros + exponent_digit_cnt + 1 < buffer + buf_size) {
                memmove(start + zeros, start, exponent_digit_cnt + 1);
                memset(start, '0', zeros);
            }
        }
    }
}
Beispiel #27
0
//
// Tests if a file name (WITHOUT PATH) is FAT compliant
// 1 - FAT compliant
// 0 - non FAT compliant
//
// ... could be better but seems to work !
//
int isfat(pchar component) {
    int len = strlen(component);
    int i, j, pos;


    if (strcmp(component, ".") == 0) {          // "."
        return 1;
    }

    if (strcmp(component, "..") == 0) {         // ".."
        return 1;
    }

    if ((len > 12) || (len == 0)) {
        return 0;                   // lenght > 8.3 or null
    }

    for (i = 0;i < nb_forbiden_names  ; i++) {
       if (strcmp(component, forbidden_names[i]) == 0) {
           return 0;
       } /* endif */
    } /* endfor */

    if (strpbrk(component, forbidden_chars) > 0) {
        return 0;                   // Forbidden characters present
    }

    j = 0;
    pos = 0;
    for (i = 0; i < len; i++) {
        if (component[i] == '.') {
            j++;
        } else{
           if (j == 0) {
               pos++;
           } /* endif */
        }
    }

    if (j > 1) {                    // More than one '.'
        return 0;
    }

    if (j == 0) {                   // No '.'
        if (len > 8) {
            return 0;
        } else {
            return 1;
        }
    }

    if (j == 1) {
        if ((len - pos > 4) || (pos == 0)) {            // '.' in front or extension > 3
            return 0;
        } else {
            if (pos > 8) {
                return 0;                               // name > 8
            } else {
               return 1;
            } /* endif */
        }
    }

    return 0;
}
Beispiel #28
0
/**
 * gst_rtsp_url_parse:
 * @urlstr: the url string to parse
 * @url: location to hold the result.
 *
 * Parse the RTSP @urlstr into a newly allocated #GstRTSPUrl. Free after usage
 * with gst_rtsp_url_free().
 *
 * Returns: a #GstRTSPResult.
 */
GstRTSPResult
gst_rtsp_url_parse (const gchar * urlstr, GstRTSPUrl ** url)
{
  GstRTSPUrl *res;
  gchar *p, *delim, *at, *col;
  gchar *host_end = NULL;
  guint i;

  g_return_val_if_fail (urlstr != NULL, GST_RTSP_EINVAL);
  g_return_val_if_fail (url != NULL, GST_RTSP_EINVAL);

  res = g_new0 (GstRTSPUrl, 1);

  p = (gchar *) urlstr;

  col = strstr (p, "://");
  if (col == NULL)
    goto invalid;

  for (i = 0; i < G_N_ELEMENTS (rtsp_schemes_map); i++) {
    if (g_ascii_strncasecmp (rtsp_schemes_map[i].scheme, p, col - p) == 0) {
      res->transports = rtsp_schemes_map[i].transports;
      p = col + 3;
      break;
    }
  }

  if (res->transports == GST_RTSP_LOWER_TRANS_UNKNOWN)
    goto invalid;

  delim = strpbrk (p, "/?");
  at = strchr (p, '@');

  if (at && delim && at > delim)
    at = NULL;

  if (at) {
    col = strchr (p, ':');

    /* must have a ':' and it must be before the '@' */
    if (col == NULL || col > at)
      goto invalid;

    res->user = g_strndup (p, col - p);
    col++;
    res->passwd = g_strndup (col, at - col);

    /* move to host */
    p = at + 1;
  }

  if (*p == '[') {
    res->family = GST_RTSP_FAM_INET6;

    /* we have an IPv6 address in the URL, find the ending ] which must be
     * before any delimiter */
    host_end = strchr (++p, ']');
    if (!host_end || (delim && host_end >= delim))
      goto invalid;

    /* a port specifier must follow the address immediately */
    col = host_end[1] == ':' ? host_end + 1 : NULL;
  } else {
    res->family = GST_RTSP_FAM_INET;

    col = strchr (p, ':');

    /* we have a ':' and a delimiter but the ':' is after the delimiter, it's
     * not really part of the hostname */
    if (col && delim && col >= delim)
      col = NULL;

    host_end = col ? col : delim;
  }

  if (!host_end)
    res->host = g_strdup (p);
  else {
    res->host = g_strndup (p, host_end - p);

    if (col) {
      res->port = strtoul (col + 1, NULL, 10);
    } else {
      /* no port specified, set to 0. gst_rtsp_url_get_port() will return the
       * default port */
      res->port = 0;
    }
  }
  p = delim;

  if (p && *p == '/') {
    delim = strchr (p, '?');
    if (!delim)
      res->abspath = g_strdup (p);
    else
      res->abspath = g_strndup (p, delim - p);
    p = delim;
  } else {
    res->abspath = g_strdup ("/");
  }

  if (p && *p == '?')
    res->query = g_strdup (p + 1);

  *url = res;

  return GST_RTSP_OK;

  /* ERRORS */
invalid:
  {
    gst_rtsp_url_free (res);
    return GST_RTSP_EINVAL;
  }
}
Beispiel #29
0
static int parse_line(char *line,
		      const char *host, size_t host_len,
		      const char *service, size_t service_len,
		      time_t now,
		      const gnutls_datum_t * rawkey,
		      const gnutls_datum_t * b64key)
{
	char *p, *kp;
	char *savep = NULL;
	size_t kp_len;
	time_t expiration;

	/* read version */
	p = strtok_r(line, "|", &savep);
	if (p == NULL)
		return gnutls_assert_val(GNUTLS_E_PARSING_ERROR);

	if (strncmp(p, "c0", 2) == 0)
		return parse_commitment_line(p + 3, host, host_len,
					     service, service_len, now,
					     rawkey);

	if (strncmp(p, "g0", 2) != 0)
		return gnutls_assert_val(GNUTLS_E_PARSING_ERROR);

	/* read host */
	p = strtok_r(NULL, "|", &savep);
	if (p == NULL)
		return gnutls_assert_val(GNUTLS_E_PARSING_ERROR);

	if (p[0] != '*' && host != NULL && strcmp(p, host) != 0)
		return gnutls_assert_val(GNUTLS_E_PARSING_ERROR);

	/* read service */
	p = strtok_r(NULL, "|", &savep);
	if (p == NULL)
		return gnutls_assert_val(GNUTLS_E_PARSING_ERROR);

	if (p[0] != '*' && service != NULL && strcmp(p, service) != 0)
		return gnutls_assert_val(GNUTLS_E_PARSING_ERROR);

	/* read expiration */
	p = strtok_r(NULL, "|", &savep);
	if (p == NULL)
		return gnutls_assert_val(GNUTLS_E_PARSING_ERROR);

	expiration = (time_t) atol(p);
	if (expiration > 0 && now > expiration)
		return gnutls_assert_val(GNUTLS_E_EXPIRED);

	/* read key */
	kp = strtok_r(NULL, "|", &savep);
	if (kp == NULL)
		return gnutls_assert_val(GNUTLS_E_PARSING_ERROR);

	p = strpbrk(kp, "\n \r\t|");
	if (p != NULL)
		*p = 0;

	kp_len = strlen(kp);
	if (kp_len != b64key->size)
		return
		    gnutls_assert_val(GNUTLS_E_CERTIFICATE_KEY_MISMATCH);

	if (memcmp(kp, b64key->data, b64key->size) != 0)
		return
		    gnutls_assert_val(GNUTLS_E_CERTIFICATE_KEY_MISMATCH);

	/* key found and matches */
	return 0;
}
Beispiel #30
0
/**
 * Reads in binary program from file filename.
 */
int process_file(const char* filename, binPrg& bp) {
	assert(NULL != filename);
	assert(0 < strlen(filename));

	FILE* fp;
	char buf[MAX_LINE_LEN];
	char* s;
	char* check;
	char space[2] = " ";
	int lines = 0;
	int rows = 0, cols;
	READ_MODE mode = READ_COLS;

	if (NULL == (fp = fopen(filename, "r"))) {
		fprintf(stderr, "Can't open file %s\n", filename);
		goto readError;;
	}

	while (NULL != (s = fgets(buf, sizeof(buf), fp))) {
		char* t = strpbrk(s, "#\n\r");

		lines++;

		if (NULL != t) /* else line is not terminated or too long */
			*t = '\0'; /* clip comment or newline */

		/* Skip over leading space
		 */
		while (isspace(*s))
			s++;

		/* Skip over empty lines
		 */
		if (!*s) /* <=> (*s == '\0') */
			continue;

		/* Process binary program here
		 */
		switch (mode) {

		case (READ_COLS):

			bp.columns = strtol(s, &check, 10);
			//check errors in format
			if (*check && !isspace(*check)) { /* (*check != '\0')*/
				fprintf(stderr,
						"Error in line %d: Wrong input format for columns. \n",
						lines);
				goto readError;
			}
			if (strtok(check, space)) {
				fprintf(stderr,
						"Error in line %d: Too many arguments for columns. \n",
						lines);
				goto readError;
			}

			if (1 > bp.columns || LIMIT < bp.columns) {
				fprintf(stderr,
						"Error in line %d: cols = %d. Allowed limits: 0 < cols <= %d \n",
						lines, bp.columns, LIMIT);
				goto readError;
			}

			mode = READ_ROWS;
			break;

		case (READ_ROWS):

			bp.rows = strtol(s, &check, 10);
			if (*check && !isspace(*check)) { /* (*check != '\0')*/
				fprintf(stderr,
						"Error in line %d: Wrong input format for rows. \n",
						lines);
				goto readError;
			}

			if (strtok(check, space)) {
				fprintf(stderr,
						"Error in line %d: Too many arguments for rows. \n",
						lines);
				goto readError;
			}

			if (1 > bp.rows || LIMIT < bp.rows) {
				fprintf(stderr,
						"Error in line %d. rows = %d. Allowed limits: 0 < rows <= %d \n",
						lines, bp.rows, LIMIT);
				goto readError;
			}
			mode = READ_MATRIX;
			break;

		case (READ_MATRIX):

			if (rows >= bp.rows) {
				fprintf(stderr, "Error in line: %d. Expected %d rows, "
						"got at least %d rows. Check your file.\n", lines,
						bp.rows, rows + 1);
				goto readError;
			}
			// read row
			for (cols = 0; cols < bp.columns; cols++) {

				bp.A[rows][cols] = strtod(s, &t);

				if (s == t) {
					fprintf(stderr,
							"Error in line: %d. Expected %d columns with digits. Got %d columns. \n",
							lines, bp.columns, cols);
					goto readError;
				}
				s = t;
			}

			// skip white spaces
			while (isspace(*s)) {
				s++;
			}

			if (!strncmp(s, "<=", 2)) {
				s += 2;
				bp.b[rows] = strtod(s, &t);
				if (s == t) {
					fprintf(stderr,
							"Error in line: %d. Expected constraint value. \n",
							lines);
					goto readError;
				}
				if (strtok(t, space)) {
					fprintf(stderr,
							"Error in line %d: Too many arguments for constraints. \n",
							lines);
					goto readError;
				}
			} else if (!strncmp(s, ">=", 2)) {
				s += 2;
				bp.multiplyRow(rows, -1);
				bp.b[rows] = -1 * strtod(s, &t);
				if (s == t) {
					fprintf(stderr,
							"Error in line: %d. Expected constraint value. \n",
							lines);
					goto readError;
				}
				if (strtok(t, space)) {
					fprintf(stderr,
							"Error in line %d: Too many arguments for constraints. \n",
							lines);
					goto readError;
				}
			} else if (!strncmp(s, "==", 2)) {
				s += 2;
				bp.b[rows] = strtod(s, &t);
				bp.comparator[rows] = true;
				if (s == t) {
					fprintf(stderr,
							"Error in line: %d. Expected constraint value. \n",
							lines);
					goto readError;
				}
				if (strtok(t, space)) {
					fprintf(stderr,
							"Error in line %d: Too many arguments for constraints. \n",
							lines);
					goto readError;
				}
			} else if (!strncmp(s, "=", 1)) {
				s += 1;
				bp.b[rows] = strtod(s, &t);
				bp.comparator[rows] = true;
				if (s == t) {
					fprintf(stderr,
							"Error in line: %d. Expected constraint value. \n",
							lines);
					goto readError;
				}
				if (strtok(t, space)) {
					fprintf(stderr,
							"Error in line %d: Too many arguments for constraints. \n",
							lines);
					goto readError;
				}

			} else {
				fprintf(stderr, "Error in line: %d. Expected =, <= or >=.\n",
						lines);
				goto readError;
			}
			rows++;
			break;
		}

	}
	fclose(fp);

	return lines;

	/**
	 * Error handling
	 */
	readError: fprintf(stderr, "Error in file. Terminated.\n");
	fclose(fp);
	return -1;
}