Exemplo n.º 1
0
////////////////////////////////////////////////////////////////////////////////////
///
///   \brief Test method to verify ability to read/write message data from
///   an example wireshark log provided for testing systems for the JAUS
///   Interoperability Challenge hosted at several AUVSI competitions.
///
////////////////////////////////////////////////////////////////////////////////////
void VerifyAgainstLog()
{
    Packet::List packets;
    Packet::List::iterator packet;

    Component component;
    component.DiscoveryService()->SetSubsystemIdentification(Subsystem::OCU, "OCP");
    component.AddService(new LocalPoseSensor());
    component.AddService(new VelocityStateSensor());
    component.AddService(new ListManager());    
    component.AddService(new TestLocalWaypointListDriver());

    Packet::LoadWiresharkCapturePacketExport("logs/example-capture.txt", packets);
    Address cop(42, 1, 1);
    Address sim(6000, 1, 1);
    //Packet::LoadWiresharkCapturePacketExport("logs/example_capture-2.txt", packets);

    Message::List messages;
    Message::List::iterator message;
    
    // Delete UDP header data to get to just the JAUS message.
    for(packet = packets.begin(); packet != packets.end();)
    {
        // Delete UDP header data.
        packet->Delete(43);
        // Read message header data.
        Header jausHeader;
        if(jausHeader.Read(*packet))
        {
            UShort messageCode = 0;
            packet->Read(messageCode, Header::PayloadOffset);
            Message* jausMessage = component.TransportService()->CreateMessage(messageCode);
            if(jausMessage)
            {
                packet->SetReadPos(0);
                if(jausMessage->Read(*packet))
                {
                    messages.push_back(jausMessage);
                    if(jausMessage->GetMessageCode() == SET_ELEMENT)
                    {
                        Element::List::iterator m;
                        SetElement* setElement = (SetElement *)jausMessage;
                        for(m = setElement->GetElementList()->begin();
                            m != setElement->GetElementList()->end();
                            m++)
                        {
                            UShort code = 0;
                            m->mPayload.SetReadPos(0);
                            m->mPayload.Read(code);
                            Message* element = component.TransportService()->CreateMessage(code);
                            if(element)
                            {
                                element->CopyHeaderData(jausMessage);
                                if(element->ReadMessageBody(m->mPayload))
                                {
                                    messages.push_back(element);
                                }
                                else
                                {
                                    std::cout << "Failed to Read Message Data [" << std::hex << element->GetMessageCode() << "]:\n";
                                    delete element;
                                }
                            }
                        }
                    }
                }
                else
                {
                    std::cout << "Failed to Read Message Data [" << std::hex << jausMessage->GetMessageCode() << "]:\n";
                }
            }
            else
            {
                std::cout << "Unknown Message Type [" << std::hex << messageCode << "]:\n";
            }
        }
        else
        {
            std::cout << "Bad Header!\n";
        }
        packet++;
    }

    component.Initialize(cop);

    message = messages.begin();
    for(message = messages.begin(); 
        message != messages.end(); 
        message++)
    {
        //(*message)->Print();
        if((*message)->GetSourceID() == cop)
        {
            (*message)->SetDestinationID(sim);
            component.Send((*message));
        }
        CxUtils::SleepMs(1);
        delete (*message);
    }
}
Exemplo n.º 2
0
void FourSectionDictionary::populateHeader(Header & header, string rootNode)
{
	header.insert(rootNode, HDTVocabulary::DICTIONARY_TYPE, getType());
#if 0
	header.insert(rootNode, HDTVocabulary::DICTIONARY_NUMSUBJECTS, getNsubjects());
	header.insert(rootNode, HDTVocabulary::DICTIONARY_NUMPREDICATES, getNpredicates());
	header.insert(rootNode, HDTVocabulary::DICTIONARY_NUMOBJECTS, getNobjects());
	header.insert(rootNode, HDTVocabulary::DICTIONARY_MAXSUBJECTID, getMaxSubjectID());
	header.insert(rootNode, HDTVocabulary::DICTIONARY_MAXPREDICATEID, getMaxPredicateID());
	header.insert(rootNode, HDTVocabulary::DICTIONARY_MAXOBJECTTID, getMaxObjectID());
#endif
	header.insert(rootNode, HDTVocabulary::DICTIONARY_NUMSHARED, getNshared());
	header.insert(rootNode, HDTVocabulary::DICTIONARY_MAPPING, this->mapping);
	header.insert(rootNode, HDTVocabulary::DICTIONARY_SIZE_STRINGS, size());
	header.insert(rootNode, HDTVocabulary::DICTIONARY_BLOCK_SIZE, this->blocksize);
}
Exemplo n.º 3
0
    Eigen::MatrixXd get_DW_scheme (const Header& header)
    {
      DEBUG ("searching for suitable gradient encoding...");
      using namespace App;
      Eigen::MatrixXd grad;

      try {
        const auto opt_mrtrix = get_options ("grad");
        if (opt_mrtrix.size())
          grad = load_matrix<> (opt_mrtrix[0][0]);
        const auto opt_fsl = get_options ("fslgrad");
        if (opt_fsl.size()) {
          if (opt_mrtrix.size())
            throw Exception ("Please provide diffusion gradient table using either -grad or -fslgrad option (not both)");
          grad = load_bvecs_bvals (header, opt_fsl[0][0], opt_fsl[0][1]);
        }
        if (!opt_mrtrix.size() && !opt_fsl.size())
          grad = parse_DW_scheme (header);
      }
      catch (Exception& e) {
        throw Exception (e, "error importing diffusion gradient table for image \"" + header.name() + "\"");
      }

      if (!grad.rows())
        return grad;

      if (grad.cols() < 4)
        throw Exception ("unexpected diffusion gradient table matrix dimensions");

      INFO ("found " + str (grad.rows()) + "x" + str (grad.cols()) + " diffusion gradient table");

      return grad;
    }
Exemplo n.º 4
0
void Client::HandleUdpReceive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo)
{
    Header responseHeader;
    Header requestHeader;
    RequestMetadata requestMetadata;
    Message *message = NULL;
    ThreadError error;

    SuccessOrExit(error = responseHeader.FromMessage(aMessage));
    aMessage.MoveOffset(responseHeader.GetLength());

    message = FindRelatedRequest(responseHeader, aMessageInfo, requestHeader, requestMetadata);

    if (message == NULL)
    {
        ExitNow();
    }

    switch (responseHeader.GetType())
    {
    case kCoapTypeReset:
        if (responseHeader.IsEmpty())
        {
            FinalizeCoapTransaction(*message, requestMetadata, NULL, NULL, kThreadError_Abort);
        }

        // Silently ignore non-empty reset messages (RFC 7252, p. 4.2).
        break;

    case kCoapTypeAcknowledgment:
        if (responseHeader.IsEmpty())
        {
            // Empty acknowledgment.
            if (requestMetadata.mConfirmable)
            {
                requestMetadata.mAcknowledged = true;
                requestMetadata.UpdateIn(*message);
            }

            // Remove the message if response is not expected, otherwise await response.
            if (requestMetadata.mResponseHandler == NULL)
            {
                DequeueMessage(*message);
            }
        }
        else if (responseHeader.IsResponse() && responseHeader.IsTokenEqual(requestHeader))
        {
            // Piggybacked response.
            FinalizeCoapTransaction(*message, requestMetadata, &responseHeader, &aMessage, kThreadError_None);
        }

        // Silently ignore acknowledgments carrying requests (RFC 7252, p. 4.2)
        // or with no token match (RFC 7252, p. 5.3.2)
        break;

    case kCoapTypeConfirmable:
    case kCoapTypeNonConfirmable:
        if (responseHeader.IsConfirmable())
        {
            // Send empty ACK if it is a CON message.
            SendEmptyAck(aMessageInfo.GetPeerAddr(), aMessageInfo.mPeerPort, responseHeader.GetMessageId());
        }

        FinalizeCoapTransaction(*message, requestMetadata, &responseHeader, &aMessage, kThreadError_None);

        break;
    }

exit:

    if (error == kThreadError_None && message == NULL)
    {
        if (responseHeader.IsConfirmable() || responseHeader.IsNonConfirmable())
        {
            // Successfully parsed a header but no matching request was found - reject the message by sending reset.
            SendReset(aMessageInfo.GetPeerAddr(), aMessageInfo.mPeerPort, responseHeader.GetMessageId());
        }
    }
}
Exemplo n.º 5
0
 Eigen::MatrixXd parse_scheme (const Header& header)
 {
   Eigen::MatrixXd PE;
   const auto it = header.keyval().find ("pe_scheme");
   if (it != header.keyval().end()) {
     try {
       PE = parse_matrix (it->second);
     } catch (Exception& e) {
       throw Exception (e, "malformed PE scheme in image \"" + header.name() + "\"");
     }
     if (ssize_t(PE.rows()) != ((header.ndim() > 3) ? header.size(3) : 1))
       throw Exception ("malformed PE scheme in image \"" + header.name() + "\" - number of rows does not equal number of volumes");
   } else {
     // Header entries are cast to lowercase at some point
     const auto it_dir  = header.keyval().find ("PhaseEncodingDirection");
     const auto it_time = header.keyval().find ("TotalReadoutTime");
     if (it_dir != header.keyval().end() && it_time != header.keyval().end()) {
       Eigen::Matrix<default_type, 4, 1> row;
       row.head<3>() = Axes::id2dir (it_dir->second);
       row[3] = to<default_type>(it_time->second);
       PE.resize ((header.ndim() > 3) ? header.size(3) : 1, 4);
       PE.rowwise() = row.transpose();
     }
   }
   return PE;
 }
