Ejemplo n.º 1
0
void Autoaway::checkIdleTime()
{
	kdebugf();

	m_idleTime = m_idle->secondsIdle();

	if (m_refreshStatusInterval > 0 && m_idleTime >= m_refreshStatusTime)
	{
		m_descriptionAddon = parseDescription(m_autoStatusText);
		m_refreshStatusTime = m_idleTime + m_refreshStatusInterval;
	}

	if (changeStatusTo() != AutoawayStatusChanger::NoChangeStatus)
	{
		m_autoawayStatusChanger->update();
		m_statusChanged = true;
	}
	else if (m_statusChanged)
	{
		m_statusChanged = false;
		m_autoawayStatusChanger->update();
	}

	m_timer->setInterval(m_checkInterval * 1000);
	m_timer->setSingleShot(true);
	m_timer->start();

	kdebugf2();
}
Ejemplo n.º 2
0
        Model::EntityDefinition* DefParser::nextDefinition() {
            Token token = m_tokenizer.nextToken();
            while (token.type() != Eof && token.type() != ODefinition)
                token = m_tokenizer.nextToken();
            if (token.type() == Eof)
                return NULL;

            expect(ODefinition, token);
            
            StringList baseClasses;
            ClassInfo classInfo;
            
            token = m_tokenizer.nextToken();
            expect(Word, token);
            classInfo.name = token.data();

            token = m_tokenizer.peekToken();
            expect(OParenthesis | Newline, token);
            if (token.type() == OParenthesis) {
                classInfo.setColor(parseColor());
                
                token = m_tokenizer.peekToken();
                expect(OParenthesis | Question, token);
                if (token.type() == OParenthesis) {
                    classInfo.setSize(parseBounds());
                } else {
                    m_tokenizer.nextToken();
                }
                
                token = m_tokenizer.peekToken();
                if (token.type() == Word) {
                    Model::FlagsPropertyDefinition::Ptr spawnflags = parseFlags();
                    classInfo.properties[spawnflags->name()] = spawnflags;
                }
            }

            expect(Newline, token = m_tokenizer.nextToken());
            parseProperties(classInfo.properties, classInfo.models, baseClasses);
            
            classInfo.setDescription(parseDescription());
            expect(CDefinition, token = m_tokenizer.nextToken());

            Model::EntityDefinition* definition = NULL;
            
            if (classInfo.hasColor) {
                ClassInfo::resolveBaseClasses(m_baseClasses, baseClasses, classInfo);
                if (classInfo.hasSize) { // point definition
                    definition = new Model::PointEntityDefinition(classInfo.name, classInfo.color, classInfo.size, classInfo.description, classInfo.propertyList(), classInfo.models);
                } else {
                    definition = new Model::BrushEntityDefinition(classInfo.name, classInfo.color, classInfo.description, classInfo.propertyList());
                }
            } else { // base definition
                m_baseClasses[classInfo.name] = classInfo;
                definition = nextDefinition();
            }
            
            return definition;
        }
Ejemplo n.º 3
0
/**
 * @brief	This function gets the description message from IGD(Internet Gateway Device).
 * @return	0: success, -2: Invalid UPnP Step, -1: reply packet timeout, 1: received xml parse error
 */
signed char GetDescriptionProcess(
  SOCKET sockfd 	/**< a socket number. */
  )
{
	char ret_value=0;
        long endTime=0;
        uint32 ipaddr;
        uint16 port;

	// Check UPnP Step
	if(UPnP_Step < 1) return -2;

	// Make HTTP GET Header
	memset(send_buffer, '\0', MAX_BUFFER);
	MakeGETHeader(send_buffer);

#ifdef UPNP_DEBUG
	printf("%s\r\n", send_buffer);
#endif

        ipaddr = inet_addr((uint8*)descIP);
        ipaddr = swapl(ipaddr);
        port = ATOI(descPORT, 10);

	// Connect to IGD(Internet Gateway Device)
	if(TCPClientOpen(sockfd, PORT_UPNP, (uint8*)&ipaddr, port) == FAIL) printf("TCP Socket Error!!\r\n");

	// Send Get Discription Message
	while(GetTCPSocketStatus(sockfd) != STATUS_ESTABLISHED);
	TCPSend(sockfd, (void *)send_buffer, strlen(send_buffer));

	// Receive Reply
	memset(recv_buffer, '\0', MAX_BUFFER);
	Delay_ms(500);
	endTime = my_time + 3;
	while (TCPRecv(sockfd, (void *)recv_buffer, MAX_BUFFER) <= 0 && my_time < endTime);	// Check Receive Buffer of W5200
	if(my_time >= endTime){	// Check Timeout
		TCPClose(sockfd);
		return -1;
	}

	// TCP Socket Close
	TCPClose(sockfd);

#ifdef UPNP_DEBUG
	printf("\r\nReceiveData\r\n%s\r\n", recv_buffer);
#endif

	// Parse Discription Message
	if((ret_value = parseDescription(recv_buffer)) == 0) UPnP_Step = 2;
	return ret_value;
}
Ejemplo n.º 4
0
std::vector<DescriptionScene> LevelModel::parseDescriptions(QXmlStreamReader* aXmlStreamReader)
{
    assert(aXmlStreamReader);
    //CrashLogger logger("LevelManager::parseDescriptions");
    std::vector<DescriptionScene> result;
    while (!aXmlStreamReader->atEnd() &&
           !(aXmlStreamReader->isEndElement() && aXmlStreamReader->name() == "descriptions")) {
        aXmlStreamReader->readNext();
        if (aXmlStreamReader->isStartElement()) {
            if (aXmlStreamReader->name() == "description") {
                result.push_back(parseDescription(aXmlStreamReader));
            }
        }
    }
    return result;
}
Ejemplo n.º 5
0
status CAFFile::readInit(AFfilesetup setup)
{
	m_fh->seek(8, File::SeekFromBeginning);

	if (!allocateTrack())
		return AF_FAIL;

	off_t currentOffset = m_fh->tell();
	off_t fileLength = m_fh->length();

	while (currentOffset < fileLength)
	{
		Tag chunkType;
		int64_t chunkLength;
		if (!readTag(&chunkType) ||
			!readS64(&chunkLength))
			return AF_FAIL;

		currentOffset += 12;

		if (chunkType == "data" && chunkLength == -1)
			chunkLength = fileLength - currentOffset;
		else if (chunkLength < 0)
			_af_error(AF_BAD_HEADER,
				"invalid chunk length %jd for chunk type %s\n",
				static_cast<intmax_t>(chunkLength), chunkType.name().c_str());

		if (chunkType == "desc")
		{
			if (parseDescription(chunkType, chunkLength) == AF_FAIL)
				return AF_FAIL;
		}
		else if (chunkType == "data")
		{
			if (parseData(chunkType, chunkLength) == AF_FAIL)
				return AF_FAIL;
		}

		currentOffset = m_fh->seek(currentOffset + chunkLength,
			File::SeekFromBeginning);
	}

	return AF_SUCCEED;
}
Ejemplo n.º 6
0
void Autoaway::configurationUpdated()
{
	if (!m_configuration)
		return;

	m_checkInterval = m_configuration->deprecatedApi()->readUnsignedNumEntry("General","AutoAwayCheckTime");
	m_refreshStatusTime = m_configuration->deprecatedApi()->readUnsignedNumEntry("General","AutoRefreshStatusTime");
	m_autoAwayTime = m_configuration->deprecatedApi()->readUnsignedNumEntry("General","AutoAwayTimeMinutes")*60;
	m_autoExtendedAwayTime = m_configuration->deprecatedApi()->readUnsignedNumEntry("General","AutoExtendedAwayTimeMinutes")*60;
	m_autoDisconnectTime = m_configuration->deprecatedApi()->readUnsignedNumEntry("General","AutoDisconnectTimeMinutes")*60;
	m_autoInvisibleTime = m_configuration->deprecatedApi()->readUnsignedNumEntry("General","AutoInvisibleTimeMinutes")*60;

	m_autoAwayEnabled = m_configuration->deprecatedApi()->readBoolEntry("General","AutoAway");
	m_autoExtendedAwayEnabled = m_configuration->deprecatedApi()->readBoolEntry("General","AutoExtendedAway");
	m_autoInvisibleEnabled = m_configuration->deprecatedApi()->readBoolEntry("General","AutoInvisible");
	m_autoDisconnectEnabled = m_configuration->deprecatedApi()->readBoolEntry("General","AutoDisconnect");
	m_parseAutoStatus = m_configuration->deprecatedApi()->readBoolEntry("General", "ParseStatus");

	m_refreshStatusInterval = m_refreshStatusTime;

	m_autoStatusText = m_configuration->deprecatedApi()->readEntry("General", "AutoStatusText");
	m_descriptionAddon = parseDescription(m_autoStatusText);

	m_changeTo = (AutoawayStatusChanger::ChangeDescriptionTo)m_configuration->deprecatedApi()->readNumEntry("General", "AutoChangeDescription");

	m_autoawayStatusChanger->update();

	if (m_autoAwayEnabled || m_autoExtendedAwayEnabled || m_autoInvisibleEnabled || m_autoDisconnectEnabled)
	{
		m_timer->setInterval(m_checkInterval * 1000);
		m_timer->setSingleShot(true);
		m_timer->start();
	}
	else
		m_timer->stop();
}
Ejemplo n.º 7
0
int main(int argc, char **argv) {
  // read command line arguments to get additional parameter for the calculus
  checkArgsNum(argc, 3, 
	       "The qualifier for this calculus requires the following parameters:\n- calculus parameter string (dcc2)\n- generation mode ('all' or 'first2all')\n"
  	       );
    
  if (strcmp(argv[1],"dcc2")!=0) {
    cerr << "Wrong number of parameters in calculus parameter string. "
	 << "Expected form: dcc2.\n";
    exit(2);
  }

  mode = readQualifierGenerationMode(argv[2]);

  // read scene description from stdin and parse it (see top of this file 
  // for input and output format)	
  std::vector<entity> confg = parseDescription();
	
  // generate qualitative description
  std::string desc = writeQualitativeSceneTernary(mode,confg);
	cout << desc << endl;

  return 0;	
}
Ejemplo n.º 8
0
/* Parse a string that generates shards and replicas. Separator - one of two characters | or ,
 *  depending on whether shards or replicas are generated.
 * For example:
 * host1,host2,...      - generates set of shards from host1, host2, ...
 * host1|host2|...      - generates set of replicas from host1, host2, ...
 * abc{8..10}def        - generates set of shards abc8def, abc9def, abc10def.
 * abc{08..10}def       - generates set of shards abc08def, abc09def, abc10def.
 * abc{x,yy,z}def       - generates set of shards abcxdef, abcyydef, abczdef.
 * abc{x|yy|z} def      - generates set of replicas abcxdef, abcyydef, abczdef.
 * abc{1..9}de{f,g,h}   - is a direct product, 27 shards.
 * abc{1..9}de{0|1}     - is a direct product, 9 shards, in each 2 replicas.
 */