Exemplo n.º 6
0
void
MultiPartInputFile::initialize()
{
    readMagicNumberAndVersionField(*_data->is, _data->version);
    
    bool multipart = isMultiPart(_data->version);
    bool tiled = isTiled(_data->version);

    //
    // Multipart files don't have and shouldn't have the tiled bit set.
    //

    if (tiled && multipart)
        throw IEX_NAMESPACE::InputExc ("Multipart files cannot have the tiled bit set");

    
    int pos = 0;
    while (true)
    {
        Header header;
        header.readFrom(*_data->is, _data->version);

        //
        // If we read nothing then we stop reading.
        //

        if (header.readsNothing())
        {
            pos++;
            break;
        }

        _data->_headers.push_back(header);
        
        if(multipart == false)
          break;
    }

    //
    // Perform usual check on headers.
    //

    for (size_t i = 0; i < _data->_headers.size(); i++)
    {
        //
        // Silently invent a type if the file is a single part regular image.
        //

        if( _data->_headers[i].hasType() == false )
        {
            if(multipart)

                throw IEX_NAMESPACE::ArgExc ("Every header in a multipart file should have a type");
          
            _data->_headers[i].setType(tiled ? TILEDIMAGE : SCANLINEIMAGE);
        }
        else
        {
            
            //
            // Silently fix the header type if it's wrong
            // (happens when a regular Image file written by EXR_2.0 is rewritten by an older library,
            //  so doesn't effect deep image types)
            //

            if(!multipart && !isNonImage(_data->version))
            {
                _data->_headers[i].setType(tiled ? TILEDIMAGE : SCANLINEIMAGE);
            }
        }
         

        
        if( _data->_headers[i].hasName() == false )
        {
            if(multipart)
                throw IEX_NAMESPACE::ArgExc ("Every header in a multipart file should have a name");
        }
        
        if (isTiled(_data->_headers[i].type()))
            _data->_headers[i].sanityCheck(true, multipart);
        else
            _data->_headers[i].sanityCheck(false, multipart);
    }

    //
    // Check name uniqueness.
    //

    if (multipart)
    {
        set<string> names;
        for (size_t i = 0; i < _data->_headers.size(); i++)
        {
        
            if (names.find(_data->_headers[i].name()) != names.end())
            {
                throw IEX_NAMESPACE::InputExc ("Header name " + _data->_headers[i].name() +
                                   " is not a unique name.");
            }
            names.insert(_data->_headers[i].name());
        }
    }
    
    //
    // Check shared attributes compliance.
    //

    if (multipart && strictSharedAttribute)
    {
        for (size_t i = 1; i < _data->_headers.size(); i++)
        {
            vector <string> attrs;
            if (_data->checkSharedAttributesValues (_data->_headers[0], _data->_headers[i], attrs))
            {
                string attrNames;
                for (size_t j=0; j<attrs.size(); j++)
                    attrNames += " " + attrs[j];
                throw IEX_NAMESPACE::InputExc ("Header name " + _data->_headers[i].name() +
                                     " has non-conforming shared attributes: "+
                                     attrNames);
            }
        }
    }

    //
    // Create InputParts and read chunk offset tables.
    //
        
    for (size_t i = 0; i < _data->_headers.size(); i++)
        _data->parts.push_back(
                new InputPartData(_data, _data->_headers[i], i, _data->numThreads, _data->version));

    _data->readChunkOffsetTables(_data->reconstructChunkOffsetTable);
}
oc::result<void> AndroidFormatWriter::write_header(File &file,
                                                   const Header &header)
{
    // Construct header
    m_hdr = {};
    memcpy(m_hdr.magic, BOOT_MAGIC, BOOT_MAGIC_SIZE);

    if (auto address = header.kernel_address()) {
        m_hdr.kernel_addr = *address;
    }
    if (auto address = header.ramdisk_address()) {
        m_hdr.ramdisk_addr = *address;
    }
    if (auto address = header.secondboot_address()) {
        m_hdr.second_addr = *address;
    }
    if (auto address = header.kernel_tags_address()) {
        m_hdr.tags_addr = *address;
    }
    if (auto page_size = header.page_size()) {
        switch (*page_size) {
        case 2048:
        case 4096:
        case 8192:
        case 16384:
        case 32768:
        case 65536:
        case 131072:
            m_hdr.page_size = *page_size;
            break;
        default:
            //DEBUG("Invalid page size: %" PRIu32, *page_size);
            return AndroidError::InvalidPageSize;
        }
    } else {
        return AndroidError::MissingPageSize;
    }

    if (auto board_name = header.board_name()) {
        if (board_name->size() >= sizeof(m_hdr.name)) {
            return AndroidError::BoardNameTooLong;
        }

        strncpy(reinterpret_cast<char *>(m_hdr.name), board_name->c_str(),
                sizeof(m_hdr.name) - 1);
        m_hdr.name[sizeof(m_hdr.name) - 1] = '\0';
    }
    if (auto cmdline = header.kernel_cmdline()) {
        if (cmdline->size() >= sizeof(m_hdr.cmdline)) {
            return AndroidError::KernelCmdlineTooLong;
        }

        strncpy(reinterpret_cast<char *>(m_hdr.cmdline), cmdline->c_str(),
                sizeof(m_hdr.cmdline) - 1);
        m_hdr.cmdline[sizeof(m_hdr.cmdline) - 1] = '\0';
    }

    // TODO: UNUSED
    // TODO: ID

    std::vector<SegmentWriterEntry> entries;

    entries.push_back({ ENTRY_TYPE_KERNEL, 0, {}, m_hdr.page_size });
    entries.push_back({ ENTRY_TYPE_RAMDISK, 0, {}, m_hdr.page_size });
    entries.push_back({ ENTRY_TYPE_SECONDBOOT, 0, {}, m_hdr.page_size });
    entries.push_back({ ENTRY_TYPE_DEVICE_TREE, 0, {}, m_hdr.page_size });

    OUTCOME_TRYV(m_seg->set_entries(std::move(entries)));

    // Start writing after first page
    auto seek_ret = file.seek(m_hdr.page_size, SEEK_SET);
    if (!seek_ret) {
        if (file.is_fatal()) { m_writer.set_fatal(); }
        return seek_ret.as_failure();
    }

    return oc::success();
}
Exemplo n.º 8
0
int main(int argc, char** argv)
{
	(void) argc;
	(void) argv;
	signal(SIGCHLD, SIG_IGN);
	int iSocket = socket(AF_INET, SOCK_STREAM, 0);
	if (iSocket < 0) {
		fprintf(stderr, "socket failed %d, errno %d\n", 
				iSocket, errno);
		return 0;
	}
	struct sockaddr_in servAddr, cliAddr;
	socklen_t iCliLen = sizeof(cliAddr);
	memset(&servAddr, 0, sizeof(servAddr));
	servAddr.sin_family = AF_INET;
	servAddr.sin_addr.s_addr = inet_addr(*(argv + 1));
	servAddr.sin_port = htons(atoi(*(argv + 2)));
	int option = 1;
	setsockopt(iSocket, SOL_SOCKET, SO_REUSEADDR, (const void *)&option, sizeof(option));
	bind(iSocket, (struct sockaddr *)&servAddr, sizeof(servAddr));
	listen(iSocket, 512);
	while(1) {
		int iCliFd;
		iCliFd = accept(iSocket, (struct sockaddr *)&cliAddr, &iCliLen);
		if (iCliFd < 0) {
			fprintf(stderr, "accept failed %d, errno %d\n",
					iCliFd, errno);
			return 0;
		}

		pid_t pid = fork();
		if (pid == 0)
		{

#define USERID 1
			char sBuf[10240];
			ssize_t size;
			uint64_t iMsgId = 1ull;
			Encoder encoder(sBuf, sizeof(sBuf));
			Decoder decoder;
			{
				ConnSvrConnectChallenge req;
				char sRandomStr[256];
				memset(sRandomStr, 'z', sizeof(sRandomStr));
				req.set_random_msg(sRandomStr, 256);
				Header header;
				header.set_type(kMsgTypeConnSvrConnectChallenge);
				header.set_msg_id(iMsgId++);
				encoder.EncodeHeader(header);
				encoder.Encode(req);
				size = send(iCliFd, encoder.Data(), encoder.DataLen(), 0);
				printf("send %ld\n", size);
			}
			{
				Header header;
				size = recv(iCliFd, sBuf, sizeof(sBuf), 0);
				decoder.DecodeHeader(sBuf, size, &header);
				ConnSvrConnectReq resp;
				decoder.DecodePayload(&resp);
				unsigned char sUserAgentBuf[1024];
				UserAgent userAgent;
				if (resp.has_user_agent()) {
					const std::string &sUserAgent = resp.user_agent();
					memcpy(sUserAgentBuf, sUserAgent.c_str(), sUserAgent.size());
					if (sUserAgent.size()) {
						unsigned char inputKey = sUserAgentBuf[0];
						unsigned char outputKey;
						for(int i = 1, n = sUserAgent.size(); i != n; i++) {
							outputKey = sUserAgentBuf[i];
							sUserAgentBuf[i] ^= inputKey;
							inputKey = outputKey;
						}
					}
					userAgent.ParseFromArray(sUserAgentBuf + 1, sUserAgent.size() - 1);
				}
				printf("type %d, msgid %lu, phonenum %s, role %d, secretchap %s, ostype %s, osver %s, model %s, clientver %s, network %s, location %s operator %s\n",
						header.type(), header.has_msg_id() ? header.msg_id() : 0,
						resp.phone_num().c_str(), resp.role(), resp.secret_chap().c_str(),
						userAgent.has_os_type() ? userAgent.os_type().c_str() : "",
						userAgent.has_os_ver() ? userAgent.os_ver().c_str() : "",
						userAgent.has_model() ? userAgent.model().c_str() : "",
						userAgent.has_client_ver() ? userAgent.client_ver().c_str() : "",
						userAgent.has_network() ? userAgent.network().c_str() : "",
						userAgent.has_location() ? userAgent.location().c_str() : "",
						userAgent.has_carrier_operator() ? userAgent.carrier_operator().c_str() : "");
			}
			{
				ConnSvrConnectRsp req;
				RspMsg* pRspMsg = req.mutable_rsp_msg();
				pRspMsg->set_rsp_code(0);
				pRspMsg->set_rsp_msg("OK");
				Header header;
				header.set_type(kMsgTypeConnSvrConnectRsp);
				header.set_msg_id(iMsgId++);
				encoder.EncodeHeader(header);
				encoder.Encode(req);
				size = send(iCliFd, encoder.Data(), encoder.DataLen(), 0);
				printf("send %ld\n", size);
			}
			int number = 0;
			while(number < 100) {
				size = recv(iCliFd, sBuf, sizeof(sBuf), 0);
				if (size == 0) {
					break;
				}
				Header header;
				decoder.DecodeHeader(sBuf, size, &header);
				printf("type %d, msgid %lu, ",
						header.type(), header.has_msg_id() ? header.msg_id() : 0);
				if (header.type() == kMsgTypeConnSvrHeartbeatReq) {
					ConnSvrHeartbeatReq resp;
					decoder.DecodePayload(&resp);
					printf("heartbeat\n");
				} else if (header.type() == kMsgTypeCdntSvrUpReq) {
					Coordinate resp;
					decoder.DecodePayload(&resp);
					printf("x %lf, y %lf, coordinatetype %d\n",
							resp.x(), resp.y(), resp.type());
				} else if (header.type() == kMsgTypeDispatchSvrNoRspReq) {
					BinaryMsg req;
					decoder.DecodePayload(&req);
					if (req.type() == kDispatchMessageTypeDriverOrderGetReq) {
						DriverOrderGetReq getReq;
						getReq.ParseFromArray(req.payload().data(), req.payload().size());
						const DriverOrderGetReq::LastStatus &lastStatus = getReq.laststatus();
						printf("type %d, phone %s, token %s, oid %s, down %d, play %d, cancel %d\n",
								req.type(), getReq.phone().c_str(), getReq.token().c_str(),
								lastStatus.oid().c_str(), lastStatus.down(), lastStatus.play(), 
								lastStatus.cancel());
					}
				} else {
					printf("unkown type %d\n", header.type());
				}
				number++;
				if (number == 4) {
					ConnSvrHeartbeatReq req;
					Header header;
					header.set_type(kMsgTypeConnSvrHeartbeatReq);
					header.set_msg_id(iMsgId++);
					encoder.EncodeHeader(header);
					encoder.Encode(req);
					size = send(iCliFd, encoder.Data(), encoder.DataLen(), 0);
					printf("send %ld\n", size);
				}
				/* else if (number == 7) {
					CdntSvrDownReq req;
					Header header;
					header.set_type(kMsgTypeCdntSvrDownReq);
					header.set_msg_id(iMsgId++);
					{
						PeerCoordinateInfo* pPeerCoordinateInfo = req.add_peer_coordinate_infos();
						Coordinate* pCoordinate = pPeerCoordinateInfo->mutable_coordinate();
						pCoordinate->set_x(1.0f);
						pCoordinate->set_y(1.0f);
						pCoordinate->set_type(DidiPush::BD_09);
						pPeerCoordinateInfo->set_distance(10);
						pPeerCoordinateInfo->set_wait_time(10);
						pPeerCoordinateInfo->set_local_id("aslkdjflajk");
					}
					{
						PeerCoordinateInfo* pPeerCoordinateInfo = req.add_peer_coordinate_infos();
						Coordinate* pCoordinate = pPeerCoordinateInfo->mutable_coordinate();
						pCoordinate->set_x(2.0f);
						pCoordinate->set_y(2.0f);
						pCoordinate->set_type(DidiPush::BD_09);
						pPeerCoordinateInfo->set_distance(20);
						pPeerCoordinateInfo->set_wait_time(20);
						pPeerCoordinateInfo->set_local_id("lkjlkjlkj");
					}
					encoder.EncodeHeader(header);
					encoder.Encode(req);
					size = send(iCliFd, encoder.Data(), encoder.DataLen(), 0);
					printf("send %ld\n", size);
				} else if (number == 9) {
					Header header;
					header.set_type(kMsgTypeConnSvrDisconnectReq);
					header.set_msg_id(iMsgId++);
					ConnSvrDisconnectReq req;
					encoder.EncodeHeader(header);
					encoder.Encode(req);
					size = send(iCliFd, encoder.Data(), encoder.DataLen(), 0);
					printf("send %ld\n", size);
				} else if (number == 4) {
					BinaryMsg msg;
					msg.set_type(kPushMessageTypeDriverOrderStrivedReq);
					char sBuf[10240];
					DriverOrderStrivedReq req;
					req.set_oid("asldkjfa");
					req.set_dinfo("alskjdflakj");
					req.set_msg("msg");
					req.set_showtype(DriverMessageTipShowTypeWindow);
					req.SerializeToArray(sBuf, req.ByteSize());
					msg.set_payload(sBuf, req.ByteSize());
					msg.SerializeToArray(sBuf, msg.ByteSize());
					Header header;
					header.set_type(kMsgTypeAppPushMessageReq);
					header.set_msg_id(iMsgId++);
					encoder.EncodeHeader(header);
					encoder.Encode(msg);
					size = send(iCliFd, encoder.Data(), encoder.DataLen(), 0);
					printf("send %ld\n", size);
				}
				*/
			}
			close(iCliFd);
			return 0;
		} else if (pid > 0) {
			close(iCliFd);
		} else {
			fprintf(stderr, "Fork failed\n");
		}
	}
	return 0;
}
Exemplo n.º 9
0
      std::shared_ptr<Handler::Base> MRtrix_sparse::create (Header& H) const
      {

        Header::const_iterator name_it = H.find (Image::Sparse::name_key);
        if (name_it == H.end())
          throw Exception ("Cannot create sparse image " + H.name() + "; no knowledge of underlying data class type");

        Header::const_iterator size_it = H.find (Image::Sparse::size_key);
        if (size_it == H.end())
          throw Exception ("Cannot create sparse image " + H.name() + "; no knowledge of underlying data class size");

        H.datatype() = DataType::UInt64;
        H.datatype().set_byte_order_native();

        File::OFStream out (H.name(), std::ios::out | std::ios::binary);

        out << "mrtrix sparse image\n";

        write_mrtrix_header (H, out);

        bool single_file = Path::has_suffix (H.name(), ".msf");

        int64_t image_offset = 0, sparse_offset = 0;
        std::string image_path, sparse_path;
        if (single_file) {

          image_offset = out.tellp() + int64_t(54);
          image_offset += ((4 - (image_offset % 4)) % 4);
          sparse_offset = image_offset + Image::footprint(H);

          out << "file: . " << image_offset << "\nsparse_file: . " << sparse_offset << "\nEND\n";

          File::resize (H.name(), sparse_offset);
          image_path = H.name();
          sparse_path = H.name();

        } else {

          image_path  = Path::basename (H.name().substr (0, H.name().size()-4) + ".dat");
          sparse_path = Path::basename (H.name().substr (0, H.name().size()-4) + ".sdat");

          out << "file: " << image_path << "\nsparse_file: " << sparse_path << "\nEND\n";

          File::create (image_path, Image::footprint(H));
          File::create (sparse_path);

        }

        Handler::Default base_handler (H);
        base_handler.files.push_back (File::Entry (image_path, image_offset));

        std::shared_ptr<Handler::Base> handler (new Handler::Sparse (base_handler, name_it->second, to<size_t>(size_it->second), File::Entry (sparse_path, sparse_offset)));

        return handler;
      }
Exemplo n.º 10
0
    int Control::process(Header &header) {
        size_ = header.payload_size() + 2;
        Utilities::Utf8::Byte utf8;
        uint8_t mask_offset = 0;
        uint8_t *buffer = &(*buffer_.get())[0];

        buffer[0] = header.begin()[0];
        buffer[1] = header.begin()[1];
        
        Utilities::Print::hex(&buffer[0],header.payload_size()+2); std::cout << std::endl;
       
    if(   (buffer[0] & 0x0F) == 0x08) {
        if(header.payload_size() >= 2) {
            Utilities::Websocket::applyMask(&buffer[2]
                    , 2 
                    , &header.mask(), mask_offset
                    , false
                    , utf8);

            Utilities::Websocket::applyMask(&buffer[4]
                    , header.payload_size() -2
                    , &header.mask(), mask_offset
                    , true 
                    , utf8);

            if(!utf8.complete()) {
                std::cout << "invalid utf in control" << std::endl;
                return 1007;
            }
        }
        state_ = ControlState::KILL;
        std::cout << "control kill" << std::endl;
        buffer[1] &= 0x7F;
        uint16_t code = buffer[2] << 8 | buffer[3] << 0;
        if(    code < 1000
            ||(code < 3000
                && code != 1000 && code != 1001 && code != 1002 && code != 1003 
                && code != 1007 && code != 1008 && code != 1009 && code != 1010
                && code != 1011)
            || code > 4999
          ) {
            buffer[2] = 0x03;
            buffer[3] = 0xEA;
        }
    } else if ( (buffer[0] & 0x0F) == 0x09 ) {
        Utilities::Websocket::applyMask(&buffer[2]
                , header.payload_size()
                , &header.mask(), mask_offset
                , false 
                , utf8);
        if(!utf8.complete()) {
            std::cout << "invalid utf in control" << std::endl;
            return 1007;
        }
        state_ = ControlState::PING;
        buffer[0] = ( buffer[0] & 0xF0 ) | 0x0A;
        buffer[1] &= 0x7F;
        std::cout << "control pong"; Utilities::Print::hex(&buffer[0],2);std::cout <<std::endl;
    } else if ( (buffer[0] & 0x0F) == 0x0A ) {
        state_ = ControlState::PONG;
        std::cout << "pong recieved" << std::endl;
    } else {
      state_ = ControlState::INVALID;
    }
    return 0;
    }
Exemplo n.º 11
0
result
EventListForm::OnInitializing(void)
{
	result r = E_SUCCESS;

	Header* pHeader = GetHeader();
	AppAssert(pHeader);

	DateTime today;
	String formattedString;

	SystemTime::GetCurrentTime(WALL_TIME, today);

	__pLocaleCalendar = Tizen::Locales::Calendar::CreateInstanceN(CALENDAR_GREGORIAN);
	__pLocaleCalendar->SetTime(today);
	DateTimeFormatter* pDateFormatter = DateTimeFormatter::CreateDateFormatterN(DATE_TIME_STYLE_DEFAULT);

	String customizedPattern = L"dd MMM yyyy";
	pDateFormatter->ApplyPattern(customizedPattern);
	pDateFormatter->Format(*__pLocaleCalendar, formattedString);

	HeaderItem headerDaily;
	headerDaily.Construct(ID_HEADER_DAILY);
	headerDaily.SetText(L"일");

	HeaderItem headerMonthly;
	headerMonthly.Construct(ID_HEADER_MONTHLY);
	headerMonthly.SetText(L"월");

	pHeader->SetStyle(HEADER_STYLE_SEGMENTED_WITH_TITLE);
	pHeader->SetTitleText(formattedString);
	pHeader->AddItem(headerDaily);
	pHeader->AddItem(headerMonthly);
	pHeader->AddActionEventListener(*this);

	Footer* pFooter = GetFooter();
	AppAssert(pFooter);
	pFooter->SetStyle(FOOTER_STYLE_BUTTON_TEXT);

	FooterItem footerCreate;
	footerCreate.Construct(ID_FOOTER_CREATE);
	footerCreate.SetText(L"일정 생성");
	pFooter->AddItem(footerCreate);

	SetFormBackEventListener(this);
	pFooter->AddActionEventListener(*this);

	Tizen::Ui::Controls::Button* pPreviousButton = new (std::nothrow) Button();
	pPreviousButton->Construct(Rectangle(0, 0, GetClientAreaBounds().width / 2, 72), L"이전");
	pPreviousButton->SetActionId(ID_BUTTON_PREV);
	pPreviousButton->AddActionEventListener(*this);
	AddControl(pPreviousButton);

	Tizen::Ui::Controls::Button* pNextButton = new (std::nothrow) Button();
	pNextButton->Construct(Rectangle(GetClientAreaBounds().width / 2, 0, GetClientAreaBounds().width / 2, 72), L"다음");
	pNextButton->SetActionId(ID_BUTTON_NEXT);
	pNextButton->AddActionEventListener(*this);
	AddControl(pNextButton);

	__pGroupedListView = new (std::nothrow) GroupedListView();
	__pGroupedListView->Construct(Rectangle(0, 72, GetClientAreaBounds().width, GetClientAreaBounds().height - 72), GROUPED_LIST_VIEW_STYLE_INDEXED, true, SCROLL_STYLE_FADE_OUT);
	__pGroupedListView->SetTextOfEmptyList(L"일정 없음");
	__pGroupedListView->SetItemProvider(*this);
	__pGroupedListView->AddGroupedListViewItemEventListener(*this);
	__pGroupedListView->SetItemDividerColor(Tizen::Graphics::Color::GetColor(COLOR_ID_BLACK));
	AddControl(__pGroupedListView);

	LocaleManager localeManager;
	localeManager.Construct();
	__timeZone = localeManager.GetSystemTimeZone();

	return r;
}
Exemplo n.º 12
0
void writeToFile(fs::path _path)
{
	stringstream ss;

	if (fileCount < 0){
		fileCount = 0;
		ss << fileCount;
		outFile.open(fs::path(string(BASE_MODEL_PATH)+"/Data"+ss.str()+".bin"), ios::binary);
		ss.flush();
	}
	else if (byteCount > BYTE_LIMIT){
		outFile.flush();
		outFile.close();
		fileCount++;
		ss << fileCount;
		outFile.open(fs::path(string(BASE_DEST_PATH)+"/Data"+ss.str()+".bin"), ios::binary);
		ss.flush();
		byteCount = 0;
		// close file and open new
	}

	Header head;
	head.id = strToUint64(_path.stem());


	idxFile.open(_path, ios::binary);
	dataFile.open(_path.parent_path() / (_path.stem()+".data"), ios::binary);

	idxFile.seekg(0, ios::beg);
	idxFile.read((char*)&head.indexCount, sizeof(unsigned));
	idxFile.seekg(4, ios::beg);
	dataFile.seekg(0, ios::beg);
	dataFile.read((char*)&head.vertexCount, sizeof(unsigned));
	dataFile.seekg(4, ios::beg);

	indexData = new unsigned[head.indexCount];
	vertexData = new ooctools::V4N4[head.vertexCount];

	idxFile.read((char*)indexData, sizeof(unsigned)*head.indexCount);
	idxFile.close();

	dataFile.read((char*)vertexData, sizeof(V4N4)*head.vertexCount);
	dataFile.close();

	// ------------------------------------
	//write to file

	outFile.seekp(byteCount, ios::beg);
	//writing header-info
	outFile.write((char*)&head, sizeof(Header));
	outFile.seekp(byteCount+sizeof(Header), ios::beg);
	//writing the indices
	outFile.write((char*)indexData, head.indexCount*sizeof(unsigned));
	outFile.seekp(byteCount + sizeof(Header) + head.indexCount*sizeof(unsigned), ios::beg);
	//writing the vertices
	outFile.write((char*)vertexData, head.vertexCount*sizeof(V4N4));
	byteCount += head.sizeOf();
	outFile.flush();

	delete[] vertexData;
	vertexData = 0;
	delete[] indexData;
	indexData = 0;
}
Exemplo n.º 13
0
void Multipart::simplifyMimeStructure()
{
    // If we're looking at a multipart with just a single part, change
    // the mime type to avoid the middle multipart. This affects
    // Kaiten Mail.
    if ( header()->contentType() &&
         header()->contentType()->type() == "multipart" &&
         parts->count() == 1 &&
         ( !parts->firstElement()->header()->contentType() ||
           parts->firstElement()->header()->contentType()->type() != "multipart" ) ) {
        Header * me = header();
        Header * sub = parts->firstElement()->header();

        me->removeField( HeaderField::ContentType );
        ContentType * ct = sub->contentType();
        if ( ct )
            me->add( ct );

        me->removeField( HeaderField::ContentTransferEncoding );
        ContentTransferEncoding * cte = sub->contentTransferEncoding();
        if ( cte )
            me->add( cte );

        me->removeField( HeaderField::ContentDisposition );
        ContentDisposition * cd = sub->contentDisposition();
        if ( cd )
            me->add( cd );

        if ( !ct && !cte && !cd )
            me->removeField( HeaderField::MimeVersion );
    }
}
Exemplo n.º 14
0
 /**
  *  This method checks if Tokens in two CoAP headers are equal.
  *
  *  @param[in]  aHeader  A header to compare.
  *
  * @retval TRUE   If two Tokens are equal.
  * @retval FALSE  If Tokens differ in length or value.
  *
  */
 bool IsTokenEqual(const Header &aHeader) const {
     return ((this->GetTokenLength() == aHeader.GetTokenLength()) &&
             (memcmp(this->GetToken(), aHeader.GetToken(), this->GetTokenLength()) == 0));
 }