static std::vector<String> parseDescription(const String & description, size_t l, size_t r, char separator, size_t max_addresses)
{
    std::vector<String> res;
    std::vector<String> cur;

    /// An empty substring means a set of an empty string
    if (l >= r)
    {
        res.push_back("");
        return res;
    }

    for (size_t i = l; i < r; ++i)
    {
        /// Either the numeric interval (8..10) or equivalent expression in brackets
        if (description[i] == '{')
        {
            int cnt = 1;
            int last_dot = -1; /// The rightmost pair of points, remember the index of the right of the two
            size_t m;
            std::vector<String> buffer;
            bool have_splitter = false;

            /// Look for the corresponding closing bracket
            for (m = i + 1; m < r; ++m)
            {
                if (description[m] == '{') ++cnt;
                if (description[m] == '}') --cnt;
                if (description[m] == '.' && description[m-1] == '.') last_dot = m;
                if (description[m] == separator) have_splitter = true;
                if (cnt == 0) break;
            }
            if (cnt != 0)
                throw Exception("Table function 'remote': incorrect brace sequence in first argument",
                                ErrorCodes::BAD_ARGUMENTS);
            /// The presence of a dot - numeric interval
            if (last_dot != -1)
            {
                size_t left, right;
                if (description[last_dot - 1] != '.')
                    throw Exception("Table function 'remote': incorrect argument in braces (only one dot): " + description.substr(i, m - i + 1),
                                    ErrorCodes::BAD_ARGUMENTS);
                if (!parseNumber(description, i + 1, last_dot - 1, left))
                    throw Exception("Table function 'remote': incorrect argument in braces (Incorrect left number): "
                                    + description.substr(i, m - i + 1),
                                    ErrorCodes::BAD_ARGUMENTS);
                if (!parseNumber(description, last_dot + 1, m, right))
                    throw Exception("Table function 'remote': incorrect argument in braces (Incorrect right number): "
                                    + description.substr(i, m - i + 1),
                                    ErrorCodes::BAD_ARGUMENTS);
                if (left > right)
                    throw Exception("Table function 'remote': incorrect argument in braces (left number is greater then right): "
                                    + description.substr(i, m - i + 1),
                                    ErrorCodes::BAD_ARGUMENTS);
                if (right - left + 1 >  max_addresses)
                    throw Exception("Table function 'remote': first argument generates too many result addresses",
                        ErrorCodes::BAD_ARGUMENTS);
                bool add_leading_zeroes = false;
                size_t len = last_dot - 1 - (i + 1);
                 /// If the left and right borders have equal numbers, then you must add leading zeros.
                if (last_dot - 1 - (i + 1) == m - (last_dot + 1))
                    add_leading_zeroes = true;
                for (size_t id = left; id <= right; ++id)
                {
                    String cur = toString<UInt64>(id);
                    if (add_leading_zeroes)
                    {
                        while (cur.size() < len)
                            cur = "0" + cur;
                    }
                    buffer.push_back(cur);
                }
            }
            else if (have_splitter) /// If there is a current delimiter inside, then generate a set of resulting rows
                buffer = parseDescription(description, i + 1, m, separator, max_addresses);
            else                     /// Otherwise just copy, spawn will occur when you call with the correct delimiter
                buffer.push_back(description.substr(i, m - i + 1));
            /// Add all possible received extensions to the current set of lines
            append(cur, buffer, max_addresses);
            i = m;
        }
        else if (description[i] == separator)
        {
            /// If the delimiter, then add found rows
            res.insert(res.end(), cur.begin(), cur.end());
            cur.clear();
        }
        else
        {
            /// Otherwise, simply append the character to current lines
            std::vector<String> buffer;
            buffer.push_back(description.substr(i, 1));
            append(cur, buffer, max_addresses);
        }
    }

    res.insert(res.end(), cur.begin(), cur.end());
    if (res.size() > max_addresses)
        throw Exception("Table function 'remote': first argument generates too many result addresses",
            ErrorCodes::BAD_ARGUMENTS);

    return res;
}
Ejemplo n.º 9
0
StoragePtr TableFunctionRemote::executeImpl(const ASTPtr & ast_function, const Context & context) const
{
    ASTs & args_func = typeid_cast<ASTFunction &>(*ast_function).children;

    if (args_func.size() != 1)
        throw Exception(help_message, ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

    ASTs & args = typeid_cast<ASTExpressionList &>(*args_func.at(0)).children;

    const size_t max_args = is_cluster_function ? 3 : 5;
    if (args.size() < 2 || args.size() > max_args)
        throw Exception(help_message, ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

    String cluster_name;
    String cluster_description;
    String remote_database;
    String remote_table;
    String username;
    String password;

    size_t arg_num = 0;

    auto getStringLiteral = [](const IAST & node, const char * description)
    {
        const ASTLiteral * lit = typeid_cast<const ASTLiteral *>(&node);
        if (!lit)
            throw Exception(description + String(" must be string literal (in single quotes)."), ErrorCodes::BAD_ARGUMENTS);

        if (lit->value.getType() != Field::Types::String)
            throw Exception(description + String(" must be string literal (in single quotes)."), ErrorCodes::BAD_ARGUMENTS);

        return safeGet<const String &>(lit->value);
    };

    if (is_cluster_function)
    {
        ASTPtr ast_name = evaluateConstantExpressionOrIdentifierAsLiteral(args[arg_num], context);
        cluster_name = static_cast<const ASTLiteral &>(*ast_name).value.safeGet<const String &>();
    }
    else
    {
        if (auto ast_cluster = typeid_cast<const ASTIdentifier *>(args[arg_num].get()))
            cluster_name = ast_cluster->name;
        else
            cluster_description = getStringLiteral(*args[arg_num], "Hosts pattern");
    }
    ++arg_num;

    args[arg_num] = evaluateConstantExpressionOrIdentifierAsLiteral(args[arg_num], context);
    remote_database = static_cast<const ASTLiteral &>(*args[arg_num]).value.safeGet<String>();
    ++arg_num;

    size_t dot = remote_database.find('.');
    if (dot != String::npos)
    {
        /// NOTE Bad - do not support identifiers in backquotes.
        remote_table = remote_database.substr(dot + 1);
        remote_database = remote_database.substr(0, dot);
    }
    else
    {
        if (arg_num >= args.size())
            throw Exception(help_message, ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

        args[arg_num] = evaluateConstantExpressionOrIdentifierAsLiteral(args[arg_num], context);
        remote_table = static_cast<const ASTLiteral &>(*args[arg_num]).value.safeGet<String>();
        ++arg_num;
    }

    /// Username and password parameters are prohibited in cluster version of the function
    if (!is_cluster_function)
    {
        if (arg_num < args.size())
        {
            username = getStringLiteral(*args[arg_num], "Username");
            ++arg_num;
        }
        else
            username = "******";

        if (arg_num < args.size())
        {
            password = getStringLiteral(*args[arg_num], "Password");
            ++arg_num;
        }
    }

    if (arg_num < args.size())
        throw Exception(help_message, ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

    /// ExpressionAnalyzer will be created in InterpreterSelectQuery that will meet these `Identifier` when processing the request.
    /// We need to mark them as the name of the database or table, because the default value is column.
    for (auto & arg : args)
        if (ASTIdentifier * id = typeid_cast<ASTIdentifier *>(arg.get()))
            id->kind = ASTIdentifier::Table;

    ClusterPtr cluster;
    if (!cluster_name.empty())
    {
        /// Use an existing cluster from the main config
        cluster = context.getCluster(cluster_name);
    }
    else
    {
        /// Create new cluster from the scratch
        size_t max_addresses = context.getSettingsRef().table_function_remote_max_addresses;
        std::vector<String> shards = parseDescription(cluster_description, 0, cluster_description.size(), ',', max_addresses);

        std::vector<std::vector<String>> names;
        for (size_t i = 0; i < shards.size(); ++i)
            names.push_back(parseDescription(shards[i], 0, shards[i].size(), '|', max_addresses));

        if (names.empty())
            throw Exception("Shard list is empty after parsing first argument", ErrorCodes::BAD_ARGUMENTS);

        cluster = std::make_shared<Cluster>(context.getSettings(), names, username, password, context.getTCPPort(), false);
    }

    auto res = StorageDistributed::createWithOwnCluster(
        getName(),
        getStructureOfRemoteTable(*cluster, remote_database, remote_table, context),
        remote_database,
        remote_table,
        cluster,
        context);
    res->startup();
    return res;
}
Ejemplo n.º 10
0
static rpmSpec parseSpec(const char *specFile, rpmSpecFlags flags,
                         const char *buildRoot, int recursing)
{
    int parsePart = PART_PREAMBLE;
    int initialPackage = 1;
    rpmSpec spec;

    /* Set up a new Spec structure with no packages. */
    spec = newSpec();

    spec->specFile = rpmGetPath(specFile, NULL);
    pushOFI(spec, spec->specFile);
    /* If buildRoot not specified, use default %{buildroot} */
    if (buildRoot) {
        spec->buildRoot = xstrdup(buildRoot);
    } else {
        spec->buildRoot = rpmGetPath("%{?buildroot:%{buildroot}}", NULL);
    }
    addMacro(NULL, "_docdir", NULL, "%{_defaultdocdir}", RMIL_SPEC);
    addMacro(NULL, "_licensedir", NULL, "%{_defaultlicensedir}", RMIL_SPEC);
    spec->recursing = recursing;
    spec->flags = flags;

    /* All the parse*() functions expect to have a line pre-read */
    /* in the spec's line buffer.  Except for parsePreamble(),   */
    /* which handles the initial entry into a spec file.         */

    while (parsePart != PART_NONE) {
        int goterror = 0;
        switch (parsePart) {
        case PART_ERROR: /* fallthrough */
        default:
            goterror = 1;
            break;
        case PART_PREAMBLE:
            parsePart = parsePreamble(spec, initialPackage);
            initialPackage = 0;
            break;
        case PART_PREP:
            parsePart = parsePrep(spec);
            break;
        case PART_BUILD:
        case PART_INSTALL:
        case PART_CHECK:
        case PART_CLEAN:
            parsePart = parseBuildInstallClean(spec, parsePart);
            break;
        case PART_CHANGELOG:
            parsePart = parseChangelog(spec);
            break;
        case PART_DESCRIPTION:
            parsePart = parseDescription(spec);
            break;

        case PART_PRE:
        case PART_POST:
        case PART_PREUN:
        case PART_POSTUN:
        case PART_PRETRANS:
        case PART_POSTTRANS:
        case PART_VERIFYSCRIPT:
        case PART_TRIGGERPREIN:
        case PART_TRIGGERIN:
        case PART_TRIGGERUN:
        case PART_TRIGGERPOSTUN:
        case PART_FILETRIGGERIN:
        case PART_FILETRIGGERUN:
        case PART_FILETRIGGERPOSTUN:
        case PART_TRANSFILETRIGGERIN:
        case PART_TRANSFILETRIGGERUN:
        case PART_TRANSFILETRIGGERPOSTUN:
            parsePart = parseScript(spec, parsePart);
            break;

        case PART_FILES:
            parsePart = parseFiles(spec);
            break;

        case PART_POLICIES:
            parsePart = parsePolicies(spec);
            break;

        case PART_NONE:		/* XXX avoid gcc whining */
        case PART_LAST:
        case PART_BUILDARCHITECTURES:
            break;
        }

        if (goterror || parsePart >= PART_LAST) {
            goto errxit;
        }

        if (parsePart == PART_BUILDARCHITECTURES) {
            int index;
            int x;

            closeSpec(spec);

            spec->BASpecs = xcalloc(spec->BACount, sizeof(*spec->BASpecs));
            index = 0;
            if (spec->BANames != NULL)
                for (x = 0; x < spec->BACount; x++) {

                    /* Skip if not arch is not compatible. */
                    if (!rpmMachineScore(RPM_MACHTABLE_BUILDARCH, spec->BANames[x]))
                        continue;
                    addMacro(NULL, "_target_cpu", NULL, spec->BANames[x], RMIL_RPMRC);
                    spec->BASpecs[index] = parseSpec(specFile, flags, buildRoot, 1);
                    if (spec->BASpecs[index] == NULL) {
                        spec->BACount = index;
                        goto errxit;
                    }
                    delMacro(NULL, "_target_cpu");
                    index++;
                }

            spec->BACount = index;
            if (! index) {
                rpmlog(RPMLOG_ERR,
                       _("No compatible architectures found for build\n"));
                goto errxit;
            }

            /*
             * Return the 1st child's fully parsed Spec structure.
             * The restart of the parse when encountering BuildArch
             * causes problems for "rpm -q --specfile". This is
             * still a hack because there may be more than 1 arch
             * specified (unlikely but possible.) There's also the
             * further problem that the macro context, particularly
             * %{_target_cpu}, disagrees with the info in the header.
             */
            if (spec->BACount >= 1) {
                rpmSpec nspec = spec->BASpecs[0];
                spec->BASpecs = _free(spec->BASpecs);
                rpmSpecFree(spec);
                spec = nspec;
            }

            goto exit;
        }
    }

    if (spec->clean == NULL) {
        char *body = rpmExpand("%{?buildroot: %{__rm} -rf %{buildroot}}", NULL);
        spec->clean = newStringBuf();
        appendLineStringBuf(spec->clean, body);
        free(body);
    }

    /* Check for description in each package */
    for (Package pkg = spec->packages; pkg != NULL; pkg = pkg->next) {
        if (!headerIsEntry(pkg->header, RPMTAG_DESCRIPTION)) {
            rpmlog(RPMLOG_ERR, _("Package has no %%description: %s\n"),
                   headerGetString(pkg->header, RPMTAG_NAME));
            goto errxit;
        }
    }

    /* Add arch, os and platform, self-provides etc for each package */
    addTargets(spec->packages);

    /* Check for encoding in each package unless disabled */
    if (!(spec->flags & RPMSPEC_NOUTF8)) {
        int badenc = 0;
        for (Package pkg = spec->packages; pkg != NULL; pkg = pkg->next) {
            if (checkForEncoding(pkg->header, 0) != RPMRC_OK) {
                badenc = 1;
            }
        }
        if (badenc)
            goto errxit;
    }

    closeSpec(spec);
exit:
    /* Assemble source header from parsed components */
    initSourceHeader(spec);

    return spec;

errxit:
    rpmSpecFree(spec);
    return NULL;
}
Ejemplo n.º 11
0
/*
 * Parse Event Information Table
 */
static void parseEIT(u_char *data, size_t len) {
	struct eit *e = (struct eit *) data;
	u_char *p;
	struct tm dvb_time;
	const char *xmltvid;
	char date_strbuf[256];

	len -= 4; //remove CRC

	// For each event listing
	for (p = (u_char *) (&e->data); p < (u_char *) (data + len); p
			+= EIT_EVENT_LEN + GetEITDescriptorsLoopLength(p)) {
		struct eit_event *evt = (struct eit_event *) p;
		struct chninfo *c;
		// find existing information?
		for (c = channels; c != NULL; c = c->next) {
			// found it
			if (c->sid == HILO(e->service_id)
					&& (c->eid == HILO(evt->event_id))) {
				if (c->ver <= e->version_number) // seen it before or its older FIXME: wrap-around to 0
					return;
				else {
					c->ver = e->version_number; // update outputted version
					update_count++;
					if (ignore_updates)
						return;
					break;
				}
			}
		}

		// its a new program
		if (c == NULL) {
			chninfo_t *nc = (chninfo_t *) malloc(sizeof(struct chninfo));
			nc->sid = HILO(e->service_id);
			nc->eid = HILO(evt->event_id);
			nc->ver = e->version_number;
			nc->sname = strdup("not-yet-known");
			nc->next = channels;
			channels = nc;
		}

		/* we have more data, refresh alarm */
		if (timeout)
		{
			setTimeoutDeadline();
			//alarm(timeout);
		}

		// No program info at end! Just skip it
		if (GetEITDescriptorsLoopLength(evt) == 0)
			return;

		parseMJD(HILO(evt->mjd), &dvb_time);

		dvb_time.tm_sec = BcdCharToInt(evt->start_time_s);
		dvb_time.tm_min = BcdCharToInt(evt->start_time_m);
		dvb_time.tm_hour = BcdCharToInt(evt->start_time_h) + time_offset;
		time_t start_time = timegm(&dvb_time);

		dvb_time.tm_sec += BcdCharToInt(evt->duration_s);
		dvb_time.tm_min += BcdCharToInt(evt->duration_m);
		dvb_time.tm_hour += BcdCharToInt(evt->duration_h);
		time_t stop_time = timegm(&dvb_time);

		time_t now;
		time(&now);
		// basic bad date check. if the program ends before this time yesterday, or two weeks from today, forget it.
		if ((difftime(stop_time, now) < -24 * 60 * 60) || (difftime(now,
						stop_time) > 14 * 24 * 60 * 60)) {
			invalid_date_count++;
			if (ignore_bad_dates)
				return;
		}
		// a program must have a title that isn't empty
		if (!validateDescription((u_char *) (&evt->data),
					GetEITDescriptorsLoopLength(evt))) {
			return;
		}

		programme_count++;

		if ((start_time >= start_of_period) && (start_time < end_of_period)) {
			xmltvid = dvbxmltvid(GetServiceId(e));
			if (xmltvid != NULL) {
				printf("<programme channel=\"%s\" ", xmltvid);
				strftime(date_strbuf, sizeof(date_strbuf),
						"start=\"%Y%m%d%H%M%S %z\"", localtime(&start_time));
				printf("%s ", date_strbuf);
				strftime(date_strbuf, sizeof(date_strbuf),
						"stop=\"%Y%m%d%H%M%S %z\"", localtime(&stop_time));
				printf("%s>\n ", date_strbuf);

				//printf("\t<EventID>%i</EventID>\n", HILO(evt->event_id));
				//printf("\t<RunningStatus>%i</RunningStatus>\n", evt->running_status);
				//1 Airing, 2 Starts in a few seconds, 3 Pausing, 4 About to air

				parseDescription((u_char *) (&evt->data),
						GetEITDescriptorsLoopLength(evt));
				printf("</programme>\n");
			}
		}
	}
}
Ejemplo n.º 12
0
int parseSpec(rpmts ts, const char *specFile, const char *rootDir,
		const char *buildRoot, int recursing, const char *passPhrase,
		const char *cookie, int anyarch, int force)
{
    rpmParseState parsePart = PART_PREAMBLE;
    int initialPackage = 1;
    Package pkg;
    rpmSpec spec;
    
    /* Set up a new Spec structure with no packages. */
    spec = newSpec();

    spec->specFile = rpmGetPath(specFile, NULL);
    spec->fileStack = newOpenFileInfo();
    spec->fileStack->fileName = xstrdup(spec->specFile);
    /* If buildRoot not specified, use default %{buildroot} */
    if (buildRoot) {
	spec->buildRoot = xstrdup(buildRoot);
    } else {
	spec->buildRoot = rpmGetPath("%{?buildroot:%{buildroot}}", NULL);
    }
    addMacro(NULL, "_docdir", NULL, "%{_defaultdocdir}", RMIL_SPEC);
    spec->recursing = recursing;
    spec->anyarch = anyarch;
    spec->force = force;

    if (rootDir)
	spec->rootDir = xstrdup(rootDir);
    if (passPhrase)
	spec->passPhrase = xstrdup(passPhrase);
    if (cookie)
	spec->cookie = xstrdup(cookie);

    spec->timeCheck = rpmExpandNumeric("%{_timecheck}");

    /* All the parse*() functions expect to have a line pre-read */
    /* in the spec's line buffer.  Except for parsePreamble(),   */
    /* which handles the initial entry into a spec file.         */
    
    while (parsePart != PART_NONE) {
	int goterror = 0;
	switch (parsePart) {
	/* XXX Trap unexpected RPMRC_FAIL returns for now */
	case RPMRC_FAIL:
	    rpmlog(RPMLOG_ERR, "FIXME: got RPMRC_FAIL from spec parse\n");
	    abort();
	case PART_ERROR: /* fallthrough */
	default:
	    goterror = 1;
	    break;
	case PART_PREAMBLE:
	    parsePart = parsePreamble(spec, initialPackage);
	    initialPackage = 0;
	    break;
	case PART_PREP:
	    parsePart = parsePrep(spec);
	    break;
	case PART_BUILD:
	case PART_INSTALL:
	case PART_CHECK:
	case PART_CLEAN:
	    parsePart = parseBuildInstallClean(spec, parsePart);
	    break;
	case PART_CHANGELOG:
	    parsePart = parseChangelog(spec);
	    break;
	case PART_DESCRIPTION:
	    parsePart = parseDescription(spec);
	    break;

	case PART_PRE:
	case PART_POST:
	case PART_PREUN:
	case PART_POSTUN:
	case PART_PRETRANS:
	case PART_POSTTRANS:
	case PART_VERIFYSCRIPT:
	case PART_TRIGGERPREIN:
	case PART_TRIGGERIN:
	case PART_TRIGGERUN:
	case PART_TRIGGERPOSTUN:
	    parsePart = parseScript(spec, parsePart);
	    break;

	case PART_FILES:
	    parsePart = parseFiles(spec);
	    break;

	case PART_NONE:		/* XXX avoid gcc whining */
	case PART_LAST:
	case PART_BUILDARCHITECTURES:
	    break;
	}

	if (goterror || parsePart >= PART_LAST) {
	    goto errxit;
	}

	if (parsePart == PART_BUILDARCHITECTURES) {
	    int index;
	    int x;

	    closeSpec(spec);

	    spec->BASpecs = xcalloc(spec->BACount, sizeof(*spec->BASpecs));
	    index = 0;
	    if (spec->BANames != NULL)
	    for (x = 0; x < spec->BACount; x++) {

		/* Skip if not arch is not compatible. */
		if (!rpmMachineScore(RPM_MACHTABLE_BUILDARCH, spec->BANames[x]))
		    continue;
		addMacro(NULL, "_target_cpu", NULL, spec->BANames[x], RMIL_RPMRC);
		spec->BASpecs[index] = NULL;
		if (parseSpec(ts, specFile, spec->rootDir, buildRoot, 1,
				  passPhrase, cookie, anyarch, force)
		 || (spec->BASpecs[index] = rpmtsSetSpec(ts, NULL)) == NULL)
		{
			spec->BACount = index;
			goto errxit;
		}
		delMacro(NULL, "_target_cpu");
		index++;
	    }

	    spec->BACount = index;
	    if (! index) {
		rpmlog(RPMLOG_ERR,
			_("No compatible architectures found for build\n"));
		goto errxit;
	    }

	    /*
	     * Return the 1st child's fully parsed Spec structure.
	     * The restart of the parse when encountering BuildArch
	     * causes problems for "rpm -q --specfile". This is
	     * still a hack because there may be more than 1 arch
	     * specified (unlikely but possible.) There's also the
	     * further problem that the macro context, particularly
	     * %{_target_cpu}, disagrees with the info in the header.
	     */
	    if (spec->BACount >= 1) {
		rpmSpec nspec = spec->BASpecs[0];
		spec->BASpecs = _free(spec->BASpecs);
		spec = freeSpec(spec);
		spec = nspec;
	    }

	    (void) rpmtsSetSpec(ts, spec);
	    return 0;
	}
    }

    if (spec->clean == NULL) {
	char *body = rpmExpand("%{?buildroot: %{__rm} -rf %{buildroot}}", NULL);
	spec->clean = newStringBuf();
	appendLineStringBuf(spec->clean, body);
	free(body);
    }

    /* Check for description in each package and add arch and os */
  {
    char *platform = rpmExpand("%{_target_platform}", NULL);
    char *arch = rpmExpand("%{_target_cpu}", NULL);
    char *os = rpmExpand("%{_target_os}", NULL);

    for (pkg = spec->packages; pkg != NULL; pkg = pkg->next) {
	if (!headerIsEntry(pkg->header, RPMTAG_DESCRIPTION)) {
	    rpmlog(RPMLOG_ERR, _("Package has no %%description: %s\n"),
		   headerGetString(pkg->header, RPMTAG_NAME));
	    goto errxit;
	}

	headerPutString(pkg->header, RPMTAG_OS, os);
	/* noarch subpackages already have arch set here, leave it alone */
	if (!headerIsEntry(pkg->header, RPMTAG_ARCH)) {
	    headerPutString(pkg->header, RPMTAG_ARCH, arch);
	}
	headerPutString(pkg->header, RPMTAG_PLATFORM, platform);

	pkg->ds = rpmdsThis(pkg->header, RPMTAG_REQUIRENAME, RPMSENSE_EQUAL);

    }

    platform = _free(platform);
    arch = _free(arch);
    os = _free(os);
  }

    closeSpec(spec);
    (void) rpmtsSetSpec(ts, spec);

    return 0;

errxit:
    spec = freeSpec(spec);
    return PART_ERROR;
}
Ejemplo n.º 13
0
StoragePtr TableFunctionRemote::execute(const ASTPtr & ast_function, const Context & context) const
{
    ASTs & args_func = typeid_cast<ASTFunction &>(*ast_function).children;

    const char * err = "Table function 'remote' requires from 2 to 5 parameters: "
        "addresses pattern, name of remote database, name of remote table, [username, [password]].";

    if (args_func.size() != 1)
        throw Exception(err, ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

    ASTs & args = typeid_cast<ASTExpressionList &>(*args_func.at(0)).children;

    if (args.size() < 2 || args.size() > 5)
        throw Exception(err, ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

    String description;
    String remote_database;
    String remote_table;
    String username;
    String password;

    size_t arg_num = 0;

    auto getStringLiteral = [](const IAST & node, const char * description)
    {
        const ASTLiteral * lit = typeid_cast<const ASTLiteral *>(&node);
        if (!lit)
            throw Exception(description + String(" must be string literal (in single quotes)."), ErrorCodes::BAD_ARGUMENTS);

        if (lit->value.getType() != Field::Types::String)
            throw Exception(description + String(" must be string literal (in single quotes)."), ErrorCodes::BAD_ARGUMENTS);

        return safeGet<const String &>(lit->value);
    };

    description = getStringLiteral(*args[arg_num], "Hosts pattern");
    ++arg_num;

    args[arg_num] = evaluateConstantExpressionOrIdentidierAsLiteral(args[arg_num], context);
    remote_database = static_cast<const ASTLiteral &>(*args[arg_num]).value.safeGet<String>();
    ++arg_num;

    size_t dot = remote_database.find('.');
    if (dot != String::npos)
    {
        /// NOTE Bad - do not support identifiers in backquotes.
        remote_table = remote_database.substr(dot + 1);
        remote_database = remote_database.substr(0, dot);
    }
    else
    {
        if (arg_num >= args.size())
            throw Exception(err, ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

        args[arg_num] = evaluateConstantExpressionOrIdentidierAsLiteral(args[arg_num], context);
        remote_table = static_cast<const ASTLiteral &>(*args[arg_num]).value.safeGet<String>();
        ++arg_num;
    }

    if (arg_num < args.size())
    {
        username = getStringLiteral(*args[arg_num], "Username");
        ++arg_num;
    }
    else
        username = "******";

    if (arg_num < args.size())
    {
        password = getStringLiteral(*args[arg_num], "Password");
        ++arg_num;
    }

    if (arg_num < args.size())
        throw Exception(err, ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH);

    /// ExpressionAnalyzer will be created in InterpreterSelectQuery that will meet these `Identifier` when processing the request.
    /// We need to mark them as the name of the database or table, because the default value is column.
    for (auto & arg : args)
        if (ASTIdentifier * id = typeid_cast<ASTIdentifier *>(arg.get()))
            id->kind = ASTIdentifier::Table;

    size_t max_addresses = context.getSettingsRef().table_function_remote_max_addresses;

    std::vector<std::vector<String>> names;
    std::vector<String> shards = parseDescription(description, 0, description.size(), ',', max_addresses);

    for (size_t i = 0; i < shards.size(); ++i)
        names.push_back(parseDescription(shards[i], 0, shards[i].size(), '|', max_addresses));

    if (names.empty())
        throw Exception("Shard list is empty after parsing first argument", ErrorCodes::BAD_ARGUMENTS);

    auto cluster = std::make_shared<Cluster>(context.getSettings(), names, username, password);

    return StorageDistributed::create(
        getName(),
        std::make_shared<NamesAndTypesList>(getStructureOfRemoteTable(*cluster, remote_database, remote_table, context)),
        remote_database,
        remote_table,
        cluster,
        context);
}
Ejemplo n.º 14
0
FB2Content *
parseFile(char *filename)
{

  xmlDocPtr doc;
  xmlNodePtr cur;
  FB2Content *fb;

  doc = xmlParseFile(filename);

  if (doc == NULL ) {
    fprintf(stderr, "Document not parsed successfully. \n");
    return NULL;
  }

  cur = xmlDocGetRootElement(doc);

  if (cur == NULL) {
    fprintf(stderr, "empty document\n");
    xmlFreeDoc(doc);
    return NULL;
  }

  if (xmlStrcmp(cur->name, (const xmlChar *) "FictionBook")) {
    fprintf(stderr, "document of the wrong type, root node != FictionBook\n");
    xmlFreeDoc(doc);
    return NULL;
  }

  fb = (FB2Content *) malloc(sizeof(FB2Content));

  /* initialize buffers */
  fb->text = (char *) malloc(BUF_SIZE);
  fb->text_buffer_size = BUF_SIZE;
  fb->text_current_index = 0;
  fb->utf8_current_index = 0;
  fb->description = (char *) malloc(BUF_SIZE);
  fb->description_buffer_size = BUF_SIZE;
  fb->description_current_index = 0;

  *fb->author = '\0';
  *fb->name = '\0';
  *fb->cover_href = '\0';

  fb->genres[0] = NULL;
  fb->num_genres = 0;

  fb->marks[0] = NULL;
  fb->num_marks = 0;

  fb->binaries[0] = NULL;
  fb->num_binaries = 0;

  //fb->links[0] = NULL;
  //fb->num_links = 0;

  cur = cur->children;
  while (cur != NULL) {

    if (!xmlStrcmp(cur->name, (const xmlChar *)"description")) {
      fb->current_buffer = DESCRIPTION_BUFFER;
      parseDescription(doc, cur, fb);

    } else if (!xmlStrcmp(cur->name, (const xmlChar *)"body")) {
      fb->current_buffer = TEXT_BUFFER;
      parseBody(doc, cur, fb);

    } else if (!xmlStrcmp(cur->name, (const xmlChar *)"binary")) {
      fb->current_buffer = BINARY_BUFFER;
      parseBinary(doc, cur, fb);

    }

    cur = cur->next;
  }
  xmlFreeDoc(doc);

  fb->current_buffer = DESCRIPTION_BUFFER;
  bufferAppend("\0", 1, fb);

  fb->current_buffer = TEXT_BUFFER;
  bufferAppend("\0", 1, fb);

  return fb;
}