Exemplo n.º 15
0
void GPUOctree::dumpIndirection(const char *filename)
{
	m_idr = new short[INDIRECTIONPOOLSIZE*4];
	m_dt = new float[DATAPOOLSIZE*4];

	setIndirection(m_root);
	
	half *idr_r = new half[INDIRECTIONPOOLSIZE];
	half *idr_g = new half[INDIRECTIONPOOLSIZE];
	half *idr_b = new half[INDIRECTIONPOOLSIZE];
	half *idr_a = new half[INDIRECTIONPOOLSIZE];
	
	for(long i=0; i<INDIRECTIONPOOLSIZE; i++) {
		idr_r[i] = (half)m_idr[i*4];
		idr_g[i] = (half)m_idr[i*4+1];
		idr_b[i] = (half)m_idr[i*4+2];
		idr_a[i] = (half)m_idr[i*4+3];
	}
	
// save indirection	
	Header idrheader (INDIRECTIONPOOLWIDTH, INDIRECTIONPOOLWIDTH); 
	idrheader.insert ("root_size", FloatAttribute (m_rootSize));
	idrheader.insert ("root_center", V3fAttribute (Imath::V3f(m_rootCenter.x, m_rootCenter.y, m_rootCenter.z))); 

		idrheader.channels().insert ("R", Channel (HALF));
		idrheader.channels().insert ("G", Channel (HALF));                                   // 1 
        idrheader.channels().insert ("B", Channel (HALF));
		idrheader.channels().insert ("A", Channel (HALF));                   // 2  
    
	std::string idrname = filename;
	idrname += ".idr";
        OutputFile idrfile (idrname.c_str(), idrheader);                               // 4 
        FrameBuffer idrframeBuffer;
		 idrframeBuffer.insert ("R",                                // name   // 6 
                            Slice (HALF,                        // type   // 7 
                                   (char *) idr_r,            // base   // 8 
                                   sizeof (*idr_r) * 1,       // xStride// 9 
                                   sizeof (*idr_r) * INDIRECTIONPOOLWIDTH));
        idrframeBuffer.insert ("G",                                // name   // 6 
                            Slice (HALF,                        // type   // 7 
                                   (char *) idr_g,            // base   // 8 
                                   sizeof (*idr_g) * 1,       // xStride// 9 
                                   sizeof (*idr_g) * INDIRECTIONPOOLWIDTH));
		 idrframeBuffer.insert ("B",                                // name   // 6 
                            Slice (HALF,                        // type   // 7 
                                   (char *) idr_b,            // base   // 8 
                                   sizeof (*idr_b) * 1,       // xStride// 9 
                                   sizeof (*idr_b) * INDIRECTIONPOOLWIDTH));
		 idrframeBuffer.insert ("A",                                // name   // 6 
                            Slice (HALF,                        // type   // 7 
                                   (char *) idr_a,            // base   // 8 
                                   sizeof (*idr_a) * 1,       // xStride// 9 
                                   sizeof (*idr_a) * INDIRECTIONPOOLWIDTH));
       
        idrfile.setFrameBuffer (idrframeBuffer);                                // 16 
        idrfile.writePixels (INDIRECTIONPOOLWIDTH); 
        
        delete[] idr_r;
	delete[] idr_g;
	delete[] idr_b;
	delete[] idr_a;
// save data

	half *dt_r = new half[DATAPOOLSIZE];
	half *dt_g = new half[DATAPOOLSIZE];
	half *dt_b = new half[DATAPOOLSIZE];
	half *dt_a = new half[DATAPOOLSIZE];
	
	for(long i=0; i<DATAPOOLSIZE; i++) {
		dt_r[i] = (half)m_dt[i*4];
		dt_g[i] = (half)m_dt[i*4+1];
		dt_b[i] = (half)m_dt[i*4+2];
		dt_a[i] = (half)m_dt[i*4+3];
	}
	
	Header dtheader (DATAPOOLWIDTH, DATAPOOLWIDTH); 
		dtheader.channels().insert ("R", Channel (HALF));
		dtheader.channels().insert ("G", Channel (HALF));                                   // 1 
        dtheader.channels().insert ("B", Channel (HALF));
		dtheader.channels().insert ("A", Channel (HALF));                   // 2  
    
	std::string dtname = filename;
	dtname += ".exr";
        OutputFile dtfile (dtname.c_str(), dtheader);                               // 4 
        FrameBuffer dtframeBuffer;
		 dtframeBuffer.insert ("R",                                // name   // 6 
                            Slice (HALF,                        // type   // 7 
                                   (char *) dt_r,            // base   // 8 
                                   sizeof (*dt_r) * 1,       // xStride// 9 
                                   sizeof (*dt_r) * DATAPOOLWIDTH));
        dtframeBuffer.insert ("G",                                // name   // 6 
                            Slice (HALF,                        // type   // 7 
                                   (char *) dt_g,            // base   // 8 
                                   sizeof (*dt_g) * 1,       // xStride// 9 
                                   sizeof (*dt_g) * DATAPOOLWIDTH));
		 dtframeBuffer.insert ("B",                                // name   // 6 
                            Slice (HALF,                        // type   // 7 
                                   (char *) dt_b,            // base   // 8 
                                   sizeof (*dt_b) * 1,       // xStride// 9 
                                   sizeof (*dt_b) * DATAPOOLWIDTH));
		 dtframeBuffer.insert ("A",                                // name   // 6 
                            Slice (HALF,                        // type   // 7 
                                   (char *) dt_a,            // base   // 8 
                                   sizeof (*dt_a) * 1,       // xStride// 9 
                                   sizeof (*dt_a) * DATAPOOLWIDTH));
       
        dtfile.setFrameBuffer (dtframeBuffer);                                // 16 
        dtfile.writePixels (DATAPOOLWIDTH); 
		
	delete[] dt_r;
	delete[] dt_g;
	delete[] dt_b;
	delete[] dt_a;
}
Exemplo n.º 16
0
Injectee * DSN::result() const
{
    Injectee * r = new Injectee;
    Bodypart * plainText = new Bodypart( 1, r );
    Bodypart * dsn = new Bodypart( 2, r );
    Bodypart * original = new Bodypart( 3, r );

    plainText->setParent( r );
    dsn->setParent( r );
    original->setParent( r );
    r->children()->append( plainText );
    r->children()->append( dsn );
    r->children()->append( original );

    // set up the original message, either full or header-only
    if ( fullReport() ) {
        original->header()->add( "Content-Type", "text/rfc822-headers" );
        original->setData( message()->header()->asText() );

        // this is what we _should_ do, except that we don't. the body
        // of the message is lost, probably because original-> has a
        // null parent.

        //original->header()->add( "Content-Type", "message/rfc822" );
        //original->setMessage( message() );

        // and maybe we shouldn't anyway. sending a potentially big
        // body in a bounce is not necessarily a good idea.
    }
    else {
        // nasty mime name there
        original->header()->add( "Content-Type", "text/rfc822-headers" );
        original->setData( message()->header()->asText() );
    }

    // the from field has to contain... what? let's try this for now.
    Address * from = new Address( Configuration::hostname(),
                                  "postmaster",
                                  Configuration::hostname() );
    // set up the top-level header
    Header * h = r->header();
    if ( resultDate() ) {
        h->add( "Date", resultDate()->rfc822() );
    }
    else {
        Date * now = new Date;
        now->setCurrentTime();
        h->add( "Date", now->rfc822() );
    }
    h->add( "From", from->toString() );
    if ( sender() )
        h->add( "To", sender()->toString() );
    if ( allOk() )
        h->add( "Subject", "Message delivered" );
    else if ( allFailed() )
        h->add( "Subject", "Message delivery failed" );
    else
        h->add( "Subject", "Message delivery reports" );
    h->add( "Mime-Version", "1.0" );
    h->add( "Content-Type", "multipart/report; boundary=" +
            Message::acceptableBoundary( message()->rfc822() ) );

    // set up the plaintext and DSN parts
    // what charset should we use for plainText?
    plainText->header()->add( "Content-Type", "text/plain; format=flowed" );
    dsn->header()->add( "Content-Type", "message/delivery-status" );

    plainText->setData( plainBody() );
    dsn->setData( dsnBody() );
    r->addMessageId();

    return r;
}
Exemplo n.º 17
0
bool
MultiPartInputFile::Data::checkSharedAttributesValues(const Header & src,
                                                const Header & dst,
                                                vector<string> & conflictingAttributes) const
{
    conflictingAttributes.clear();

    bool conflict = false;

    //
    // Display Window
    //
    if (src.displayWindow() != dst.displayWindow())
    {
        conflict = true;
        conflictingAttributes.push_back ("displayWindow");
    }


    //
    // Pixel Aspect Ratio
    //
    if (src.pixelAspectRatio() != dst.pixelAspectRatio())
    {
        conflict = true;
        conflictingAttributes.push_back ("pixelAspectRatio");
    }


    //
    // Timecode
    //
    const TimeCodeAttribute * srcTimeCode = src.findTypedAttribute<
          TimeCodeAttribute> (TimeCodeAttribute::staticTypeName());
    const TimeCodeAttribute * dstTimeCode = dst.findTypedAttribute<
          TimeCodeAttribute> (TimeCodeAttribute::staticTypeName());

    if (dstTimeCode)
    {
        if  ( (srcTimeCode && (srcTimeCode->value() != dstTimeCode->value())) ||
              (!srcTimeCode))
        {
            conflict = true;
            conflictingAttributes.push_back (TimeCodeAttribute::staticTypeName());
        }
    }

    //
    // Chromaticities
    //
    const ChromaticitiesAttribute * srcChrom =  src.findTypedAttribute<
          ChromaticitiesAttribute> (ChromaticitiesAttribute::staticTypeName());
    const ChromaticitiesAttribute * dstChrom =  dst.findTypedAttribute<
          ChromaticitiesAttribute> (ChromaticitiesAttribute::staticTypeName());

    if (dstChrom)
    {
        if ( (srcChrom && (srcChrom->value() != dstChrom->value())) ||
             (!srcChrom))
        {
            conflict = true;
            conflictingAttributes.push_back (ChromaticitiesAttribute::staticTypeName());
        }
    }


    return conflict;
}
Exemplo n.º 18
0
void Exporter::execute()
{
    if ( Mailbox::refreshing() ) {
        Database::notifyWhenIdle( this );
        return;
    }

    if ( !d->mailbox && !d->sourceName.isEmpty() ) {
        d->mailbox = Mailbox::find( d->sourceName );
        if ( !d->mailbox ) {
            log( "No such mailbox: " + d->sourceName.utf8(),
                 Log::Disaster );
            return;
        }
    }

    if ( !d->find ) {
        EStringList wanted;
        wanted.append( "message" );
        d->find = d->selector->query( 0, d->mailbox, 0, this,
                                      true, &wanted, false );
        d->find->execute();
    }

    if ( !d->find->done() )
        return;

    if ( !d->fetcher ) {
        d->messages = new List<Message>;
        while ( d->find->hasResults() ) {
            Row * r = d->find->nextRow();
            Message * m = new Message;
            m->setDatabaseId( r->getInt( "message" ) );
            d->messages->append( m );
        }
        d->fetcher = new Fetcher( d->messages, this, 0 );
        d->fetcher->fetch( Fetcher::Addresses );
        d->fetcher->fetch( Fetcher::OtherHeader );
        d->fetcher->fetch( Fetcher::Body );
        d->fetcher->fetch( Fetcher::Trivia );
        d->fetcher->execute();
    }

    while ( !d->messages->isEmpty() ) {
        Message * m = d->messages->firstElement();
        if ( !m->hasAddresses() )
            return;
        if ( !m->hasHeaders() )
            return;
        if ( !m->hasBodies() )
            return;
        if ( !m->hasTrivia() )
            return;
        d->messages->shift();
        EString from = "From ";
        Header * h = m->header();
        List<Address> * rp = 0;
        if ( h ) {
            rp = h->addresses( HeaderField::ReturnPath );
            if ( !rp )
                rp = h->addresses( HeaderField::Sender );
            if ( !rp )
                rp = h->addresses( HeaderField::From );
        }
        if ( rp )
            from.append( rp->firstElement()->lpdomain() );
        else
            from.append( "*****@*****.**" );
        from.append( "  " );
        Date id;
        if ( m->internalDate() )
            id.setUnixTime( m->internalDate() );
        else if ( m->header()->date() )
            id = *m->header()->date();
        // Tue Jul 23 19:39:23 2002
        from.append( weekdays[id.weekday()] );
        from.append( " " );
        from.append( months[id.month()-1] );
        from.append( " " );
        from.appendNumber( id.day() );
        from.append( " " );
        from.appendNumber( id.hour() );
        from.append( ":" );
        if ( id.minute() < 10 )
            from.append( "0" );
        from.appendNumber( id.minute() );
        from.append( ":" );
        if ( id.second() < 10 )
            from.append( "0" );
        from.appendNumber( id.second() );
        from.append( " " );
        from.appendNumber( id.year() );
        from.append( "\r\n" );
        EString rfc822 = m->rfc822();
        int r = ::write( 1, from.data(), from.length() ) +
                ::write( 1, rfc822.data(), rfc822.length() );
        // we don't really care whether the write succeeds or not, so
        // just fool the compiler.
        r = r;
    }

    EventLoop::global()->stop();
}
Exemplo n.º 19
0
void SieveCommand::parse( const EString & previous )
{
    if ( identifier().isEmpty() )
        setError( "Command name is empty" );

    bool test = false;
    bool blk = false;

    EString i = identifier();
    if ( i == "if" || i == "elsif" ) {
        test = true;
        blk = true;
        if ( i == "elsif" && previous != "if" && previous != "elsif" )
            setError( "elsif is only permitted after if/elsif" );
    }
    else if ( i == "else" ) {
        blk = true;
        if ( previous != "if" && previous != "elsif" )
            setError( "else is only permitted after if/elsif" );
    }
    else if ( i == "require" ) {
        arguments()->numberRemainingArguments();
        UStringList::Iterator i( arguments()->takeStringList( 1 ) );
        EStringList a;
        EStringList e;
        while ( i ) {
            if ( supportedExtensions()->contains( i->ascii() ) )
                a.append( i->ascii().quoted() );
            else
                e.append( i->ascii().quoted() );
            ++i;
        }
        if ( !e.isEmpty() )
            setError( "Each string must be a supported "
                      "sieve extension. "
                      "These are not: " + e.join( ", " ) );
        if ( !d->require )
            setError( "require is only permitted as the first command." );
        else if ( parent() )
            parent()->addExtensions( &a );
    }
    else if ( i == "stop" ) {
        // nothing needed
    }
    else if ( i == "reject" ) {
        require( "reject" );
        if ( arguments()->arguments()->isEmpty() ) {
            // we accept reject without reason
        }
        else {
            // if there is an argument, it must be a string
            arguments()->numberRemainingArguments();
            (void)arguments()->takeString( 1 );
        }
    }
    else if ( i == "ereject" ) {
        require( "reject" );
        arguments()->numberRemainingArguments();
        (void)arguments()->takeString( 1 );
    }
    else if ( i == "fileinto" ) {
        require( "fileinto" );
        if ( arguments()->findTag( ":copy" ) )
            require( "copy" );
        if ( arguments()->findTag( ":flags" ) ) {
            require( "imap4flags" );
            (void)arguments()->takeTaggedStringList( ":copy" );
        }
        arguments()->numberRemainingArguments();
        UString mailbox = arguments()->takeString( 1 );
        UString p;
        p.append( "/" );
        p.append( mailbox );

        if ( !Mailbox::validName( mailbox ) && !Mailbox::validName( p ) ) {
            setError( "Expected mailbox name, but got: " + mailbox.utf8() );
        }
        else if ( mailbox.startsWith( "INBOX." ) ) {
            // a sieve script which wants to reference a
            // mailbox called INBOX.X must use lower case
            // (inbox.x).
            UString aox =
                UStringList::split( '.', mailbox.mid( 6 ) )->join( "/" );
            setError( mailbox.utf8().quoted() +
                      " is Cyrus syntax. Archiveopteryx uses " +
                      aox.utf8().quoted() );
        }
    }
    else if ( i == "redirect" ) {
        (void)arguments()->findTag( ":copy" );
        arguments()->numberRemainingArguments();
        EString s = arguments()->takeString( 1 ).utf8();
        AddressParser ap( s );
        ap.assertSingleAddress();
        if ( !ap.error().isEmpty() )
            setError( "Expected one normal address (local@domain), but got: "
                      + s );
    }
    else if ( i == "keep" ) {
        // nothing needed
    }
    else if ( i == "discard" ) {
        // nothing needed
    }
    else if ( i == "vacation" ) {
        // vacation [":days" number] [":subject" string]
        //          [":from" string] [":addresses" string-list]
        //          [":mime"] [":handle" string] <reason: string>

        require( "vacation" );

        // :days
        uint days = 7;
        if ( arguments()->findTag( ":days" ) )
            days = arguments()->takeTaggedNumber( ":days" );
        if ( days < 1 || days > 365 )
            arguments()->tagError( ":days", "Number must be 1..365" );

        // :subject
        (void)arguments()->takeTaggedString( ":subject" );
        // anything is acceptable, right?

        // :from
        if ( arguments()->findTag( ":from" ) ) {
            parseAsAddress( arguments()->takeTaggedString( ":from" ),
                            ":from" );
            // XXX we don't enforce its being a local address.
        }

        // :addresses
        if ( arguments()->findTag( ":addresses" ) ) {
            UStringList * addresses
                = arguments()->takeTaggedStringList( ":addresses" );
            UStringList::Iterator i( addresses );
            while ( i ) {
                parseAsAddress( *i, ":addresses" );
                ++i;
            }
        }

        // :mime
        bool mime = false;
        if ( arguments()->findTag( ":mime" ) )
            mime = true;

        // :handle
        (void)arguments()->takeTaggedString( ":handle" );

        // reason
        arguments()->numberRemainingArguments();
        UString reason = arguments()->takeString( 1 );
        if ( mime ) {
            if ( !reason.isAscii() )
                setError( ":mime bodies must be all-ASCII, "
                          "8-bit text is not permitted" ); // so says the RFC
            EString x = reason.utf8();
            uint i = 0;
            Header * h = Message::parseHeader( i, x.length(),
                                               x, Header::Mime );
            Bodypart * bp = Bodypart::parseBodypart( i, x.length(),
                                                     x, h, 0 );
            if ( !h->error().isEmpty() )
                setError( "While parsing MIME header: " + h->error() );
            else if ( !bp->error().isEmpty() )
                setError( "While parsing MIME bodypart: " + bp->error() );

            List<HeaderField>::Iterator f( h->fields() );
            while ( f ) {
                if ( !f->name().startsWith( "Content-" ) )
                    setError( "Header field not permitted: " + f->name() );
                ++f;
            }

            if ( bp->children()->isEmpty() && bp->text().isEmpty() )
                setError( "Vacation reply does not contain any text" );
        }
        else {
            if ( reason.isEmpty() )
                setError( "Empty vacation text does not make sense" );
        }
    }
    else if ( i == "setflag" ||
              i == "addflags" ||
              i == "removeflag" ) {
        arguments()->numberRemainingArguments();
        (void)arguments()->takeStringList( 1 );
    }
    else if ( i == "notify" ) {
        require( "enotify" );
        UString from;
        if ( arguments()->findTag( ":from" ))
            from = arguments()->takeTaggedString( ":from" );

        UString importance;
        importance.append( "2" );
        if ( arguments()->findTag( ":importance" ) )
            importance = arguments()->takeTaggedString( ":from" );
        uint c = importance[0];
        if ( c < '1' || c > '3' )
            arguments()->tagError( ":importance",
                                   "Importance must be 1, 2 or 3" );

        UStringList * options;
        if ( arguments()->findTag( ":options" ) )
            options = arguments()->takeTaggedStringList( ":options" );

        UString message;
        if ( arguments()->findTag( ":message" ) )
            message = arguments()->takeTaggedString( ":message" );

        arguments()->numberRemainingArguments();
        UString method = arguments()->takeString( 1 );

        SieveNotifyMethod * m
            = new SieveNotifyMethod( method,
                                     arguments()->takeArgument( 1 ),
                                     this );

        if ( m->valid() ) {
            if ( arguments()->findTag( ":from" ) )
                m->setFrom( from, arguments()->findTag( ":from" ) );
            if ( arguments()->findTag( ":message" ) )
                m->setMessage( message, arguments()->findTag( ":message" ) );
        }
    }
    else {
        setError( "Command unknown: " + identifier() );
    }

    arguments()->flagUnparsedAsBad();

    if ( test ) {
        // we must have a test
        if ( !arguments() || arguments()->tests()->count() != 1 )
            setError( "Command " + identifier() + " requires one test" );
        if ( arguments() ) {
            List<SieveTest>::Iterator i( arguments()->tests() );
            while ( i ) {
                i->parse();
                if ( blk && block() ) {
                    if ( i->ihaveFailed() )
                        block()->setIhaveFailed();
                    else
                        block()->addExtensions( i->addedExtensions() );
                }
                ++i;
            }
        }
    }
    else {
        // we cannot have a test
        if ( arguments() && arguments()->tests()->isEmpty() ) {
            List<SieveTest>::Iterator i( arguments()->tests() );
            while ( i ) {
                i->setError( "Command " + identifier() +
                             " does not use tests" );
                ++i;
            }
        }
    }

    if ( blk ) {
        // we must have a subsidiary block
        if ( !block() ) {
            setError( "Command " + identifier() +
                      " requires a subsidiary {..} block" );
        }
        else {
            EString prev;
            List<SieveCommand>::Iterator i( block()->commands() );
            while ( i ) {
                i->parse( prev );
                prev = i->identifier();
                ++i;
            }
        }
    }
    else {
        // we cannot have a subsidiary block
        if ( block() )
            block()->setError( "Command " + identifier() +
                               " does not use a subsidiary command block" );
        // in this case we don't even bother syntax-checking the test
        // or block
    }
}
Exemplo n.º 20
0
bool isSUVI(const Header& header)
{
	return header.has("INSTRUME") && header.get<string>("INSTRUME").find("GOES-R") != string::npos;
}
Exemplo n.º 21
0
Frame *FrameFactory::createFrame(const ByteVector &data, unsigned int version) const
{
  Header tagHeader;
  tagHeader.setMajorVersion(version);
  return createFrame(data, &tagHeader);
}
Exemplo n.º 22
0
void run ()
{
  auto amp = Image<value_type>::open (argument[0]).with_direct_io (3);
  Header header (amp);

  std::vector<size_t> bzeros, dwis;
  Eigen::MatrixXd dirs;
  auto opt = get_options ("directions");
  if (opt.size()) {
    dirs = load_matrix (opt[0][0]);
  } 
  else {
    auto hit = header.keyval().find ("directions");
    if (hit != header.keyval().end()) {
      std::vector<default_type> dir_vector;
      for (auto line : split_lines (hit->second)) {
        auto v = parse_floats (line);
        dir_vector.insert (dir_vector.end(), v.begin(), v.end());
      }
      dirs.resize(dir_vector.size() / 2, 2);
      for (size_t i = 0; i < dir_vector.size(); i += 2) {
        dirs(i/2, 0) = dir_vector[i];
        dirs(i/2, 1) = dir_vector[i+1];
      }
    } 
    else {
      auto grad = DWI::get_valid_DW_scheme (amp);
      DWI::Shells shells (grad);
      shells.select_shells (true, true);
      if (shells.smallest().is_bzero())
        bzeros = shells.smallest().get_volumes();
      dwis = shells.largest().get_volumes();
      dirs = DWI::gen_direction_matrix (grad, dwis);
    }
  }

  auto sh2amp = DWI::compute_SH2amp_mapping (dirs, true, 8);


  bool normalise = get_options ("normalise").size();
  if (normalise && !bzeros.size())
    throw Exception ("the normalise option is only available if the input data contains b=0 images.");


  header.size (3) = sh2amp.cols();
  Stride::set_from_command_line (header);
  auto SH = Image<value_type>::create (argument[1], header);

  Amp2SHCommon common (sh2amp, bzeros, dwis, normalise);

  opt = get_options ("rician");
  if (opt.size()) {
    auto noise = Image<value_type>::open (opt[0][0]).with_direct_io();
    ThreadedLoop ("mapping amplitudes to SH coefficients", amp, 0, 3)
      .run (Amp2SH (common), SH, amp, noise);
  }
  else {
    ThreadedLoop ("mapping amplitudes to SH coefficients", amp, 0, 3)
      .run (Amp2SH (common), SH, amp);
  }
}
Exemplo n.º 23
0
 static void bsToHeader(Header& param, BitWriter& bs)
 {
     ASSERT(BIT_WRITER_BIT_SIZE (&bs) % 8 == 0);
     param.insert(param.end(), BIT_WRITER_DATA (&bs),  BIT_WRITER_DATA (&bs) + BIT_WRITER_BIT_SIZE (&bs)/8);
 }
Exemplo n.º 24
0
result
CreateProfileForm::OnInitializing(void)
{
	result r = E_SUCCESS;

	Header* pHeader = GetHeader();
	AppAssert(pHeader);
	pHeader->SetStyle(HEADER_STYLE_TITLE);
	String getProfileCreationTitle;
	Application::GetInstance()->GetAppResource()->GetString(IDS_CREATE_TITLE, getProfileCreationTitle);
	pHeader->SetTitleText(getProfileCreationTitle);

	Footer* pFooter = GetFooter();
	AppAssert(pFooter);
	pFooter->SetStyle(FOOTER_STYLE_BUTTON_TEXT);

	FooterItem footerSave;
	footerSave.Construct(ID_BUTTON_SAVE);
	String getSave;
	Application::GetInstance()->GetAppResource()->GetString(IDS_SAVE, getSave);
	footerSave.SetText(getSave);
	pFooter->AddItem(footerSave);
	pFooter->AddActionEventListener(*this);

	SetFormBackEventListener(this);

	static const unsigned int COLOR_BACKGROUND_LABEL = 0xFFEFEDE5;
	static const unsigned int COLOR_TITLE_LABEL = 0xFF808080;

	static const int UI_X_POSITION_GAP = 20;
	static const int UI_WIDTH = GetClientAreaBounds().width - 40;
	static const int UI_X_POSITION_MIDDLE = UI_WIDTH / 4;
	static const int UI_HEIGHT = 112;
	static const int UI_SPACE = 26;
	int yPosition = 0;

	__pScrollPanel = new (std::nothrow) ScrollPanel();
	__pScrollPanel->Construct(Rectangle(0, 0, GetClientAreaBounds().width, GetClientAreaBounds().height));

	// Subject
	__pSubjectEditField = new (std::nothrow) EditField();
	__pSubjectEditField->Construct(Rectangle(UI_X_POSITION_GAP, yPosition, UI_WIDTH, UI_HEIGHT), EDIT_FIELD_STYLE_NORMAL, INPUT_STYLE_FULLSCREEN, EDIT_FIELD_TITLE_STYLE_TOP);
	String getProfileName, getProfileNameGuid;
	Application::GetInstance()->GetAppResource()->GetString(IDS_PROFILE_NAME, getProfileName);
	Application::GetInstance()->GetAppResource()->GetString(IDS_PROFILE_GUIDE, getProfileNameGuid);
	__pSubjectEditField->SetGuideText(getProfileNameGuid);
	__pSubjectEditField->SetName(L"Subject");
	__pSubjectEditField->SetTitleText(getProfileName);
	__pSubjectEditField->SetOverlayKeypadCommandButtonVisible(false);
	__pScrollPanel->AddControl(__pSubjectEditField);

	// Start Date
	int minYear = Calendarbook::GetMinDateTime().GetYear() + 1;
	int maxYear = Calendarbook::GetMaxDateTime().GetYear() - 1;

	Label* pStartDateLabel = new (std::nothrow) Label();
	String getStartDateTime, getEndDateTime;
	Application::GetInstance()->GetAppResource()->GetString(IDS_START_DATETIME, getStartDateTime);
	Application::GetInstance()->GetAppResource()->GetString(IDS_END_DATETIME, getEndDateTime);
	pStartDateLabel->Construct(Rectangle(UI_X_POSITION_GAP, yPosition += UI_HEIGHT + UI_SPACE, UI_WIDTH, UI_HEIGHT), getStartDateTime);
	pStartDateLabel->SetTextVerticalAlignment(ALIGNMENT_TOP);
	pStartDateLabel->SetTextHorizontalAlignment(ALIGNMENT_LEFT);
	pStartDateLabel->SetTextColor(COLOR_TITLE_LABEL);
	pStartDateLabel->SetBackgroundColor(COLOR_BACKGROUND_LABEL);
	__pScrollPanel->AddControl(pStartDateLabel);

	__pStartEditDate = new (std::nothrow) EditDate();
	__pStartEditDate->Construct(Point(UI_X_POSITION_GAP, yPosition + 10));
	__pStartEditDate->SetCurrentDate();
	__pStartEditDate->SetYearRange(minYear, maxYear);
	__pStartEditDate->AddDateChangeEventListener(*this);
	__pScrollPanel->AddControl(__pStartEditDate);

	__pStartEditTime = new (std::nothrow) EditTime();
	__pStartEditTime->Construct(Point(UI_X_POSITION_MIDDLE * 2 + UI_SPACE, yPosition + 10));
	__pStartEditTime->SetCurrentTime();
	__pStartEditTime->AddTimeChangeEventListener(*this);
	__pScrollPanel->AddControl(__pStartEditTime);

	// Due Date
	Label* pDueDateLabel = new (std::nothrow) Label();
	pDueDateLabel->Construct(Rectangle(UI_X_POSITION_GAP, yPosition += UI_HEIGHT, UI_WIDTH, UI_HEIGHT), getEndDateTime);
	pDueDateLabel->SetTextVerticalAlignment(ALIGNMENT_TOP);
	pDueDateLabel->SetTextHorizontalAlignment(ALIGNMENT_LEFT);
	pDueDateLabel->SetTextColor(COLOR_TITLE_LABEL);
	pDueDateLabel->SetBackgroundColor(COLOR_BACKGROUND_LABEL);
	__pScrollPanel->AddControl(pDueDateLabel);

	__pDueEditDate = new (std::nothrow) EditDate();
	__pDueEditDate->Construct(Point(UI_X_POSITION_GAP, yPosition + 10));
	__pDueEditDate->SetCurrentDate();
	__pDueEditDate->SetYearRange(minYear, maxYear);
	__pDueEditDate->AddDateChangeEventListener(*this);
	__pScrollPanel->AddControl(__pDueEditDate);

	DateTime endTime;
	endTime = __pStartEditTime->GetTime();
	endTime.AddHours(1);

	__pDueEditTime = new (std::nothrow) EditTime();
	__pDueEditTime->Construct(Point(UI_X_POSITION_MIDDLE * 2 + UI_SPACE, yPosition + 10));
	__pDueEditTime->SetTime(endTime);
	__pDueEditTime->AddTimeChangeEventListener(*this);
	__pScrollPanel->AddControl(__pDueEditTime);

	// Location
	String  getLocationGuide;
	Application::GetInstance()->GetAppResource()->GetString(IDS_LOCATION_GUIDE, getLocationGuide);

	__pLocationButton = new (std::nothrow) Button();
	__pLocationButton->Construct(Rectangle(UI_X_POSITION_GAP, yPosition += UI_HEIGHT + UI_SPACE, UI_WIDTH, UI_HEIGHT), getLocationGuide);
	__pLocationButton->SetActionId(ID_LOCATION_BUTTON);
	__pLocationButton->AddActionEventListener(*this);
	__pScrollPanel->AddControl(__pLocationButton);

	// Volume
	String getVolume;
	Application::GetInstance()->GetAppResource()->GetString(IDS_VOLUME, getVolume);
	__pVolumeSlider = new (std::nothrow) Slider();
	__pVolumeSlider->Construct(Rectangle(UI_X_POSITION_GAP, yPosition += UI_HEIGHT + UI_SPACE, UI_WIDTH/*GetClientAreaBounds().width*/, UI_HEIGHT + 30), BACKGROUND_STYLE_DEFAULT, true, 0, 15);
	__pVolumeSlider->SetValue(5);
	__pVolumeSlider->SetTitleText(getVolume);
	__pVolumeSlider->AddAdjustmentEventListener(*this);
	__pScrollPanel->AddControl(__pVolumeSlider);

	// Wifi
	String getWifi;
	Application::GetInstance()->GetAppResource()->GetString(IDS_WIFI, getWifi);
	__pWifiCheckButton = new (std::nothrow) CheckButton();
	__pWifiCheckButton->Construct(Rectangle(UI_X_POSITION_GAP, yPosition += UI_HEIGHT + UI_SPACE, UI_WIDTH, UI_HEIGHT),
			CHECK_BUTTON_STYLE_ONOFF_SLIDING, BACKGROUND_STYLE_DEFAULT, false, getWifi);
	__pWifiCheckButton->SetActionId(ID_BUTTON_CHECKED, ID_BUTTON_UNCHECKED, ID_BUTTON_SELECTED);
	__pWifiCheckButton->AddActionEventListener(*this);
	__pScrollPanel->AddControl(__pWifiCheckButton);

	// Description
	String getDescription, getDescriptionGuide;
	Application::GetInstance()->GetAppResource()->GetString(IDS_DESCRIPTION, getDescription);
	Application::GetInstance()->GetAppResource()->GetString(IDS_DESCRIPTION_GUIDE, getDescriptionGuide);
	__pDescriptionEditField = new (std::nothrow) EditField();
	__pDescriptionEditField->Construct(Rectangle(UI_X_POSITION_GAP, yPosition += UI_HEIGHT + UI_SPACE, UI_WIDTH, UI_HEIGHT), EDIT_FIELD_STYLE_NORMAL, INPUT_STYLE_FULLSCREEN, EDIT_FIELD_TITLE_STYLE_TOP);
	__pDescriptionEditField->SetGuideText(getDescriptionGuide);
	__pDescriptionEditField->SetName(L"Description");
	__pDescriptionEditField->SetTitleText(getDescription);
	__pDescriptionEditField->SetOverlayKeypadCommandButtonVisible(false);
	__pScrollPanel->AddControl(__pDescriptionEditField);

	AddControl(__pScrollPanel);

	return r;
}
Exemplo n.º 25
0
result
ProfileListForm::OnInitializing(void)
{
	result r = E_SUCCESS;

	Header* pHeader = GetHeader();
	AppAssert(pHeader);
	pHeader->SetStyle(HEADER_STYLE_TITLE);
	String getHeaderTitle;
	Application::GetInstance()->GetAppResource()->GetString(IDS_HEADER_TITLE, getHeaderTitle);
	pHeader->SetTitleText(getHeaderTitle);

	Footer* pFooter = GetFooter();
	AppAssert(pFooter);
	pFooter->SetStyle(FOOTER_STYLE_BUTTON_TEXT);

	FooterItem footerCreate;
	footerCreate.Construct(ID_FOOTER_CREATE);
	String getFooterCreate;
	UiApp::GetInstance()->GetAppResource()->GetString(IDS_FOOTER_CREATE, getFooterCreate);
	footerCreate.SetText(getFooterCreate);
	pFooter->AddItem(footerCreate);
	pFooter->AddActionEventListener(*this);

	SetFormBackEventListener(this);

	String sql (L"CREATE TABLE IF NOT EXISTS profile(id INTEGER PRIMARY KEY, "
			"title TEXT, "
			"year INTEGER, month INTEGER, day INTEGER, hour INTEGER, minute INTEGER, "
			"year2 INTEGER, month2 INTEGER, day2 INTEGER, hour2 INTEGER, minute2 INTEGER, "
			"latitude INTEGER, longitude INTEGER, volume INTEGER, wifi INTEGER, memo TEXT)");
	__pProfileDatabase->ExecuteSql(sql, true);
    __pTitleList.RemoveAll(true);
    __pIndexList.RemoveAll(true);

//    static const int UI_POSITION_GAP = 0;

//	__pStatusContextButton = new (std::nothrow) Button();
//	__pStatusContextButton->Construct(Rectangle(GetClientAreaBounds().width * 2 / 3, UI_POSITION_GAP, GetClientAreaBounds().width / 3, BUTTON_HEIGHT), L"All");
//	__pStatusContextButton->SetActionId(ID_BUTTON_STATUS);
//	__pStatusContextButton->AddActionEventListener(*this);
//	AddControl(__pStatusContextButton);
//
//	__pStatusContextMenu = new (std::nothrow) ContextMenu();
//	__pStatusContextMenu->Construct(Point(GetClientAreaBounds().width * 5 / 6, BUTTON_HEIGHT * 3), CONTEXT_MENU_STYLE_LIST);
//	__pStatusContextMenu->AddItem(L"All", ID_CONTEXT_STATUS_ALL);
//	__pStatusContextMenu->AddItem(L"None", ID_CONTEXT_STATUS_NONE);
//	__pStatusContextMenu->AddItem(L"Needs action", ID_CONTEXT_STATUS_NEEDS_ACTION);
//	__pStatusContextMenu->AddItem(L"Completed", ID_CONTEXT_STATUS_COMPLETED);
//	__pStatusContextMenu->AddItem(L"In process", ID_CONTEXT_STATUS_IN_PROCESS);
//	__pStatusContextMenu->AddItem(L"Cancelled", ID_CONTEXT_STATUS_CANCELLED);
//	__pStatusContextMenu->AddActionEventListener(*this);

	__pProfileListView = new (std::nothrow) ListView();
	__pProfileListView->Construct(Rectangle(0 /*UI_POSITION_GAP*/, 0/*BUTTON_HEIGHT*/, GetClientAreaBounds().width, GetClientAreaBounds().height /*- BUTTON_HEIGHT*/));
	String getNoList;
	Application::GetInstance()->GetAppResource()->GetString(IDS_EMPTY_LIST, getNoList);
	__pProfileListView->SetTextOfEmptyList(getNoList);
	__pProfileListView->SetItemProvider(*this);
	__pProfileListView->AddListViewItemEventListener(*this);
	__pProfileListView->SetSweepEnabled(true);

	AddControl(__pProfileListView);
	//(*this);
	SettingInfo::AddSettingEventListener(*this);

	ListUpdate();

//	__selectedStatus = TODO_STATUS_ALL;

	return r;
}
Exemplo n.º 26
0
int main(int argc, char **argv) {
	int c;
	char *inputFile=NULL, *insertFile=NULL, *removeFile=NULL, *outputFile=NULL;
	char *insertSubject=NULL, *insertPredicate=NULL, *insertObject=NULL;
	char *removeSubject=NULL, *removePredicate=NULL, *removeObject=NULL;
	bool insertSingle = false;
	bool removeSingle = false;

	bool insertMultiple = false;
	bool removeMultiple = false;

	while ((c = getopt(argc, argv, "hO:i:r:I:R:")) != -1) {
		switch (c) {
		case 'h':
			help();
			break;
		case 'O':
			outputFile = optarg;
			break;
		case 'i':
			insertSingle = true;
			insertSubject = optarg;
			insertPredicate = argv[optind++];
			insertObject = argv[optind++];
			break;
		case 'r':
			removeSingle = true;
			removeSubject = optarg;
			removePredicate = argv[optind++];
			removeObject = argv[optind++];
			break;
		case 'I':
			insertMultiple = true;
			insertFile = optarg;
			break;
		case 'R':
			removeMultiple = true;
			removeFile = optarg;
			break;
		default:
			cout << "ERROR: Unknown option" << endl;
			help();
			return 1;
		}
	}

	if (argc - optind < 2) {
		cout << "ERROR: You must supply an input and output HDT File" << endl << endl;
		help();
		return 1;
	}
	inputFile = argv[optind];
	outputFile = argv[optind+1];
	if (strcmp(inputFile,outputFile)==0){
		cerr<< "ERROR: input and output files must me different" << endl <<endl;
		return 1;
	}

	try {
		// LOAD
		HDT *hdt = HDTManager::mapHDT(inputFile);

		// Replace header
		Header *head = hdt->getHeader();

		if (insertSingle) {
			TripleString ti(insertSubject, insertPredicate, insertObject);
			head->insert(ti);
		}
		if (removeSingle) {
			TripleString ti(removeSubject, removePredicate, removeObject);
			head->remove(ti);
		}
		if (insertMultiple) {
			string line;
			std::ifstream infile(insertFile);
			while (getline(infile, line)) {
				TripleString ti;
				ti.read(line);
				head->insert(ti);
			}
		}
		if (removeMultiple) {
			string line;
			std::ifstream infile(removeFile);
			while (getline(infile, line)) {
				TripleString ti;
				ti.read(line);
				head->remove(ti);
			}
		}
		// SAVE
		hdt->saveToHDT(outputFile);

		delete hdt;
	} catch (std::exception& e) {
		cerr << "ERROR: " << e.what() << endl;
		return 1;
	}
}
Exemplo n.º 27
0
 void clear_DW_scheme (Header& header)
 {
   auto it = header.keyval().find ("dw_scheme");
   if (it != header.keyval().end())
     header.keyval().erase (it);
 }
Exemplo n.º 28
0
////////////////////////////////////////////////////////////////////////////////////
///
///   \brief Writes message contents to packet for the transport layer to
///          send.  Begins writing from current write position in packet.
///
///   Message contents are written to the packet following the JAUS standard.
///
///   \param[out] packet Packet to write header and payload data to.
///   \param[out] header Packet transport header data.
///   \param[in] transportHeader Optional parameter for transport header data to
///                              write before the general transport header.
///   \param[in] clearPacket If true, packet contents are cleared before
///                          writing takes place.
///   \param[in] startingSequenceNumber Sequence number to use for packets.
///   \param[in] broadcastFlag Values to use to signify if message should be
///                            sent using any broadcast options (e.g. 
///                            multicast). 0 = no options, 1 = local broadcast,
///                            2 = global broadcast.
///
///   \return FAILURE on error, otherwise number of bytes written.
///
////////////////////////////////////////////////////////////////////////////////////
int Message::Write(Packet& packet, 
                   Header& header,
                   const Packet* transportHeader, 
                   const bool clearPacket,
                   const UShort startingSequenceNumber,
                   const Byte broadcastFlag) const
{
    int total = 0;
    //  Build JAUS header data.
    header.mSourceID = mSourceID;
    header.mDestinationID = mDestinationID;
    header.mPriorityFlag = mPriority;
    header.mControlFlag = Header::DataControl::Single;
    header.mCompressionFlag = Header::Compression::None;
    header.mSequenceNumber = startingSequenceNumber;
    header.mBroadcastFlag = broadcastFlag;

    //  Clear out any previous message data.
    if(clearPacket)
    {
        packet.Clear();
        packet.Reserve(Header::MinSize + USHORT_SIZE + 1);
    }
    unsigned int writePos = packet.GetWritePos();
    
    if(transportHeader && transportHeader->Length() > 0)
    {
        writePos += (unsigned int)packet.Write(*transportHeader);
    }
    //  The first thing we must do is advance
    //  the write position to after the JAUS Header
    //  data.  The header is not written first because
    //  we do not know how large the message body will
    //  be yet.
    packet.SetLength(writePos + Header::PayloadOffset);
    packet.SetWritePos(writePos + Header::PayloadOffset);
    total += packet.Write(mMessageCode);
    int payloadSize = 0;
    if( (payloadSize = WriteMessageBody(packet)) >= 0)
    {
        total += payloadSize;
        // Check for large data set.
        if(total + Header::MinSize > Header::MaxPacketSize)
        {
            return FAILURE;
        }
        else
        {
            header.mSize = total + Header::MinSize;
            packet.SetWritePos(writePos);
            // Go back, and re-write the header since 
            // we now know the size of the message.
            if(header.Write(packet))
            {
                // Set the write position to the end of message we just wrote.
                packet.SetWritePos(writePos + header.mSize);
                //  Return the number of bytes written.
                if(transportHeader)
                {
                    return header.mSize + transportHeader->Length();
                }
                else
                {
                    return header.mSize;
                }
            }
        }
    }

    return FAILURE;
}
Exemplo n.º 29
0
oc::result<void> SonyElfFormatWriter::write_header(File &file,
                                                   const Header &header)
{
    m_cmdline.clear();

    m_hdr = {};
    m_hdr_kernel = {};
    m_hdr_ramdisk = {};
    m_hdr_cmdline = {};
    m_hdr_ipl = {};
    m_hdr_rpm = {};
    m_hdr_appsbl = {};

    // Construct ELF header
    memcpy(&m_hdr.e_ident, SONY_E_IDENT, SONY_EI_NIDENT);
    m_hdr.e_type = 2;
    m_hdr.e_machine = 40;
    m_hdr.e_version = 1;
    m_hdr.e_phoff = 52;
    m_hdr.e_shoff = 0;
    m_hdr.e_flags = 0;
    m_hdr.e_ehsize = sizeof(Sony_Elf32_Ehdr);
    m_hdr.e_phentsize = sizeof(Sony_Elf32_Phdr);
    m_hdr.e_shentsize = 0;
    m_hdr.e_shnum = 0;
    m_hdr.e_shstrndx = 0;

    if (auto entrypoint_address = header.entrypoint_address()) {
        m_hdr.e_entry = *entrypoint_address;
    } else if (auto kernel_address = header.kernel_address()) {
        m_hdr.e_entry = *kernel_address;
    }

    // Construct kernel program header
    m_hdr_kernel.p_type = SONY_E_TYPE_KERNEL;
    m_hdr_kernel.p_flags = SONY_E_FLAGS_KERNEL;
    m_hdr_kernel.p_align = 0;

    if (auto address = header.kernel_address()) {
        m_hdr_kernel.p_vaddr = *address;
        m_hdr_kernel.p_paddr = *address;
    }

    // Construct ramdisk program header
    m_hdr_ramdisk.p_type = SONY_E_TYPE_RAMDISK;
    m_hdr_ramdisk.p_flags = SONY_E_FLAGS_RAMDISK;
    m_hdr_ramdisk.p_align = 0;

    if (auto address = header.ramdisk_address()) {
        m_hdr_ramdisk.p_vaddr = *address;
        m_hdr_ramdisk.p_paddr = *address;
    }

    // Construct cmdline program header
    m_hdr_cmdline.p_type = SONY_E_TYPE_CMDLINE;
    m_hdr_cmdline.p_vaddr = 0;
    m_hdr_cmdline.p_paddr = 0;
    m_hdr_cmdline.p_flags = SONY_E_FLAGS_CMDLINE;
    m_hdr_cmdline.p_align = 0;

    if (auto cmdline = header.kernel_cmdline()) {
        m_cmdline = *cmdline;
    }

    // Construct IPL program header
    m_hdr_ipl.p_type = SONY_E_TYPE_IPL;
    m_hdr_ipl.p_flags = SONY_E_FLAGS_IPL;
    m_hdr_ipl.p_align = 0;

    if (auto address = header.sony_ipl_address()) {
        m_hdr_ipl.p_vaddr = *address;
        m_hdr_ipl.p_paddr = *address;
    }

    // Construct RPM program header
    m_hdr_rpm.p_type = SONY_E_TYPE_RPM;
    m_hdr_rpm.p_flags = SONY_E_FLAGS_RPM;
    m_hdr_rpm.p_align = 0;

    if (auto address = header.sony_rpm_address()) {
        m_hdr_rpm.p_vaddr = *address;
        m_hdr_rpm.p_paddr = *address;
    }

    // Construct APPSBL program header
    m_hdr_appsbl.p_type = SONY_E_TYPE_APPSBL;
    m_hdr_appsbl.p_flags = SONY_E_FLAGS_APPSBL;
    m_hdr_appsbl.p_align = 0;

    if (auto address = header.sony_appsbl_address()) {
        m_hdr_appsbl.p_vaddr = *address;
        m_hdr_appsbl.p_paddr = *address;
    }

    std::vector<SegmentWriterEntry> entries;

    entries.push_back({ ENTRY_TYPE_KERNEL, 0, {}, 0 });
    entries.push_back({ ENTRY_TYPE_RAMDISK, 0, {}, 0 });
    entries.push_back({ SONY_ELF_ENTRY_CMDLINE, 0, {}, 0 });
    entries.push_back({ ENTRY_TYPE_SONY_IPL, 0, {}, 0 });
    entries.push_back({ ENTRY_TYPE_SONY_RPM, 0, {}, 0 });
    entries.push_back({ ENTRY_TYPE_SONY_APPSBL, 0, {}, 0 });

    OUTCOME_TRYV(m_seg->set_entries(std::move(entries)));

    // Start writing at offset 4096
    auto seek_ret = file.seek(4096, SEEK_SET);
    if (!seek_ret) {
        if (file.is_fatal()) { m_writer.set_fatal(); }
        return seek_ret.as_failure();
    }

    return oc::success();
}
Exemplo n.º 30
0
/*!
 * \brief Read header for new-style Loki image
 *
 * \param[in] reader Reader to set error message
 * \param[in] file File handle
 * \param[in] hdr Android header for image
 * \param[in] loki_hdr Loki header for image
 * \param[out] header Header instance to store header values
 * \param[out] kernel_offset_out Pointer to store kernel offset
 * \param[out] kernel_size_out Pointer to store kernel size
 * \param[out] ramdisk_offset_out Pointer to store ramdisk offset
 * \param[out] ramdisk_size_out Pointer to store ramdisk size
 * \param[out] dt_offset_out Pointer to store device tree offset
 *
 * \return Nothing if the header is successfully read. Otherwise, a specific
 *         error code.
 */
oc::result<void>
LokiFormatReader::read_header_new(Reader &reader, File &file,
                                  const android::AndroidHeader &hdr,
                                  const LokiHeader &loki_hdr,
                                  Header &header,
                                  uint64_t &kernel_offset_out,
                                  uint32_t &kernel_size_out,
                                  uint64_t &ramdisk_offset_out,
                                  uint32_t &ramdisk_size_out,
                                  uint64_t &dt_offset_out)
{
    uint32_t fake_size;
    uint32_t ramdisk_addr;

    if (hdr.page_size == 0) {
        return LokiError::PageSizeCannotBeZero;
    }

    if (is_lg_ramdisk_address(hdr.ramdisk_addr)) {
        fake_size = hdr.page_size;
    } else {
        fake_size = 0x200;
    }

    // Find original ramdisk address
    OUTCOME_TRYV(find_ramdisk_address(reader, file, hdr, loki_hdr,
                                      ramdisk_addr));

    // Restore original values in boot image header
    kernel_size_out = loki_hdr.orig_kernel_size;
    ramdisk_size_out = loki_hdr.orig_ramdisk_size;

    auto *name_ptr = reinterpret_cast<const char *>(hdr.name);
    auto name_size = strnlen(name_ptr, sizeof(hdr.name));

    auto *cmdline_ptr = reinterpret_cast<const char *>(hdr.cmdline);
    auto cmdline_size = strnlen(cmdline_ptr, sizeof(hdr.cmdline));

    header.set_supported_fields(NEW_SUPPORTED_FIELDS);
    header.set_board_name({{name_ptr, name_size}});
    header.set_kernel_cmdline({{cmdline_ptr, cmdline_size}});
    header.set_page_size(hdr.page_size);
    header.set_kernel_address(hdr.kernel_addr);
    header.set_ramdisk_address(ramdisk_addr);
    header.set_secondboot_address(hdr.second_addr);
    header.set_kernel_tags_address(hdr.tags_addr);

    uint64_t pos = 0;

    // pos cannot overflow due to the nature of the operands (adding UINT32_MAX
    // a few times can't overflow a uint64_t). File length overflow is checked
    // during read.

    // Header
    pos += hdr.page_size;

    // Kernel
    kernel_offset_out = pos;
    pos += loki_hdr.orig_kernel_size;
    pos += align_page_size<uint64_t>(pos, hdr.page_size);

    // Ramdisk
    ramdisk_offset_out = pos;
    pos += loki_hdr.orig_ramdisk_size;
    pos += align_page_size<uint64_t>(pos, hdr.page_size);

    // Device tree
    if (hdr.dt_size != 0) {
        pos += fake_size;
    }
    dt_offset_out = pos;
    pos += hdr.dt_size;
    pos += align_page_size<uint64_t>(pos, hdr.page_size);

    return oc::success();
}