static void DebugLog (const char* str)
{
    if (debugLog)
        debugLog(str);
}
Exemplo n.º 2
0
uint8_t txChar(int data, int channel) {
  uint8_t x;
  uint8_t parity_bit = 0;
  uint16_t tx_timeout;

  /*
   * Clear errors from previous transmissions.
   */
  tx_parity_error = FALSE;

  /*
   * Let neighbor know you want to talk to it.
   * Then wait for an acknowledgement.  Timeout
   * if necessary.
   */
  //these 3 lines take about 7 us
  setDataLine(channel, 1); //to avoid capacitive noise from clock line
  setClockLine(channel, 0);
  releaseDataLine(channel); // allow neighbor to respond

  tx_timeout = (TX_WAIT_FOR_NEIGHBOR_RELOAD + handshake_retry_addition);

  while(pollDataLine(channel)) {
    tx_timeout--;
    if(tx_timeout == 0) {
      // Communication timed out... no one listening on this channel.
      // This counts as an unsuccessful transmission.
      releaseClockLine(channel); // Set clock line back to an input.
      return FALSE;
    }
  }



  /*
   * Once acknowledged, wait for the receiving neighbor to
   * relinquish control of the data line, then assert control
   * over both clock and data.
   */
  tx_timeout = TX_TIMEOUT_RELOAD;
  while(!pollDataLine(channel)) {
    tx_timeout--;
    if(tx_timeout == 0) {
      // Communication timed out... no one listening on this channel.
      // This counts as an unsuccessful transmission.
      releaseClockLine(channel); // Set clock line back to an input.
      //if (goodChannels & (0x01 << (channel - 1))) {  // if the current channel is good, then...
      //blinkGreen(1);  // meme
      //blinkRed(1);
      //}
      //      debugLog(RECEIVER_DIDNT_RELEASE_CLOCK_LINE);
      return FALSE;
    }
  }
  setClockLine(channel, 1);
  setDataLine(channel, 1);

  sei();

  /*
   * Both parties are agreed on who is sending and who is receiving,
   * so start transmission of the byte, bit by bit.
   */
  for(x = 0; x < 8; x++) {
    /*
     * Send out the LSB.
     */
    setDataLine(channel, (data & 0x01));
    setClockLine(channel, 0);
	
    /*
     * Give the receiver time to process the outgoing bit.
     */
    delay_us(BIT_LOW_TIME);
	
    /*
     * Modify the parity bit to reflect the bit just sent and
     * prepare the data to send the next bit.
     */
    parity_bit ^= (data & 0x01);
    data >>= 1;
	
    /*
     * Return communication channel to idle state to let
     * the receiver know that a new bit is coming.
     */
    setClockLine(channel, 1);
    setDataLine(channel, 1);
    delay_us(BIT_HIGH_TIME);
  }

  /*
   * Send parity bit for error detection.
   */
  setDataLine(channel, parity_bit);
  setClockLine(channel, 0);
  delay_us(BIT_LOW_TIME);
  releaseDataLine(channel);

  //just testing here...
  //trying to drive the line high so it doesn't get accidentally driven low after release
  //under normal operations, the receiver doesn't try to control this line until 8-10 us after it's released.
  //delay_us(4);

  releaseClockLine(channel);
  /*
   * Wait for the receiver to acknowledge receipt of the byte just sent.
   * Timeout if necessary, indicating a bad transmission.
   * waiting for receiver to indicate that parity bit was received properly.
   */
  tx_timeout = TX_TIMEOUT_RELOAD;
  while(pollDataLine(channel)) { 	//avr samples about 9 times here, at 5 us intervals
    tx_timeout--;
    if(tx_timeout == 0) {
      //if (goodChannels & (0x01 << (channel - 1))) {  // if the current channel is good, then...
      //blinkGreen(1);  // meme
      //blinkRed(1);
      //}
      debugLog(NO_BYTE_TX_RECEIPT); //RECEIVER DIDN'T ACKNOWLEDGE PARTIY BIT
      return FALSE;
    }
  }
  /*
   * Check if the byte was correctly received.
   * clock line should be high. if it's low, there
   * was a parity error.
   */
  tx_parity_error = !pollClockLine(channel);
  /*
   * Wait for receiver to finish acknowledging receipt of the byte just
   * sent.  Timeout if necessary, indicating a bad transmission.
   * waiting for receiver to release the data line so that normal
   * transmissions can continue.
   */
  tx_timeout = TX_TIMEOUT_RELOAD;
  while(!pollDataLine(channel)) {
    tx_timeout--;
    if(tx_timeout == 0) {
      //if (goodChannels & (0x01 << (channel - 1))) {  // if the current channel is good, then...
      //blinkGreen(1);  // meme
      //blinkRed(1);
      //}
      debugLog(TX_PARITY_ERROR_TIMEOUT); //receiver didn't release data line after parity bit
      return FALSE;
    }
  }
  debugLog(SUCCESSFUL_TX);

  good_channels |= _BV(channel - 1); // Mark this channel as good.
  return TRUE;
}
Exemplo n.º 3
0
void PathFinding::molestPath(VectorPath &path)
{
	int sz=path.getNumPathNodes();
	if(!sz)
		return;

	int i = 0;
	// make normals
	std::vector<Vector> normals;
	normals.resize(sz);
	for (i = 0; i < sz; i++)
	{
		Vector node = path.getPathNode(i)->value;
		float dist;
		int sample = 20;
		float maxDist = sample * TILE_SIZE;
		{
			Vector n = dsq->game->getWallNormal(node, sample, &dist);
			if (dist != -1 && (n.x != 0 || n.y != 0))
			{
				n.setLength2D(200);
				TileVector test(node + n);
				if (dsq->game->isObstructed(test))
				{
					n.setLength2D(100);
					test = TileVector(node+n);
					if (dsq->game->isObstructed(test))
					{
						n.setLength2D(50);
						test = TileVector(node+n);
						if (dsq->game->isObstructed(test))
						{
							n = Vector(0,0,0);
						}
					}
				}
				normals[i] = n;
			}
		}
	}
	
	// use wall normal to push out node a bit
	std::vector<Vector> newNormals;
	newNormals.resize(normals.size());
	for (i = 1; i < normals.size()-1; i++)
		newNormals[i] = (normals[i] + normals[i-1] + normals[i+1])/3.0f;
	for (i = 1; i < sz-1; i++)
		path.getPathNode(i)->value += newNormals[i];

	// kill bowls
	int start = 0;
	int runs=0;
	bool hadSuccess = false;
	int lastSuccessNode = 0;
	int adjust = 2;
	sz=path.getNumPathNodes();

	for (i = start; i < sz-1; i++)
	{
		runs++;
		if (runs > 8000)
		{
			debugLog("kill bowls ran too much");
			start = sz*100;
		}
		lastSuccessNode = 0;
		hadSuccess = false;
		Vector node = path.getPathNode(i)->value;
		for (int j = sz-1; j >= i+adjust; j--)
		{
			Vector target = path.getPathNode(j)->value;
			if (dsq->game->trace(node, target))
			{
				hadSuccess = true;
				lastSuccessNode = j;
				break;
			}
		}
		if (hadSuccess)
		{
			// this code will only delete things that are bowl-ish
			// (things that take you on detours)
			++i;
			path.removeNodes(i, lastSuccessNode-1);
			hadSuccess = false;
		}
		sz = path.getNumPathNodes();
	}
	sz=path.getNumPathNodes();

	// remove last node
	//path.removeNodes(path.getNumPathNodes()-2, path.getNumPathNodes()-2);

	path.realPercentageCalc();
}
Exemplo n.º 4
0
inline void debugThrow(const T& e) {
    debugLog(e);
    if (THROW_DEBUG_EXCEPTIONS) {
        throw e;
    }
}
Exemplo n.º 5
0
void GourceSettings::importGourceSettings(ConfFile& conffile, ConfSection* gource_settings) {

    setGourceDefaults();

    if(gource_settings == 0) gource_settings = conffile.getSection(default_section_name);

    if(gource_settings == 0) {
        gource_settings = conffile.addSection("gource");
    }

    ConfEntry* entry = 0;

    //hide flags

    std::vector<std::string> hide_fields;

    if((entry = gource_settings->getEntry("hide")) != 0) {

        if(!entry->hasValue()) conffile.missingValueException(entry);

        std::string hide_string = entry->getString();

        size_t sep;
        while((sep = hide_string.find(",")) != std::string::npos) {

            if(sep == 0 && hide_string.size()==1) break;

            if(sep == 0) {
                hide_string = hide_string.substr(sep+1, hide_string.size()-1);
                continue;
            }

            std::string hide_field  = hide_string.substr(0, sep);
            hide_fields.push_back(hide_field);
            hide_string = hide_string.substr(sep+1, hide_string.size()-1);
        }

        if(hide_string.size() > 0 && hide_string != ",") hide_fields.push_back(hide_string);

        //validate field list

        for(std::vector<std::string>::iterator it = hide_fields.begin(); it != hide_fields.end(); it++) {
            std::string hide_field = (*it);

            if(   hide_field != "date"
               && hide_field != "users"
               && hide_field != "tree"
               && hide_field != "files"
               && hide_field != "usernames"
               && hide_field != "filenames"
               && hide_field != "dirnames"
               && hide_field != "bloom"
               && hide_field != "progress"
               && hide_field != "mouse"
               && hide_field != "root") {
                std::string unknown_hide_option = std::string("unknown option hide ") + hide_field;
                conffile.entryException(entry, unknown_hide_option);
            }
        }
    }

    //check hide booleans
    for(std::map<std::string,std::string>::iterator it = arg_types.begin(); it != arg_types.end(); it++) {
        if(it->first.find("hide-") == 0 && it->second == "bool") {

            if(gource_settings->getBool(it->first)) {
                std::string hide_field = it->first.substr(5, it->first.size()-5);
                hide_fields.push_back(hide_field);
            }
        }
    }

    if(hide_fields.size()>0) {

        for(std::vector<std::string>::iterator it = hide_fields.begin(); it != hide_fields.end(); it++) {
            std::string hidestr = (*it);

                if(hidestr == "date")       hide_date      = true;
            else if(hidestr == "users")     hide_users     = true;
            else if(hidestr == "tree")      hide_tree      = true;
            else if(hidestr == "files")     hide_files     = true;
            else if(hidestr == "usernames") hide_usernames = true;
            else if(hidestr == "filenames") hide_filenames = true;
            else if(hidestr == "dirnames")  hide_dirnames  = true;
            else if(hidestr == "bloom")     hide_bloom     = true;
            else if(hidestr == "progress")  hide_progress  = true;
            else if(hidestr == "root")      hide_root      = true;
            else if(hidestr == "mouse")     {
                hide_mouse     = true;
                hide_progress  = true;
            }
        }
    }

    if((entry = gource_settings->getEntry("date-format")) != 0) {

        if(!entry->hasValue()) conffile.missingValueException(entry);

        date_format = entry->getString();
    }

    if(gource_settings->getBool("disable-auto-rotate")) {
        disable_auto_rotate=true;
    }

    if(gource_settings->getBool("disable-auto-skip")) {
        auto_skip_seconds = -1.0;
    }

    if(gource_settings->getBool("loop")) {
        loop = true;
    }

    if((entry = gource_settings->getEntry("git-branch")) != 0) {

        if(!entry->hasValue()) conffile.missingValueException(entry);

        Regex branch_regex("^(?!-)[/\\w.,;_=+{}\\[\\]-]+$");

        std::string branch = entry->getString();

        if(branch_regex.match(branch)) {
            git_branch = branch;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if(gource_settings->getBool("colour-images")) {
        colour_user_images = true;
    }

    if((entry = gource_settings->getEntry("crop")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify crop (vertical,horizontal)");

        std::string crop = entry->getString();

        if(crop == "vertical") {
            crop_vertical = true;
        } else if (crop == "horizontal") {
            crop_horizontal = true;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("log-format")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify log-format (format)");

        log_format = entry->getString();

        if(log_format == "cvs") {
            conffile.entryException(entry, "please use either 'cvs2cl' or 'cvs-exp'");
        }

        if(   log_format != "git"
           && log_format != "cvs-exp"
           && log_format != "cvs2cl"
           && log_format != "svn"
           && log_format != "custom"
           && log_format != "hg"
           && log_format != "bzr"
           && log_format != "apache") {

            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("default-user-image")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify default-user-image (image path)");

        default_user_image = entry->getString();
    }

    if((entry = gource_settings->getEntry("user-image-dir")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-image-dir (directory)");

        user_image_dir = entry->getString();

        //append slash
        if(user_image_dir[user_image_dir.size()-1] != '/') {
            user_image_dir += std::string("/");
        }

        user_image_map.clear();

        boost::filesystem::path image_dir_path(user_image_dir);

        if(!is_directory(image_dir_path)) {
             conffile.entryException(entry, "specified user-image-dir is not a directory");
        }

        std::vector<boost::filesystem::path> image_dir_files;

        try {
            copy(boost::filesystem::directory_iterator(image_dir_path), boost::filesystem::directory_iterator(), back_inserter(image_dir_files));
        } catch(const boost::filesystem::filesystem_error& exception) {
             conffile.entryException(entry, "error reading specified user-image-dir");
        }

        for(boost::filesystem::path& p : image_dir_files) {

            std::string dirfile;

#ifdef _WIN32
            std::wstring dirfile_16 = p.filename().wstring();
            utf8::utf16to8(dirfile_16.begin(), dirfile_16.end(), back_inserter(dirfile));
#else
            dirfile = p.filename().string();
#endif
            std::string file_ext = extension(p);
            boost::algorithm::to_lower(file_ext);

            if(file_ext != ".jpg" && file_ext != ".jpeg" && file_ext != ".png") continue;

            std::string image_path = gGourceSettings.user_image_dir + dirfile;
            std::string name       = dirfile.substr(0,dirfile.size() - file_ext.size());

#ifdef __APPLE__
                CFMutableStringRef help = CFStringCreateMutable(kCFAllocatorDefault, 0);
                CFStringAppendCString(help, name.c_str(), kCFStringEncodingUTF8);
                CFStringNormalize(help, kCFStringNormalizationFormC);
                char data[4096];
                CFStringGetCString(help,
                                   data,
                                   sizeof(data),
                                   kCFStringEncodingUTF8);
                name = data;
#endif

            debugLog("%s => %s", name.c_str(), image_path.c_str());

            user_image_map[name] = image_path;
        }
    }

    if((entry = gource_settings->getEntry("caption-file")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption file (filename)");

        caption_file = entry->getString();

        if(!boost::filesystem::exists(caption_file)) {
            conffile.entryException(entry, "caption file not found");
        }
    }

    if((entry = gource_settings->getEntry("caption-duration")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption duration (seconds)");

        caption_duration = entry->getFloat();

        if(caption_duration <= 0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("caption-size")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption size");

        caption_size = entry->getInt();

        if(caption_size<1 || caption_size>100) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("caption-offset")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption offset");

        caption_offset = entry->getInt();
    }

    if((entry = gource_settings->getEntry("caption-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify caption colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            caption_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            caption_colour = vec3(r,g,b);
            caption_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("filename-colour")) != 0) {
        if(!entry->hasValue()) conffile.entryException(entry, "specify filename colour (FFFFFF)");

	int r,g,b;

	std::string colstring = entry->getString();

	if(entry->isVec3()) {
	    filename_colour = entry->getVec3();
	} else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            filename_colour = vec3(r,g,b);
            filename_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("filename-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify duration to keep files on screen (float)");

        filename_time = entry->getFloat();

        if(filename_time<2.0f) {
            conffile.entryException(entry, "filename-time must be >= 2.0");
        }
    }

    if((entry = gource_settings->getEntry("bloom-intensity")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify bloom-intensity (float)");

        bloom_intensity = entry->getFloat();

        if(bloom_intensity<=0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("bloom-multiplier")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify bloom-multiplier (float)");

        bloom_multiplier = entry->getFloat();

        if(bloom_multiplier<=0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("elasticity")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify elasticity (float)");

        elasticity = entry->getFloat();

        if(elasticity<=0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("font-size")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify font size");

        font_size = entry->getInt();

        if(font_size<1 || font_size>100) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("hash-seed")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify hash seed (integer)");

        gStringHashSeed = entry->getInt();
    }

    if((entry = gource_settings->getEntry("font-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify font colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            font_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            font_colour = vec3(r,g,b);
            font_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("background-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify background colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            background_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            background_colour = vec3(r,g,b);
            background_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("highlight-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify highlight colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            highlight_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            highlight_colour = vec3(r,g,b);
            highlight_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("selection-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify selection colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            selection_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            selection_colour = vec3(r,g,b);
            selection_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("dir-colour")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify dir colour (FFFFFF)");

        int r,g,b;

        std::string colstring = entry->getString();

        if(entry->isVec3()) {
            dir_colour = entry->getVec3();
        } else if(colstring.size()==6 && sscanf(colstring.c_str(), "%02x%02x%02x", &r, &g, &b) == 3) {
            dir_colour = vec3(r,g,b);
            dir_colour /= 255.0f;
        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("background-image")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify background image (image path)");

        background_image = entry->getString();
    }

    if((entry = gource_settings->getEntry("title")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify title");

        title = entry->getString();
    }

    if((entry = gource_settings->getEntry("logo")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify logo (image path)");

        logo = entry->getString();
    }

    if((entry = gource_settings->getEntry("logo-offset")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify logo-offset (XxY)");

        std::string logo_offset_str = entry->getString();

        int posx = 0;
        int posy = 0;

        if(parseRectangle(logo_offset_str, posx, posy)) {
            logo_offset = vec2(posx, posy);
        } else {
            conffile.invalidValueException(entry);
        }

    }

    if((entry = gource_settings->getEntry("seconds-per-day")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify seconds-per-day (seconds)");

        float seconds_per_day = entry->getFloat();

        if(seconds_per_day<=0.0f) {
            conffile.invalidValueException(entry);
        }

        // convert seconds-per-day to days-per-second
        days_per_second = 1.0 / seconds_per_day;
    }

    if((entry = gource_settings->getEntry("auto-skip-seconds")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify auto-skip-seconds (seconds)");

        auto_skip_seconds = entry->getFloat();

        if(auto_skip_seconds <= 0.0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("file-idle-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify file-idle-time (seconds)");

        std::string file_idle_str = entry->getString();

        file_idle_time = (float) atoi(file_idle_str.c_str());

        if(file_idle_time<0.0f || (file_idle_time == 0.0f && file_idle_str[0] != '0') ) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("user-idle-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-idle-time (seconds)");

        user_idle_time = entry->getFloat();

        if(user_idle_time < 0.0f) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("time-scale")) != 0) {

        if(!entry->hasValue())
            conffile.entryException(entry, "specify time-scale (scale)");

        time_scale = entry->getFloat();

        if(time_scale <= 0.0f || time_scale > 4.0f) {
            conffile.entryException(entry, "time-scale outside of range 0.0 - 4.0");
        }
    }

    if((entry = gource_settings->getEntry("start-date")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify start-date (YYYY-MM-DD hh:mm:ss)");

        std::string start_date_string = entry->getString();

        if(parseDateTime(start_date_string, start_timestamp)) {

            char datestr[256];
            strftime(datestr, 256, "%Y-%m-%d", localtime ( &start_timestamp ));
            start_date = datestr;

        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("stop-date")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify stop-date (YYYY-MM-DD hh:mm:ss)");

        std::string end_date_string = entry->getString();

        if(parseDateTime(end_date_string, stop_timestamp)) {

            struct tm * timeinfo;
            timeinfo = localtime ( &stop_timestamp );

            time_t stop_timestamp_rounded = stop_timestamp;

            if(timeinfo->tm_hour > 0 || timeinfo->tm_min > 0 || timeinfo->tm_sec > 0) {
                stop_timestamp_rounded += 60*60*24;
            }

            char datestr[256];
            strftime(datestr, 256, "%Y-%m-%d", localtime ( &stop_timestamp_rounded ));
            stop_date = datestr;

        } else {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("start-position")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify start-position (float,random)");

        if(entry->getString() == "random") {
            srand(time(0));
            start_position = (rand() % 1000) / 1000.0f;
        } else {
            start_position = entry->getFloat();

            if(start_position<=0.0 || start_position>=1.0) {
                conffile.entryException(entry, "start-position outside of range 0.0 - 1.0 (non-inclusive)");
            }
        }
    }

    if((entry = gource_settings->getEntry("stop-position")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify stop-position (float)");

        stop_position = entry->getFloat();

        if(stop_position<=0.0 || stop_position>1.0) {
            conffile.entryException(entry, "stop-position outside of range 0.0 - 1.0 (inclusive)");
        }
    }

    if((entry = gource_settings->getEntry("stop-at-time")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify stop-at-time (seconds)");

        stop_at_time = entry->getFloat();

        if(stop_at_time <= 0.0) {
            conffile.invalidValueException(entry);
        }
    }

    if(gource_settings->getBool("key")) {
        show_key = true;
    }

    if(gource_settings->getBool("ffp")) {
        ffp = true;
    }

    if(gource_settings->getBool("realtime")) {
        days_per_second = 1.0 / 86400.0;
    }

    if(gource_settings->getBool("no-time-travel")) {
        no_time_travel = true;
    }

    if(gource_settings->getBool("dont-stop")) {
        dont_stop = true;
    }

    if(gource_settings->getBool("stop-at-end")) {
        stop_at_end = true;
    }

    //NOTE: this no longer does anything
    if(gource_settings->getBool("stop-on-idle")) {
        stop_on_idle = true;
    }

    if((entry = gource_settings->getEntry("max-files")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify max-files (number)");

        max_files = entry->getInt();

        if( max_files<0 || (max_files == 0 && entry->getString() != "0") ) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("max-file-lag")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify max-file-lag (seconds)");

        max_file_lag = entry->getFloat();

        if(max_file_lag==0.0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("user-friction")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-friction (seconds)");

        user_friction = entry->getFloat();

        if(user_friction<=0.0) {
            conffile.invalidValueException(entry);
        }

        user_friction = 1.0 / user_friction;
    }

    if((entry = gource_settings->getEntry("user-scale")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify user-scale (scale)");

        user_scale = entry->getFloat();

        if(user_scale<=0.0 || user_scale>100.0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("max-user-speed")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify max-user-speed (units)");

        max_user_speed = entry->getFloat();

        if(max_user_speed<=0) {
            conffile.invalidValueException(entry);
        }
    }

    if(   gource_settings->getBool("highlight-users")
       || gource_settings->getBool("highlight-all-users")) {
        highlight_all_users = true;
    }

    if(gource_settings->getBool("highlight-dirs")) {
        highlight_dirs = true;
    }

    if((entry = gource_settings->getEntry("camera-mode")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify camera-mode (overview,track)");

        camera_mode = entry->getString();

        if(camera_mode != "overview" && camera_mode != "track") {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("padding")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify padding (float)");

        padding = entry->getFloat();

        if(padding <= 0.0f || padding >= 2.0f) {
            conffile.invalidValueException(entry);
        }
    }

    // multi-value entries

    if((entry = gource_settings->getEntry("highlight-user")) != 0) {

        ConfEntryList* highlight_user_entries = gource_settings->getEntries("highlight-user");

        for(ConfEntryList::iterator it = highlight_user_entries->begin(); it != highlight_user_entries->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify highlight-user (user)");

            highlight_users.push_back(entry->getString());
        }
    }

    if((entry = gource_settings->getEntry("follow-user")) != 0) {

        ConfEntryList* follow_user_entries = gource_settings->getEntries("follow-user");

        for(ConfEntryList::iterator it = follow_user_entries->begin(); it != follow_user_entries->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify follow-user (user)");

            follow_users.push_back(entry->getString());
        }
    }

    if(gource_settings->getBool("file-extensions")) {
        file_extensions=true;
    }

    if(gource_settings->getBool("file-extension-fallback")) {
        file_extension_fallback=true;
    }

    if((entry = gource_settings->getEntry("file-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("file-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify file-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid file-filter regular expression");
            }

            file_filters.push_back(r);
        }
    }

    if((entry = gource_settings->getEntry("file-show-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("file-show-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify file-show-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid file-show-filter regular expression");
            }

            file_show_filters.push_back(r);
        }
    }

    if((entry = gource_settings->getEntry("user-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("user-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify user-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid user-filter regular expression");
            }

            user_filters.push_back(r);
        }
    }

    if((entry = gource_settings->getEntry("user-show-filter")) != 0) {

        ConfEntryList* filters = gource_settings->getEntries("user-show-filter");

        for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {

            entry = *it;

            if(!entry->hasValue()) conffile.entryException(entry, "specify user-show-filter (regex)");

            std::string filter_string = entry->getString();

            Regex* r = new Regex(filter_string, 1);

            if(!r->isValid()) {
                delete r;
                conffile.entryException(entry, "invalid user-show-filter regular expression");
            }

            user_show_filters.push_back(r);
        }
    }

    if((entry = gource_settings->getEntry("dir-name-depth")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify dir-name-depth (depth)");

        dir_name_depth = entry->getInt();

        if(dir_name_depth <= 0) {
            conffile.invalidValueException(entry);
        }
    }

    if((entry = gource_settings->getEntry("dir-name-position")) != 0) {

        if(!entry->hasValue()) conffile.entryException(entry, "specify dir-name-position (float)");

        dir_name_position = entry->getFloat();

        if(dir_name_position < 0.1f || dir_name_position > 1.0f) {
            conffile.entryException(entry, "dir-name-position outside of range 0.1 - 1.0 (inclusive)");
        }
    }

    //validate path
    if(gource_settings->hasValue("path")) {
        path = gource_settings->getString("path");
        default_path = false;
    }

    if(path == "-") {

        if(log_format.size() == 0) {
            throw ConfFileException("log-format required when reading from STDIN", "", 0);
        }

#ifdef _WIN32
        DWORD available_bytes;
        HANDLE stdin_handle = GetStdHandle(STD_INPUT_HANDLE);

        while(PeekNamedPipe(stdin_handle, 0, 0, 0,
            &available_bytes, 0) && available_bytes==0 && !std::cin.fail()) {
            SDL_Delay(100);
        }
#else
        while(std::cin.peek() == EOF && !std::cin.fail()) SDL_Delay(100);
#endif

        std::cin.clear();

    } else if(!path.empty() && path != ".") {

        //remove trailing slash
        if(path[path.size()-1] == '\\' || path[path.size()-1] == '/') {
            path.resize(path.size()-1);
        }

        // check path exists
        if(!boost::filesystem::exists(path)) {
            throw ConfFileException(str(boost::format("'%s' does not appear to be a valid file or directory") % path), "", 0);
        }
    }
}
Exemplo n.º 6
0
void CSametimeProto::ExportContactsToList(mwSametimeList* user_list)
{
	debugLog(_T("CSametimeProto::ExportContactsToList() start"));
	mwSametimeGroup* stgroup = 0;
	char* group_name;
	char* group_alias;
	mwSametimeGroupType group_type;
	bool group_open;

	mwSametimeUser* stuser;
	char* user_alias;
	char* user_shortName;
	mwSametimeUserType user_type;
	DBVARIANT dbv, dbv2;
	char buff[256];
	mwAwareIdBlock id_block;
	mwIdBlock uid;

	GList* gl = 0;
	for (MCONTACT hContact = db_find_first(m_szModuleName); hContact; hContact = db_find_next(hContact, m_szModuleName)) {
		if (!db_get_utf(hContact, m_szModuleName, "stid", &dbv)) {
			if (dbv.pszVal) {
				if (GetAwareIdFromContact(hContact, &id_block)) {
					if (!db_get_utf(hContact, "CList", "Group", &dbv2)) {
						group_alias = _strdup(dbv2.pszVal);
						db_free(&dbv2);
					}
					else
						group_alias = _strdup(Translate("None"));

					if (group_alias) {
						mir_snprintf(buff, "GT_%s", group_alias);
						group_type = (mwSametimeGroupType)db_get_b(0, szProtoGroups, buff, (BYTE)mwSametimeGroup_NORMAL);
						// apparently we don't want to upload contacts in dynamic groups - see gaim sametime plugin comments
						if (group_type == mwSametimeGroup_DYNAMIC) {
							db_free(&dbv);
							free(id_block.user);
							free(group_alias);
							hContact = db_find_next(hContact, m_szModuleName);
							continue;
						}

						mir_snprintf(buff, "GN_%s", group_alias);
						if (!db_get_utf(0, szProtoGroups, buff, &dbv2)) {
							group_name = _strdup(dbv2.pszVal);
							db_free(&dbv2);
						}
						else
							group_name = _strdup(group_alias);

						//group_open = (db_get_b(0, szProtoGroups, buff, 0) == 1);

						ptrT ptszGroup(mir_utf8decodeT(group_alias));
						HANDLE hGroup = Clist_GroupExists(ptszGroup);
						if (hGroup) {
							int expanded;
							CallService(MS_CLIST_GROUPGETNAME, (WPARAM)hGroup, (LPARAM)&expanded);
							group_open = (expanded != 0);
						}
						else {
							mir_snprintf(buff, "GO_%s", group_alias);
							group_open = (db_get_b(0, szProtoGroups, buff, 0) == 1);
						}

						stgroup = 0;
						stgroup = mwSametimeList_findGroup(user_list, group_name);
						if (!stgroup) {
							if (group_name) stgroup = mwSametimeGroup_new(user_list, group_type, group_name);
							mwSametimeGroup_setAlias(stgroup, group_alias);
							mwSametimeGroup_setOpen(stgroup, group_open);
						}

						free(group_name);
						free(group_alias);

						if (!db_get_utf(hContact, m_szModuleName, "Name", &dbv2)) {
							user_shortName = _strdup(dbv2.pszVal);
							db_free(&dbv2);
						}
						else
							user_shortName = 0;

						if (!db_get_utf(hContact, "CList", "MyHandle", &dbv2)) {
							user_alias = _strdup(dbv2.pszVal);
							db_free(&dbv2);
						}
						else
							user_alias = 0;

						user_type = (mwSametimeUserType)db_get_b(hContact, m_szModuleName, "type", (BYTE)mwSametimeUser_NORMAL);

						uid.user = id_block.user;
						uid.community = id_block.community;

						stuser = mwSametimeUser_new(stgroup, user_type, &uid);
						if (user_shortName) {
							mwSametimeUser_setShortName(stuser, user_shortName);
							free(user_shortName);
						}
						if (user_alias) {
							mwSametimeUser_setAlias(stuser, user_alias);
							free(user_alias);
						}
					}

					free(id_block.user);
				}
			}
			db_free(&dbv);
		}
	}
}
Exemplo n.º 7
0
BOOL CJabberProto::OnRosterPushRequest(HXML, CJabberIqInfo *pInfo)
{
	HXML queryNode = pInfo->GetChildNode();

	// RFC 3921 #7.2 Business Rules
	if (pInfo->GetFrom()) {
		TCHAR *szFrom = JabberPrepareJid(pInfo->GetFrom());
		if (!szFrom)
			return TRUE;

		TCHAR *szTo = JabberPrepareJid(m_ThreadInfo->fullJID);
		if (!szTo) {
			mir_free(szFrom);
			return TRUE;
		}

		TCHAR *pDelimiter = _tcschr(szFrom, _T('/'));
		if (pDelimiter) *pDelimiter = 0;

		pDelimiter = _tcschr(szTo, _T('/'));
		if (pDelimiter) *pDelimiter = 0;

		BOOL bRetVal = mir_tstrcmp(szFrom, szTo) == 0;

		mir_free(szFrom);
		mir_free(szTo);

		// invalid JID
		if (!bRetVal) {
			debugLog(_T("<iq/> attempt to hack via roster push from %s"), pInfo->GetFrom());
			return TRUE;
		}
	}

	JABBER_LIST_ITEM *item;
	MCONTACT hContact = NULL;
	const TCHAR *jid, *str;

	debugLogA("<iq/> Got roster push, query has %d children", XmlGetChildCount(queryNode));
	for (int i = 0;; i++) {
		HXML itemNode = XmlGetChild(queryNode, i);
		if (!itemNode)
			break;

		if (mir_tstrcmp(XmlGetName(itemNode), _T("item")) != 0)
			continue;
		if ((jid = XmlGetAttrValue(itemNode, _T("jid"))) == NULL)
			continue;
		if ((str = XmlGetAttrValue(itemNode, _T("subscription"))) == NULL)
			continue;

		// we will not add new account when subscription=remove
		if (!mir_tstrcmp(str, _T("to")) || !mir_tstrcmp(str, _T("both")) || !mir_tstrcmp(str, _T("from")) || !mir_tstrcmp(str, _T("none"))) {
			const TCHAR *name = XmlGetAttrValue(itemNode, _T("name"));
			ptrT nick((name != NULL) ? mir_tstrdup(name) : JabberNickFromJID(jid));
			if (nick != NULL) {
				if ((item = ListAdd(LIST_ROSTER, jid)) != NULL) {
					replaceStrT(item->nick, nick);

					HXML groupNode = XmlGetChild(itemNode, "group");
					replaceStrT(item->group, XmlGetText(groupNode));

					if ((hContact = HContactFromJID(jid, 0)) == NULL) {
						// Received roster has a new JID.
						// Add the jid (with empty resource) to Miranda contact list.
						hContact = DBCreateContact(jid, nick, FALSE, FALSE);
					}
					else setTString(hContact, "jid", jid);

					if (name != NULL) {
						ptrT tszNick(getTStringA(hContact, "Nick"));
						if (tszNick != NULL) {
							if (mir_tstrcmp(nick, tszNick) != 0)
								db_set_ts(hContact, "CList", "MyHandle", nick);
							else
								db_unset(hContact, "CList", "MyHandle");
						}
						else db_set_ts(hContact, "CList", "MyHandle", nick);
					}
					else db_unset(hContact, "CList", "MyHandle");

					if (!m_options.IgnoreRosterGroups) {
						if (item->group != NULL) {
							Clist_CreateGroup(0, item->group);
							db_set_ts(hContact, "CList", "Group", item->group);
						}
						else db_unset(hContact, "CList", "Group");
					}
				}
			}
		}

		if ((item = ListGetItemPtr(LIST_ROSTER, jid)) != NULL) {
			if (!mir_tstrcmp(str, _T("both"))) item->subscription = SUB_BOTH;
			else if (!mir_tstrcmp(str, _T("to"))) item->subscription = SUB_TO;
			else if (!mir_tstrcmp(str, _T("from"))) item->subscription = SUB_FROM;
			else item->subscription = SUB_NONE;
			debugLog(_T("Roster push for jid=%s, set subscription to %s"), jid, str);
			// subscription = remove is to remove from roster list
			// but we will just set the contact to offline and not actually
			// remove, so that history will be retained.
			if (!mir_tstrcmp(str, _T("remove"))) {
				if ((hContact = HContactFromJID(jid)) != NULL) {
					SetContactOfflineStatus(hContact);
					ListRemove(LIST_ROSTER, jid);
				}
			}
			else if (isChatRoom(hContact))
				db_unset(hContact, "CList", "Hidden");
			else
				UpdateSubscriptionInfo(hContact, item);
		}
	}

	UI_SAFE_NOTIFY(m_pDlgServiceDiscovery, WM_JABBER_TRANSPORT_REFRESH);
	RebuildInfoFrame();
	return TRUE;
}
Exemplo n.º 8
0
void profile_stop() {
#ifdef LS_PERFORMANCE_PROFILE
    debugLog("%s took %d ms\n", profile_name.c_str(), SDL_GetTicks() - profile_start_msec);
#endif
}
Exemplo n.º 9
0
void Logstalgia::readLog(int buffer_rows) {

    profile_start("readLog");

    set_utc_tz();

    int entries_read = 0;

    std::string linestr;
    BaseLog* baselog = getLog();

    time_t read_timestamp = 0;

    while( baselog->getNextLine(linestr) ) {

        //trim whitespace
        if(linestr.size()>0) {
            size_t string_end =
                linestr.find_last_not_of(" \t\f\v\n\r");

            if(string_end == std::string::npos) {
                linestr = "";
            } else if(string_end != linestr.size()-1) {
                linestr = linestr.substr(0,string_end+1);
            }
        }

        LogEntry le;

        bool parsed_entry;

        //determine format
        if(accesslog==0) {

            //is this a recognized NCSA access log?
            NCSALog* ncsalog = new NCSALog();
            if((parsed_entry = ncsalog->parseLine(linestr, le))) {
                accesslog = ncsalog;
            } else {
                delete ncsalog;
            }

            if(accesslog==0) {
                //is this a custom log?
                CustomAccessLog* customlog = new CustomAccessLog();
                if((parsed_entry = customlog->parseLine(linestr, le))) {
                    accesslog = customlog;
                } else {
                    delete customlog;
                }
            }

        } else {

            if(!(parsed_entry = accesslog->parseLine(linestr, le))) {
                debugLog("error: could not read line %s\n", linestr.c_str());
            }
        }

        if(parsed_entry) {

            if((!mintime || mintime <= le.timestamp) && (!settings.stop_time || settings.stop_time > le.timestamp)) {

                queued_entries.push_back(new LogEntry(le));

                total_entries++;
                entries_read++;

                //read at least the buffered row count if specified
                //otherwise read all entries with the same time
                if(buffer_rows) {
                    if(entries_read > buffer_rows) break;
                } else {
                    if(read_timestamp && read_timestamp < le.timestamp) break;
                }

                read_timestamp = le.timestamp;
            }
        }
    }

    profile_stop();

    unset_utc_tz();
    
    if(queued_entries.empty() && seeklog != 0) {

        if(total_entries==0) {
            if(mintime != 0) {
                logstalgia_quit("could not parse any entries in the specified time period");
            } else {
                logstalgia_quit("could not parse any entries");
            }
        }

        //no more entries
        end_reached = true;

        return;
    }
    
    if(seeklog != 0) {
        float percent = seeklog->getPercent();

        if(percent > settings.stop_position) {
            end_reached = true;
            return;
        }

        if(!settings.disable_progress) slider.setPercent(percent);
    }

    //set start time if currently 0
    if(starttime==0 && !queued_entries.empty()) {
        starttime = queued_entries.front()->timestamp;
        currtime  = 0;
    }
}
Exemplo n.º 10
0
void u2fhid_ping(const uint8_t *buf, uint32_t len)
{
	debugLog(0, "", "u2fhid_ping");
	send_u2fhid_msg(U2FHID_PING, buf, len);
}
Exemplo n.º 11
0
static void promptRegister(bool request, const U2F_REGISTER_REQ *req)
{
#if 0
	// Users find it confusing when a Ledger and a KeepKey are plugged in
	// at the same time. To avoid that, we elect not to show a message in
	// this case.
	if (0 == memcmp(req->appId, BOGUS_APPID, U2F_APPID_SIZE)) {
		layoutU2FDialog(request, "U2f Register",
		                "Another U2F device was used to register in this application.");
	} else {
#else
	{
#endif
		const char *appname = "";
		bool readable = getReadableAppId(req->appId, &appname);
		layoutU2FDialog(request, "U2F Register",
		                readable
		                    ? "Do you want to register with %s?"
		                    : "Do you want to register with this U2F application?\n\n%s",
		                appname);
	}
}

void u2f_register(const APDU *a)
{
	static U2F_REGISTER_REQ last_req;
	const U2F_REGISTER_REQ *req = (U2F_REGISTER_REQ *)a->data;

	if (!storage_isInitialized()) {
		layout_warning_static("Cannot register u2f: not initialized");
		send_u2f_error(U2F_SW_CONDITIONS_NOT_SATISFIED);
		delay_ms(3000);
		return;
	}

	// Validate basic request parameters
	debugLog(0, "", "u2f register");
	if (APDU_LEN(*a) != sizeof(U2F_REGISTER_REQ)) {
		debugLog(0, "", "u2f register - badlen");
		send_u2f_error(U2F_SW_WRONG_LENGTH);
		return;
	}

	// If this request is different from last request, reset state machine
	if (memcmp(&last_req, req, sizeof(last_req)) != 0) {
		memcpy(&last_req, req, sizeof(last_req));
		last_req_state = INIT;
	}

	// First Time request, return not present and display request dialog
	if (last_req_state == INIT) {
		// error: testof-user-presence is required
		//buttonUpdate();
		promptRegister(true, req);
		last_req_state = REG;
	}

	// Still awaiting Keypress
	if (last_req_state == REG) {
		// error: testof-user-presence is required
		send_u2f_error(U2F_SW_CONDITIONS_NOT_SATISFIED);
		dialog_timeout = U2F_TIMEOUT;
		return;
	}

	// Buttons said yes
	if (last_req_state == REG_PASS) {
		uint8_t data[sizeof(U2F_REGISTER_RESP) + 2];
		U2F_REGISTER_RESP *resp = (U2F_REGISTER_RESP *)&data;
		memzero(data, sizeof(data));

		resp->registerId = U2F_REGISTER_ID;
		resp->keyHandleLen = KEY_HANDLE_LEN;
		// Generate keypair for this appId
		const HDNode *node =
			generateKeyHandle(req->appId, (uint8_t*)&resp->keyHandleCertSig);

		if (!node) {
			debugLog(0, "", "getDerivedNode Fail");
			send_u2f_error(U2F_SW_WRONG_DATA); // error:bad key handle
			return;
		}

		ecdsa_get_public_key65(node->curve->params, node->private_key,
				       (uint8_t *)&resp->pubKey);

		memcpy(resp->keyHandleCertSig + resp->keyHandleLen,
		       U2F_ATT_CERT, sizeof(U2F_ATT_CERT));

		uint8_t sig[64];
		U2F_REGISTER_SIG_STR sig_base;
		sig_base.reserved = 0;
		memcpy(sig_base.appId, req->appId, U2F_APPID_SIZE);
		memcpy(sig_base.chal, req->chal, U2F_CHAL_SIZE);
		memcpy(sig_base.keyHandle, &resp->keyHandleCertSig, KEY_HANDLE_LEN);
		memcpy(sig_base.pubKey, &resp->pubKey, U2F_PUBKEY_LEN);
		if (ecdsa_sign(&nist256p1, HASHER_SHA2, U2F_ATT_PRIV_KEY, (uint8_t *)&sig_base, sizeof(sig_base), sig, NULL, NULL) != 0) {
			send_u2f_error(U2F_SW_WRONG_DATA);
			return;
		}

		// Where to write the signature in the response
		uint8_t *resp_sig = resp->keyHandleCertSig +
				    resp->keyHandleLen + sizeof(U2F_ATT_CERT);
		// Convert to der for the response
		const uint8_t sig_len = ecdsa_sig_to_der(sig, resp_sig);

		// Append success bytes
		memcpy(resp->keyHandleCertSig + resp->keyHandleLen +
			   sizeof(U2F_ATT_CERT) + sig_len,
		       "\x90\x00", 2);

		int l = 1 /* registerId */ + U2F_PUBKEY_LEN +
			1 /* keyhandleLen */ + resp->keyHandleLen +
			sizeof(U2F_ATT_CERT) + sig_len + 2;

		last_req_state = INIT;
		dialog_timeout = 0;
		send_u2f_msg(data, l);

		promptRegister(false, req);
		return;
	}

	// Didnt expect to get here
	dialog_timeout = 0;
}

static void promptAuthenticate(bool request, const U2F_AUTHENTICATE_REQ *req)
{
	const char *appname = "";
	bool readable = getReadableAppId(req->appId, &appname);
	layoutU2FDialog(request,
	                "U2F Authenticate",
	                readable
	                    ? "Log in to %s?"
	                    : "Do you want to log in?\n\n%s",
	                appname);
}


void u2f_authenticate(const APDU *a)
{
	const U2F_AUTHENTICATE_REQ *req = (U2F_AUTHENTICATE_REQ *)a->data;
	static U2F_AUTHENTICATE_REQ last_req;

	if (!storage_isInitialized()) {
		layout_warning_static("Cannot authenticate u2f: not initialized");
		send_u2f_error(U2F_SW_CONDITIONS_NOT_SATISFIED);
		delay_ms(3000);
		return;
	}

	if (APDU_LEN(*a) < 64) { /// FIXME: decent value
		debugLog(0, "", "u2f authenticate - badlen");
		send_u2f_error(U2F_SW_WRONG_LENGTH);
		return;
	}

	if (req->keyHandleLen != KEY_HANDLE_LEN) {
		debugLog(0, "", "u2f auth - bad keyhandle len");
		send_u2f_error(U2F_SW_WRONG_DATA); // error:bad key handle
		return;
	}

	const HDNode *node =
	    validateKeyHandle(req->appId, req->keyHandle);

	if (!node) {
		debugLog(0, "", "u2f auth - bad keyhandle len");
		send_u2f_error(U2F_SW_WRONG_DATA); // error:bad key handle
		return;
	}

	if (a->p1 == U2F_AUTH_CHECK_ONLY) {
		debugLog(0, "", "u2f authenticate check");
		// This is a success for a good keyhandle
		// A failed check would have happened earlier
		// error: testof-user-presence is required
		send_u2f_error(U2F_SW_CONDITIONS_NOT_SATISFIED);
		return;
	}

	if (a->p1 != U2F_AUTH_ENFORCE) {
		debugLog(0, "", "u2f authenticate unknown");
		// error:bad key handle
		send_u2f_error(U2F_SW_WRONG_DATA);
		return;
	}

	debugLog(0, "", "u2f authenticate enforce");

	if (memcmp(&last_req, req, sizeof(last_req)) != 0) {
		memcpy(&last_req, req, sizeof(last_req));
		last_req_state = INIT;
	}

	if (last_req_state == INIT) {
		// error: testof-user-presence is required
		//buttonUpdate(); // Clear button state
		promptAuthenticate(true, req);
		last_req_state = AUTH;
	}

	// Awaiting Keypress
	if (last_req_state == AUTH) {
		// error: testof-user-presence is required
		send_u2f_error(U2F_SW_CONDITIONS_NOT_SATISFIED);
		dialog_timeout = U2F_TIMEOUT;
		return;
	}

	// Buttons said yes
	if (last_req_state == AUTH_PASS) {
		uint8_t buf[sizeof(U2F_AUTHENTICATE_RESP) + 2];
		U2F_AUTHENTICATE_RESP *resp =
			(U2F_AUTHENTICATE_RESP *)&buf;

		const uint32_t ctr = storage_nextU2FCounter();
		resp->flags = U2F_AUTH_FLAG_TUP;
		resp->ctr[0] = ctr >> 24 & 0xff;
		resp->ctr[1] = ctr >> 16 & 0xff;
		resp->ctr[2] = ctr >> 8 & 0xff;
		resp->ctr[3] = ctr & 0xff;

		// Build and sign response
		U2F_AUTHENTICATE_SIG_STR sig_base;
		uint8_t sig[64];
		memcpy(sig_base.appId, req->appId, U2F_APPID_SIZE);
		sig_base.flags = resp->flags;
		memcpy(sig_base.ctr, resp->ctr, 4);
		memcpy(sig_base.chal, req->chal, U2F_CHAL_SIZE);
		if (ecdsa_sign(&nist256p1, HASHER_SHA2, node->private_key, (uint8_t *)&sig_base, sizeof(sig_base), sig, NULL, NULL) != 0) {
			send_u2f_error(U2F_SW_WRONG_DATA);
			return;
		}

		// Copy DER encoded signature into response
		const uint8_t sig_len = ecdsa_sig_to_der(sig, resp->sig);

		// Append OK
		memcpy(buf + sizeof(U2F_AUTHENTICATE_RESP) -
			   U2F_MAX_EC_SIG_SIZE + sig_len,
			   "\x90\x00", 2);
		last_req_state = INIT;
		dialog_timeout = 0;
		send_u2f_msg(buf, sizeof(U2F_AUTHENTICATE_RESP) -
					  U2F_MAX_EC_SIG_SIZE + sig_len +
					  2);

		promptAuthenticate(false, req);
	}
}
Exemplo n.º 12
0
void CSteamProto::ParsePollData(JSONNode *data)
{
	JSONNode *node, *item = NULL;

	std::string steamIds;
	for (size_t i = 0; i < json_size(data); i++)
	{
		item = json_at(data, i);
		if (item == NULL)
			break;

		node = json_get(item, "steamid_from");
		ptrA steamId(mir_t2a(ptrT(json_as_string(node))));

		node = json_get(item, "utc_timestamp");
		time_t timestamp = atol(ptrA(mir_t2a(ptrT(json_as_string(node)))));

		node = json_get(item, "type");
		ptrT type(json_as_string(node));
		if (!lstrcmpi(type, _T("saytext")) || !lstrcmpi(type, _T("emote")) ||
			!lstrcmpi(type, _T("my_saytext")) || !lstrcmpi(type, _T("my_emote")))
		{
			MCONTACT hContact = FindContact(steamId);
			if (!hContact)
				continue;

			node = json_get(item, "text");
			ptrT text(json_as_string(node));
			T2Utf szMessage(text);

			if (_tcsstr(type, _T("my_")) == NULL)
			{
				PROTORECVEVENT recv = { 0 };
				recv.timestamp = timestamp;
				recv.szMessage = szMessage;
				ProtoChainRecvMsg(hContact, &recv);
			}
			else
			{
				AddDBEvent(hContact, EVENTTYPE_MESSAGE, timestamp, DBEF_UTF | DBEF_SENT, (int)mir_strlen(szMessage) + 1, (PBYTE)(char*)szMessage);
			}
		}
		else if (!lstrcmpi(type, _T("typing")))
		{
			MCONTACT hContact = FindContact(steamId);
			if (hContact)
			{
				CallService(MS_PROTO_CONTACTISTYPING, hContact, (LPARAM)STEAM_TYPING_TIME);
			}
		}
		else if (!lstrcmpi(type, _T("personastate")))
		{
			node = json_get(item, "persona_state");
			int status = node ? SteamToMirandaStatus(json_as_int(node)) : -1;

			if (IsMe(steamId))
			{
				node = json_get(item, "persona_name");
				setTString("Nick", ptrT(json_as_string(node)));

				if (status == -1 || status == ID_STATUS_OFFLINE)
					continue;

				if (status != m_iStatus)
				{
					debugLog(_T("CSteamProto::ParsePollData: Change own status to %i"), status);
					int oldStatus = m_iStatus;
					m_iStatus = m_iDesiredStatus = status;
					ProtoBroadcastAck(NULL, ACKTYPE_STATUS, ACKRESULT_SUCCESS, (HANDLE)oldStatus, m_iStatus);
				}

				continue;
			}
			
			MCONTACT hContact = FindContact(steamId);
			if (hContact == NULL)
				continue; // probably this is info about random player playing on same server, so we ignore it

			if (status != -1)
				SetContactStatus(hContact, status);

			node = json_get(item, "persona_name");
			setTString(hContact, "Nick", ptrT(json_as_string(node)));

			// todo: find difference between state changing and info changing
			steamIds.append(steamId).append(",");
		}
		else if (!lstrcmpi(type, _T("personarelationship")))
		{
			node = json_get(item, "persona_state");
			int state = json_as_int(node);

			switch (state)
			{
			case 0:
				{// removed
					MCONTACT hContact = FindContact(steamId);
					if (hContact)
					{
						ContactIsRemoved(hContact);
					}
				}
				break;

			case 1:
				{// ignored
					MCONTACT hContact = FindContact(steamId);
					if (hContact)
					{
						ContactIsIgnored(hContact);
					}
				}
				break;

			case 2:
				{// auth request
					/*MCONTACT hContact = FindContact(steamId);
					if (!hContact)
						hContact = AddContact(steamId, true);*/

					//RaiseAuthRequestThread((void*)hContact);

					ptrA token(getStringA("TokenSecret"));

					PushRequest(
						new GetUserSummariesRequest(token, steamId),
						&CSteamProto::OnAuthRequested,
						mir_strdup(steamId),
						MirFreeArg);
				}
				break;

			case 3:
				// add to list
				// todo
				break;

			default: continue;
			}
		}
		/*else if (!lstrcmpi(type, _T("leftconversation")))
		{
		}*/
		else
		{
			continue;
		}
	}

	if (!steamIds.empty())
	{
		steamIds.pop_back();
		ptrA token(getStringA("TokenSecret"));

		PushRequest(
			new GetUserSummariesRequest(token, steamIds.c_str()),
			&CSteamProto::OnGotUserSummaries);
	}
}
Exemplo n.º 13
0
void CSteamProto::PollingThread(void*)
{
	debugLog(_T("CSteamProto::PollingThread: entering"));

	ptrA token(getStringA("TokenSecret"));
	ptrA umqId(getStringA("UMQID"));
	UINT32 messageId = getDword("MessageID", 0);

	//PollApi::PollResult pollResult;
	int errors = 0;
	bool breaked = false;
	while (!isTerminated && !breaked && errors < POLLING_ERRORS_LIMIT)
	{
		PollRequest *request = new PollRequest(token, umqId, messageId, IdleSeconds());
		//request->nlc = m_pollingConnection;
		HttpResponse *response = request->Send(m_hNetlibUser);
		delete request;

		if (response == NULL || response->resultCode != HTTP_CODE_OK)
		{
			if (response != NULL)
				delete response;

			errors++;
			continue;
		}
		else
			errors = 0;

		JSONROOT root(response->pData);
		JSONNode *node = json_get(root, "error");
		ptrT error(json_as_string(node));

		if (!lstrcmpi(error, _T("OK")))
		{
			node = json_get(root, "messagelast");
			messageId = json_as_int(node);

			node = json_get(root, "messages");
			JSONNode *nroot = json_as_array(node);

			if (nroot != NULL)
			{
				ParsePollData(nroot);
				json_delete(nroot);
			}

			m_pollingConnection = response->nlc;
		}
		else if (!lstrcmpi(error, _T("Timeout")))
		{
			continue;
		}
		/*else if (!lstrcmpi(error, _T("Not Logged On"))) // 'else' below will handle this error, we don't need this particular check right now
		{
			if (!IsOnline())
			{
				// need to relogin
				debugLog(_T("CSteamProto::PollingThread: not logged on"));

				SetStatus(ID_STATUS_OFFLINE);
			}

			breaked = true;
		}*/
		else
		{
			// something wrong
			debugLog(_T("CSteamProto::PollingThread: %s (%d)"), error, response->resultCode);

			// token has expired
			if (response->resultCode == HTTP_CODE_UNAUTHORIZED)
				delSetting("TokenSecret");

			// too low timeout?
			node = json_get(root, "sectimeout");
			int timeout = json_as_int(node);
			if (timeout < STEAM_API_TIMEOUT)
				debugLog(_T("CSteamProto::PollingThread: Timeout is too low (%d)"), timeout);

			breaked = true;
		}

		delete response;
	}

	setDword("MessageID", messageId);

	m_hPollingThread = NULL;
	debugLog(_T("CSteamProto::PollingThread: leaving"));

	if (!isTerminated)
	{
		debugLog(_T("CSteamProto::PollingThread: unexpected termination; switching protocol to offline"));
		SetStatus(ID_STATUS_OFFLINE);
	}
}
Exemplo n.º 14
0
RCommitLog* RLogMill::fetchLog(std::string& log_format) {

    RCommitLog* clog = 0;

    //if the log format is not specified and 'logfile' is a directory, recursively look for a version control repository.
    //this method allows for something strange like someone who having an svn repository inside a git repository
    //(in which case it would pick the svn directory as it would encounter that first)

    if(log_format.empty() && logfile != "-") {

        try {
            boost::filesystem::path repo_path(logfile);

            if(is_directory(repo_path)) {
                if(findRepository(repo_path, log_format)) {
                    logfile = repo_path.string();
                }
            }
        } catch(boost::filesystem::filesystem_error& error) {
        }
    }

    //we've been told what format to use
    if(log_format.size() > 0) {
        debugLog("log-format = %s", log_format.c_str());

        if(log_format == "git") {
            clog = new GitCommitLog(logfile);
            if(clog->checkFormat()) return clog;
            delete clog;

            clog = new GitRawCommitLog(logfile);
            if(clog->checkFormat()) return clog;
            delete clog;
        }

        if(log_format == "hg") {
            clog = new MercurialLog(logfile);
            if(clog->checkFormat()) return clog;
            delete clog;
        }

        if(log_format == "bzr") {
            clog = new BazaarLog(logfile);
            if(clog->checkFormat()) return clog;
            delete clog;
        }

        if(log_format == "cvs") {
            clog = new CVSEXPCommitLog(logfile);
            if(clog->checkFormat()) return clog;
            delete clog;
        }

        if(log_format == "custom") {
            clog = new CustomLog(logfile);
            if(clog->checkFormat()) return clog;
            delete clog;
        }

        if(log_format == "apache") {
            clog = new ApacheCombinedLog(logfile);
            if(clog->checkFormat()) return clog;
            delete clog;
        }

        if(log_format == "svn") {
            clog = new SVNCommitLog(logfile);
            if(clog->checkFormat()) return clog;
            delete clog;
        }

        if(log_format == "cvs2cl") {
            clog = new CVS2CLCommitLog(logfile);
            if(clog->checkFormat()) return clog;
            delete clog;
        }

        return 0;
    }

    // try different formats until one works

    //git
    debugLog("trying git...");
    clog = new GitCommitLog(logfile);
    if(clog->checkFormat()) return clog;

    delete clog;

    //mercurial
    debugLog("trying mercurial...");
    clog = new MercurialLog(logfile);
    if(clog->checkFormat()) return clog;

    delete clog;

    //bzr
    debugLog("trying bzr...");
    clog = new BazaarLog(logfile);
    if(clog->checkFormat()) return clog;

    delete clog;

    //git raw
    debugLog("trying git raw...");
    clog = new GitRawCommitLog(logfile);
    if(clog->checkFormat()) return clog;

    delete clog;

    //cvs exp
    debugLog("trying cvs-exp...");
    clog = new CVSEXPCommitLog(logfile);
    if(clog->checkFormat()) return clog;

    delete clog;

    //svn
    debugLog("trying svn...");
    clog = new SVNCommitLog(logfile);
    if(clog->checkFormat()) return clog;

    delete clog;

    //cvs2cl
    debugLog("trying cvs2cl...");
    clog = new CVS2CLCommitLog(logfile);
    if(clog->checkFormat()) return clog;

    delete clog;

    //custom
    debugLog("trying custom...");
    clog = new CustomLog(logfile);
    if(clog->checkFormat()) return clog;

    delete clog;

    //apache
    debugLog("trying apache combined...");
    clog = new ApacheCombinedLog(logfile);
    if(clog->checkFormat()) return clog;

    delete clog;

    return 0;
}
void IsoSurfacePolygonizer::polygonize(const Point3D &start
                                      ,double         cellSize
                                      ,const Cube3D  &boundingBox
                                      ,bool           tetrahedralMode
                                      ,bool           tetraOptimize4
                                      ,bool           adaptiveCellSize
                                      ) {

  const double startTime = getThreadTime();

  m_cellSize         = cellSize;
  m_boundingBox      = boundingBox;
  m_delta            = cellSize/(double)(RES*RES);
  m_tetrahedralMode  = tetrahedralMode;
  m_tetraOptimize4   = tetraOptimize4;
  m_adaptiveCellSize = adaptiveCellSize;

  m_statistics.clear();
  resetTables();

#ifdef _DEBUG
  _standardRandomGenerator->setSeed(87);
#else
  randomize();
#endif // _DEBUG

  m_start = start;
  for(int i = 0; i < 10; i++) {
    m_start = findStartPoint(m_start);
    if(putInitialCube()) {
      break;
    }
  }

  m_vertexArray.setCapacity( HASHSIZE);
  m_cubesDoneSet.setCapacity(HASHSIZE);
  m_edgeMap.setCapacity(     HASHSIZE);
  m_currentLevel = 0;
  while(hasActiveCubes()) {
    while(hasActiveCubes()) { // process active cubes until none left
      const StackedCube cube = getActiveCube();
#ifdef DEBUG_POLYGONIZER
      m_eval.markCurrentCube(cube);
#endif // DEBUG_POLYGONIZER
      const bool done = addSurfaceVertices(cube);

      if(cube.getLevel() == 0) {
        // test six face directions, maybe add to stack:
        testFace(cube.m_key.i-1 , cube.m_key.j   , cube.m_key.k   , cube, LFACE, LBN, LBF, LTN, LTF);
        testFace(cube.m_key.i+1 , cube.m_key.j   , cube.m_key.k   , cube, RFACE, RBN, RBF, RTN, RTF);
        testFace(cube.m_key.i   , cube.m_key.j-1 , cube.m_key.k   , cube, BFACE, LBN, LBF, RBN, RBF);
        testFace(cube.m_key.i   , cube.m_key.j+1 , cube.m_key.k   , cube, TFACE, LTN, LTF, RTN, RTF);
        testFace(cube.m_key.i   , cube.m_key.j   , cube.m_key.k-1 , cube, NFACE, LBN, LTN, RBN, RTN);
        testFace(cube.m_key.i   , cube.m_key.j   , cube.m_key.k+1 , cube, FFACE, LBF, LTF, RBF, RTF);
      }
      if(!done) {
        splitCube(cube);
      }
    }
    m_faceCount[m_currentLevel] = (UINT)m_faceArray.size();
    if(m_currentLevel>0) m_faceCount[m_currentLevel] -= m_faceCount[m_currentLevel-1];
    prepareNextLevel();
    m_currentLevel++;
  }
  saveStatistics(startTime);
  flushFaceArray();

#ifdef  DUMP_STATISTICS
  debugLog(_T("%s\n"), m_statistics.toString().cstr());
#endif
#ifdef DUMP_CORNERMAP
  dumpCornerMap();
#endif
#ifdef DUMP_EDGEMAP
  dumpEdgeMap();
#endif
#ifdef DUMP_VERTEXARRAY
  dumpVertexArray();
#endif
#ifdef DUMP_FACEARRAY
  dumpFaceArray();
#endif
}
Exemplo n.º 16
0
INT_PTR GGPROTO::getavatarinfo(WPARAM wParam, LPARAM lParam)
{
	PROTO_AVATAR_INFORMATION *pai = (PROTO_AVATAR_INFORMATION *)lParam;
	pai->filename[0] = 0;
	pai->format = PA_FORMAT_UNKNOWN;

	uin_t uin = (uin_t)getDword(pai->hContact, GG_KEY_UIN, 0);
	if (!uin) {
		debugLogA("getavatarinfo(): Incoming request for avatar information. No uin found. return GAIR_NOAVATAR");
		return GAIR_NOAVATAR;
	}

	if (!getByte(GG_KEY_ENABLEAVATARS, GG_KEYDEF_ENABLEAVATARS)) {
		debugLogA("getavatarinfo(): Incoming request for avatar information. GG_KEY_ENABLEAVATARS == 0. return GAIR_NOAVATAR");
		return GAIR_NOAVATAR;
	}

	//directly check if contact has protected user avatar set by AVS, and if yes return it as protocol avatar
	DBVARIANT dbv;
	if (!db_get_ts(pai->hContact, "ContactPhoto", "Backup", &dbv)) {
		if ((mir_tstrlen(dbv.ptszVal)>0) && db_get_b(pai->hContact, "ContactPhoto", "Locked", 0)){
			debugLogA("getavatarinfo(): Incoming request for avatar information. Contact has assigned Locked ContactPhoto. return GAIR_SUCCESS");
			_tcscpy_s(pai->filename, _countof(pai->filename) ,dbv.ptszVal);
			pai->format = ProtoGetAvatarFormat(pai->filename);
			db_free(&dbv);
			return GAIR_SUCCESS;
		}
		db_free(&dbv);
	}

	if (!getByte(pai->hContact, GG_KEY_AVATARREQUESTED, GG_KEYDEF_AVATARREQUESTED)) {
		requestAvatarInfo(pai->hContact, 1);
		if ((wParam & GAIF_FORCE) != 0) {
			debugLogA("getavatarinfo(): Incoming request for avatar information. uin=%d. requestAvatarInfo() fired. return GAIR_WAITFOR", uin);
			return GAIR_WAITFOR;
		} else {
			debugLogA("getavatarinfo(): Incoming request for avatar information. uin=%d. requestAvatarInfo() fired. return GAIR_NOAVATAR", uin);
			return GAIR_NOAVATAR;
		}
	}

	pai->format = getByte(pai->hContact, GG_KEY_AVATARTYPE, GG_KEYDEF_AVATARTYPE);

	ptrA AvatarHash(NULL);
	ptrA AvatarURL( getStringA(pai->hContact, GG_KEY_AVATARURL));
	ptrA AvatarTs( getStringA(pai->hContact, GG_KEY_AVATARTS));
	if (AvatarURL != NULL && AvatarTs != NULL) {
		char *AvatarName = strrchr(AvatarURL, '/');
		AvatarName++;
		char AvatarNameWithTS[128];
		mir_snprintf(AvatarNameWithTS, "%s%s", AvatarName, AvatarTs);
		AvatarHash = gg_avatarhash(AvatarNameWithTS);
	}

	ptrA AvatarSavedHash( getStringA(pai->hContact, GG_KEY_AVATARHASH));
	if (AvatarHash != NULL && AvatarSavedHash != NULL) {
		getAvatarFilename(pai->hContact, pai->filename, _countof(pai->filename));
		if (!mir_strcmp(AvatarHash, AvatarSavedHash)) {
			if (_taccess(pai->filename, 0) == 0){
				debugLogA("getavatarinfo(): Incoming request for avatar information. uin=%d. Avatar hash unchanged. return GAIR_SUCCESS", uin);
				return GAIR_SUCCESS;
			}

			requestAvatarTransfer(pai->hContact, AvatarURL);
			debugLog(_T("getavatarinfo(): Incoming request for avatar information. uin=%d. Avatar hash unchanged but file %s does not exist. errno=%d: %s. requestAvatarTransfer() fired. return GAIR_WAITFOR"), uin, pai->filename, errno, strerror(errno));
			return GAIR_WAITFOR;
		}
		if ((wParam & GAIF_FORCE) != 0) {
			if (_tremove(pai->filename) != 0){
				debugLog(_T("getavatarinfo(): refresh. _tremove 1 file %s error. errno=%d: %s"), pai->filename, errno, strerror(errno));
				TCHAR error[512];
				mir_sntprintf(error, TranslateT("Cannot remove old avatar file before refresh. ERROR: %d: %s\n%s"), errno, _tcserror(errno), pai->filename);
				showpopup(m_tszUserName, error, GG_POPUP_ERROR);
			}
			setString(pai->hContact, GG_KEY_AVATARHASH, AvatarHash);
			requestAvatarTransfer(pai->hContact, AvatarURL);
			debugLogA("getavatarinfo(): Incoming request for avatar information. uin=%d. Avatar hash changed, requestAvatarTransfer() fired. return GAIR_WAITFOR", uin);
			return GAIR_WAITFOR;
		}
	}
	else if ((wParam & GAIF_FORCE) != 0) {
		if (AvatarHash == NULL && AvatarSavedHash != NULL) {
			getAvatarFilename(pai->hContact, pai->filename, _countof(pai->filename));
			if (_tremove(pai->filename) != 0){
				debugLog(_T("getavatarinfo(): delete. _tremove file %s error. errno=%d: %s"), pai->filename, errno, strerror(errno));
				TCHAR error[512];
				mir_sntprintf(error, TranslateT("Cannot remove old avatar file. ERROR: %d: %s\n%s"), errno, _tcserror(errno), pai->filename);
				showpopup(m_tszUserName, error, GG_POPUP_ERROR);
			}
			delSetting(pai->hContact, GG_KEY_AVATARHASH);
			delSetting(pai->hContact, GG_KEY_AVATARURL);
			delSetting(pai->hContact, GG_KEY_AVATARTYPE);
			debugLogA("getavatarinfo(): Incoming request for avatar information. Contact %d deleted avatar. return GAIR_NOAVATAR", uin);
		}
		else if (AvatarHash != NULL && AvatarSavedHash == NULL) {
			setString(pai->hContact, GG_KEY_AVATARHASH, AvatarHash);
			requestAvatarTransfer(pai->hContact, AvatarURL);
			debugLogA("getavatarinfo(): Incoming request for avatar information. Contact %d set avatar. requestAvatarTransfer() fired. return GAIR_WAITFOR", uin);
			return GAIR_WAITFOR;
		}
		else debugLogA("getavatarinfo(): Incoming request for avatar information. uin=%d. AvatarHash==AvatarSavedHash==NULL, with GAIF_FORCE param. return GAIR_NOAVATAR", uin);
	}
	else debugLogA("getavatarinfo(): Incoming request for avatar information. uin=%d. AvatarHash==null or AvatarSavedHash==null, but no GAIF_FORCE param. return GAIR_NOAVATAR", uin);

	return GAIR_NOAVATAR;
}
Exemplo n.º 17
0
void CSametimeProto::ImportContactsFromList(mwSametimeList* user_list, bool temporary)
{
	debugLog(_T("CSametimeProto::ImportContactsFromList() start"));
	// add contacts
	mwSametimeGroup* stgroup;
	mwSametimeUser* stuser;
	GList *gl, *gtl, *ul, *utl;
	const char* group_name;
	const char* group_alias;
	mwSametimeGroupType group_type;
	bool group_open;

	gl = gtl = mwSametimeList_getGroups(user_list);
	for (; gl; gl = gl->next) {
		char buff[256];
		stgroup = (mwSametimeGroup*)gl->data;

		group_name = mwSametimeGroup_getName(stgroup);
		group_alias = mwSametimeGroup_getAlias(stgroup);
		if (!group_alias) group_alias = group_name;

		group_type = mwSametimeGroup_getType(stgroup);
		group_open = (mwSametimeGroup_isOpen(stgroup) != 0);

		mir_snprintf(buff, "GN_%s", group_alias);
		db_set_utf(0, szProtoGroups, buff, group_name);
		mir_snprintf(buff, "GT_%s", group_alias);
		db_set_b(0, szProtoGroups, buff, (BYTE)group_type);
		mir_snprintf(buff, "GO_%s", group_alias);
		db_set_b(0, szProtoGroups, buff, (BYTE)(group_open ? 1 : 0));

		// inverse mapping
		mir_snprintf(buff, "GA_%s", group_name);
		db_set_utf(0, szProtoGroups, buff, group_alias);

		AddGroup(group_alias, group_open);

		if (group_type == mwSametimeGroup_DYNAMIC) {
			mwAwareIdBlock id_block;
			id_block.type = mwAware_GROUP;
			id_block.user = (char*)group_name;
			id_block.community = 0;

			GList* gl = g_list_prepend(NULL, &id_block);
			mwAwareList_addAware(aware_list, gl);
			g_list_free(gl);
		}

		ul = utl = mwSametimeGroup_getUsers(stgroup);
		for (; ul; ul = ul->next) {
			stuser = (mwSametimeUser*)ul->data;
			MCONTACT hContact = AddContact(stuser, temporary);
			if (hContact && group_alias && mir_strcmp(group_alias, Translate("None")) != 0 && mir_strcmp(group_alias, "MetaContacts Hidden Group") != 0) {
				SetContactGroup(hContact, group_alias);
				// mark contact as belonging to dynamic group
			}
		}
		g_list_free(utl);
	}
	g_list_free(gtl);
}
Exemplo n.º 18
0
int GGPROTO::gc_event(WPARAM, LPARAM lParam)
{
	GCHOOK *gch = (GCHOOK *)lParam;
	GGGC *chat = NULL;
	uin_t uin;

	// Check if we got our protocol, and fields are set
	if (!gch
		|| !gch->pDest
		|| !gch->pDest->ptszID
		|| !gch->pDest->pszModule
		|| mir_strcmpi(gch->pDest->pszModule, m_szModuleName)
		|| !(uin = getDword(GG_KEY_UIN, 0))
		|| !(chat = gc_lookup(gch->pDest->ptszID)))
		return 0;

	// Window terminated (Miranda exit)
	if (gch->pDest->iType == SESSION_TERMINATE)
	{
		debugLog(_T("gc_event(): Terminating chat %x, id %s from chat window..."), chat, gch->pDest->ptszID);
		// Destroy chat entry
		free(chat->recipients);
		list_remove(&chats, chat, 1);

		// Remove contact from contact list (duh!) should be done by chat.dll !!
		for (MCONTACT hContact = db_find_first(); hContact; ) {
			MCONTACT hNext = db_find_next(hContact);
			DBVARIANT dbv;
			if (!getTString(hContact, "ChatRoomID", &dbv)) {
				if (dbv.ptszVal && !mir_tstrcmp(gch->pDest->ptszID, dbv.ptszVal))
					CallService(MS_DB_CONTACT_DELETE, hContact, 0);
				db_free(&dbv);
			}
			hContact = hNext;
		}
		return 1;
	}

	// Message typed / send only if online
	if (isonline() && (gch->pDest->iType == GC_USER_MESSAGE) && gch->ptszText) {
		TCHAR id[32];
		UIN2IDT(uin, id);
		DBVARIANT dbv;

		GCDEST gcd = { m_szModuleName, gch->pDest->ptszID, GC_EVENT_MESSAGE };
		GCEVENT gce = { sizeof(gce), &gcd };
		gce.ptszUID = id;
		gce.ptszText = gch->ptszText;
		TCHAR* nickT;
		if (!getTString(GG_KEY_NICK, &dbv)){
			nickT = mir_tstrdup(dbv.ptszVal);
			db_free(&dbv);
		}
		else nickT = mir_tstrdup(TranslateT("Me"));
		gce.ptszNick = nickT;

		// Get rid of CRLF at back
		int lc = (int)mir_tstrlen(gch->ptszText) - 1;
		while(lc >= 0 && (gch->ptszText[lc] == '\n' || gch->ptszText[lc] == '\r'))
			gch->ptszText[lc --] = 0;

		gce.time = time(NULL);
		gce.bIsMe = 1;
		gce.dwFlags = GCEF_ADDTOLOG;
		debugLog(_T("gc_event(): Sending conference message to room %s, \"%s\"."), gch->pDest->ptszID, gch->ptszText);
		CallServiceSync(MS_GC_EVENT, 0, (LPARAM)&gce);
		mir_free(nickT);
		
		T2Utf pszText_utf8(gch->ptszText);
		gg_EnterCriticalSection(&sess_mutex, "gc_event", 57, "sess_mutex", 1);
		gg_send_message_confer(sess, GG_CLASS_CHAT, chat->recipients_count, chat->recipients, pszText_utf8);
		gg_LeaveCriticalSection(&sess_mutex, "gc_event", 57, 1, "sess_mutex", 1);
		return 1;
	}

	// Privmessage selected
	if (gch->pDest->iType == GC_USER_PRIVMESS)
	{
		MCONTACT hContact = NULL;
		if ((uin = _ttoi(gch->ptszUID)) && (hContact = getcontact(uin, 1, 0, NULL)))
			CallService(MS_MSG_SENDMESSAGE, hContact, 0);
	}
	debugLog(_T("gc_event(): Unhandled event %d, chat %x, uin %d, text \"%s\"."), gch->pDest->iType, chat, uin, gch->ptszText);

	return 0;
}
Exemplo n.º 19
0
MCONTACT CSametimeProto::AddContact(mwSametimeUser* user, bool temporary)
{
	debugLog(_T("CSametimeProto::AddContact() start"));
	const char* id = mwSametimeUser_getUser(user);
	const char* name = mwSametimeUser_getShortName(user);
	const char* nick = mwSametimeUser_getAlias(user);
	//const char* nick = mwSametimeUser_getShortName(user);
	mwSametimeUserType type = mwSametimeUser_getType(user);

	MCONTACT hContact = FindContactByUserId(id);
	bool new_contact = false;
	if (!hContact) {
		hContact = (MCONTACT)CallService(MS_DB_CONTACT_ADD, 0, 0);
		if (!hContact) {
			debugLog(_T("AddContact(): Failed to create Sametime contact"));
			return NULL; ///TODO error handling
		}
		if (Proto_AddToContact(hContact, m_szModuleName) != 0) {
			CallService(MS_DB_CONTACT_DELETE, (WPARAM)hContact, 0);
			debugLog(_T("AddContact(): Failed to register Sametime contact"));
			return NULL; ///TODO error handling
		}
		new_contact = true;
	}
	else if (!temporary) {
		db_unset(hContact, "CList", "NotOnList");
		db_unset(hContact, "CList", "Hidden");
	}


	// add to miranda
	if (new_contact) db_set_utf(hContact, m_szModuleName, "stid", id);

	if (name && mir_strlen(name))
		db_set_utf(hContact, m_szModuleName, "Name", name);

	if (nick && mir_strlen(nick)) {
		db_set_utf(hContact, m_szModuleName, "Nick", nick);
	}
	else if (name && mir_strlen(name)) {
		db_set_utf(hContact, m_szModuleName, "Nick", name);
	}
	else {
		db_set_utf(hContact, m_szModuleName, "Nick", id);
	}

	db_set_b(hContact, m_szModuleName, "type", (BYTE)type);

	if (new_contact) {
		//add to our awareness list
		mwAwareIdBlock id_block;
		if (GetAwareIdFromContact(hContact, &id_block)) {
			GList* gl = g_list_prepend(NULL, &id_block);
			mwAwareList_addAware(aware_list, gl);
			g_list_free(gl);
			free(id_block.user);
		}
	}

	if (temporary) {
		db_set_b(hContact, "CList", "NotOnList", 1);
		db_set_b(hContact, "CList", "Hidden", 1);
	}
	else {
		db_unset(hContact, "CList", "NotOnList");
		db_unset(hContact, "CList", "Hidden");
	}

	return hContact;
}
Exemplo n.º 20
0
////////////////////////////////////////////////////////////////////////////////
// This is main groupchat initialization routine
//
TCHAR* GGPROTO::gc_getchat(uin_t sender, uin_t *recipients, int recipients_count)
{
	list_t l;
	GGGC *chat;
	TCHAR id[32];
	uin_t uin;
	DBVARIANT dbv;
	GCDEST gcd = { m_szModuleName, 0, GC_EVENT_ADDGROUP };
	GCEVENT gce = { sizeof(gce), &gcd };

	debugLogA("gc_getchat(): Count %d.", recipients_count);
	if (!recipients) return NULL;

	// Look for existing chat
	for(l = chats; l; l = l->next)
	{
		chat = (GGGC *)l->data;
		if (!chat) continue;

		if (chat->recipients_count == recipients_count + (sender ? 1 : 0))
		{
			int i, j, found = 0, sok = (sender == 0);
			if (!sok) {
				for (i = 0; i < chat->recipients_count; i++) {
					if (sender == chat->recipients[i])
					{
						sok = 1;
						break;
					}
				}
			}
			if (sok)
				for(i = 0; i < chat->recipients_count; i++)
					for(j = 0; j < recipients_count; j++)
						if (recipients[j] == chat->recipients[i]) found++;
			// Found all recipients
			if (found == recipients_count)
			{
				if (chat->ignore)
					debugLog(_T("gc_getchat(): Ignoring existing id %s, size %d."), chat->id, chat->recipients_count);
				else
					debugLog(_T("gc_getchat(): Returning existing id %s, size %d."), chat->id, chat->recipients_count);
				return !(chat->ignore) ? chat->id : NULL;
			}
		}
	}

	// Make new uin list to chat mapping
	chat = (GGGC *)malloc(sizeof(GGGC));
	UIN2IDT(gc_id ++, chat->id);
	chat->ignore = FALSE;

	// Check groupchat policy (new) / only for incoming
	if (sender)
	{
		int unknown = (getcontact(sender, 0, 0, NULL) == NULL),
			unknownSender = unknown;
		for(int i = 0; i < recipients_count; i++)
			if (!getcontact(recipients[i], 0, 0, NULL))
				unknown ++;
		if ((getWord(GG_KEY_GC_POLICY_DEFAULT, GG_KEYDEF_GC_POLICY_DEFAULT) == 2) ||
		   (getWord(GG_KEY_GC_POLICY_TOTAL, GG_KEYDEF_GC_POLICY_TOTAL) == 2 &&
			recipients_count >= getWord(GG_KEY_GC_COUNT_TOTAL, GG_KEYDEF_GC_COUNT_TOTAL)) ||
		   (getWord(GG_KEY_GC_POLICY_UNKNOWN, GG_KEYDEF_GC_POLICY_UNKNOWN) == 2 &&
			unknown >= getWord(GG_KEY_GC_COUNT_UNKNOWN, GG_KEYDEF_GC_COUNT_UNKNOWN)))
			chat->ignore = TRUE;
		if (!chat->ignore && ((getWord(GG_KEY_GC_POLICY_DEFAULT, GG_KEYDEF_GC_POLICY_DEFAULT) == 1) ||
		   (getWord(GG_KEY_GC_POLICY_TOTAL, GG_KEYDEF_GC_POLICY_TOTAL) == 1 &&
			recipients_count >= getWord(GG_KEY_GC_COUNT_TOTAL, GG_KEYDEF_GC_COUNT_TOTAL)) ||
		   (getWord(GG_KEY_GC_POLICY_UNKNOWN, GG_KEYDEF_GC_POLICY_UNKNOWN) == 1 &&
			unknown >= getWord(GG_KEY_GC_COUNT_UNKNOWN, GG_KEYDEF_GC_COUNT_UNKNOWN))))
		{
			TCHAR *senderName = unknownSender ?
				TranslateT("Unknown") : pcli->pfnGetContactDisplayName(getcontact(sender, 0, 0, NULL), 0);
			TCHAR error[256];
			mir_sntprintf(error, TranslateT("%s has initiated conference with %d participants (%d unknowns).\nDo you want to participate?"),
				senderName, recipients_count + 1, unknown);
			chat->ignore = MessageBox(NULL, error, m_tszUserName, MB_OKCANCEL | MB_ICONEXCLAMATION) != IDOK;
		}
		if (chat->ignore)
		{
			// Copy recipient list
			chat->recipients_count = recipients_count + 1;
			chat->recipients = (uin_t *)calloc(chat->recipients_count, sizeof(uin_t));
			int i = 0;
			for(; i < recipients_count; i++)
				chat->recipients[i] = recipients[i];
			if (sender) chat->recipients[i] = sender;
			debugLog(_T("gc_getchat(): Ignoring new chat %s, count %d."), chat->id, chat->recipients_count);
			list_add(&chats, chat, 0);
			return NULL;
		}
	}

	// Create new chat window
	TCHAR status[256];
	TCHAR *senderName;
	if (sender)
	{
		senderName = pcli->pfnGetContactDisplayName(getcontact(sender, 1, 0, NULL), 0);
		mir_sntprintf(status, TranslateT("%s initiated the conference.") , senderName);
	}
	else
	{
		senderName = NULL;
		mir_sntprintf(status, TranslateT("This is my own conference."));
	}

	GCSESSION gcwindow = { sizeof(gcwindow) };
	gcwindow.iType = GCW_CHATROOM;
	gcwindow.pszModule = m_szModuleName;
	gcwindow.ptszName = sender ? senderName : TranslateT("Conference");
	gcwindow.ptszID = chat->id;
	gcwindow.dwItemData = (UINT_PTR)chat;
	gcwindow.ptszStatusbarText = status;

	// Here we put nice new hash sign
	TCHAR *name = (TCHAR*)calloc(mir_tstrlen(gcwindow.ptszName) + 2, sizeof(TCHAR));
	*name = '#'; mir_tstrcpy(name + 1, gcwindow.ptszName);
	gcwindow.ptszName = name;

	// Create new room
	if (CallServiceSync(MS_GC_NEWSESSION, 0, (LPARAM) &gcwindow)) {
		debugLog(_T("gc_getchat(): Cannot create new chat window %s."), chat->id);
		free(name);
		free(chat);
		return NULL;
	}
	free(name);

	gcd.ptszID = chat->id;
	gce.ptszUID = id;
	gce.dwFlags = GCEF_ADDTOLOG;
	gce.time = 0;

	// Add normal group
	gce.ptszStatus = TranslateT("Participants");
	CallServiceSync(MS_GC_EVENT, 0, (LPARAM)&gce);
	gcd.iType = GC_EVENT_JOIN;

	// Add myself
	if (uin = getDword(GG_KEY_UIN, 0))
	{
		UIN2IDT(uin, id);

		TCHAR* nickT;
		if (!getTString(GG_KEY_NICK, &dbv)) {
			nickT = mir_tstrdup(dbv.ptszVal);
			db_free(&dbv);
		} else {
			nickT = mir_tstrdup(TranslateT("Me"));
		}
		gce.ptszNick = nickT;

		gce.bIsMe = 1;
		CallServiceSync(MS_GC_EVENT, 0, (LPARAM)&gce);
		mir_free(nickT);
		debugLog(_T("gc_getchat(): Myself %s: %s (%s) to the list..."), gce.ptszUID, gce.ptszNick, gce.ptszStatus);
	}
	else debugLogA("gc_getchat(): Myself adding failed with uin %d !!!", uin);

	// Copy recipient list
	chat->recipients_count = recipients_count + (sender ? 1 : 0);
	chat->recipients = (uin_t *)calloc(chat->recipients_count, sizeof(uin_t));
	int i;
	for(i = 0; i < recipients_count; i++)
		chat->recipients[i] = recipients[i];
	if (sender) chat->recipients[i] = sender;

	// Add contacts
	for(i = 0; i < chat->recipients_count; i++) {
		MCONTACT hContact = getcontact(chat->recipients[i], 1, 0, NULL);
		UIN2IDT(chat->recipients[i], id);
		if (hContact && (name = pcli->pfnGetContactDisplayName(hContact, 0)) != NULL)
			gce.ptszNick = name;
		else
			gce.ptszNick = TranslateT("'Unknown'");
		gce.bIsMe = 0;
		gce.dwFlags = 0;
		debugLog(_T("gc_getchat(): Added %s: %s (%s) to the list..."), gce.ptszUID, gce.ptszNick, gce.ptszStatus);
		CallServiceSync(MS_GC_EVENT, 0, (LPARAM)&gce);
	}
	gcd.iType = GC_EVENT_CONTROL;
	CallServiceSync(MS_GC_EVENT, SESSION_INITDONE, (LPARAM)&gce);
	CallServiceSync(MS_GC_EVENT, SESSION_ONLINE, (LPARAM)&gce);

	debugLog(_T("gc_getchat(): Returning new chat window %s, count %d."), chat->id, chat->recipients_count);
	list_add(&chats, chat, 0);
	return chat->id;
}
Exemplo n.º 21
0
BOOL CJabberProto::OnIqRequestOOB(HXML, CJabberIqInfo *pInfo)
{
	if (!pInfo->GetFrom() || !pInfo->GetHContact())
		return TRUE;

	HXML n = XmlGetChild(pInfo->GetChildNode(), "url");
	if (!n || !XmlGetText(n))
		return TRUE;

	if (m_options.BsOnlyIBB) {
		// reject
		XmlNodeIq iq(_T("error"), pInfo);
		HXML e = XmlAddChild(iq, _T("error"), _T("File transfer refused")); XmlAddAttr(e, _T("code"), 406);
		m_ThreadInfo->send(iq);
		return TRUE;
	}

	filetransfer *ft = new filetransfer(this);
	ft->std.totalFiles = 1;
	ft->jid = mir_tstrdup(pInfo->GetFrom());
	ft->std.hContact = pInfo->GetHContact();
	ft->type = FT_OOB;
	ft->httpHostName = NULL;
	ft->httpPort = 80;
	ft->httpPath = NULL;

	// Parse the URL
	TCHAR *str = (TCHAR*)XmlGetText(n);	// URL of the file to get
	if (!_tcsnicmp(str, _T("http://"), 7)) {
		TCHAR *p = str + 7, *q;
		if ((q = _tcschr(p, '/')) != NULL) {
			TCHAR text[1024];
			if (q - p < _countof(text)) {
				_tcsncpy_s(text, p, q - p);
				text[q - p] = '\0';
				if ((p = _tcschr(text, ':')) != NULL) {
					ft->httpPort = (WORD)_ttoi(p + 1);
					*p = '\0';
				}
				ft->httpHostName = mir_t2a(text);
			}
		}
	}

	if (pInfo->GetIdStr())
		ft->szId = JabberId2string(pInfo->GetIqId());

	if (ft->httpHostName && ft->httpPath) {
		TCHAR *desc = NULL;

		debugLogA("Host=%s Port=%d Path=%s", ft->httpHostName, ft->httpPort, ft->httpPath);
		if ((n = XmlGetChild(pInfo->GetChildNode(), "desc")) != NULL)
			desc = (TCHAR*)XmlGetText(n);

		TCHAR *str2;
		debugLog(_T("description = %s"), desc);
		if ((str2 = _tcsrchr(ft->httpPath, '/')) != NULL)
			str2++;
		else
			str2 = ft->httpPath;
		str2 = mir_tstrdup(str2);
		JabberHttpUrlDecode(str2);

		PROTORECVFILET pre;
		pre.dwFlags = PRFF_TCHAR;
		pre.timestamp = time(NULL);
		pre.descr.t = desc;
		pre.files.t = &str2;
		pre.fileCount = 1;
		pre.lParam = (LPARAM)ft;
		ProtoChainRecvFile(ft->std.hContact, &pre);
		mir_free(str2);
	}
	else {
		// reject
		XmlNodeIq iq(_T("error"), pInfo);
		HXML e = XmlAddChild(iq, _T("error"), _T("File transfer refused")); XmlAddAttr(e, _T("code"), 406);
		m_ThreadInfo->send(iq);
		delete ft;
	}
	return TRUE;
}
Exemplo n.º 22
0
int CJabberProto::FileSendParse(JABBER_SOCKET s, filetransfer *ft, char* buffer, int datalen)
{
	char* p, *q, *t, *eob;
	char* str;
	int num;
	int currentFile;
	int fileId;
	int numRead;

	eob = buffer + datalen;
	p = buffer;
	num = 0;
	while (ft->state == FT_CONNECTING || ft->state == FT_INITIALIZING) {
		for (q = p; q + 1 < eob && (*q != '\r' || *(q + 1) != '\n'); q++);
		if (q + 1 >= eob)
			break;
		if ((str = (char*)mir_alloc(q - p + 1)) == NULL) {
			ft->state = FT_ERROR;
			break;
		}
		strncpy_s(str, q - p, p, _TRUNCATE);
		str[q - p] = '\0';
		debugLogA("FT Got: %s", str);
		if (ft->state == FT_CONNECTING) {
			// looking for "GET filename.ext HTTP/1.1"
			if (!strncmp(str, "GET ", 4)) {
				for (t = str + 4; *t != '\0' && *t != ' '; t++);
				*t = '\0';
				for (t = str + 4; *t != '\0' && *t == '/'; t++);
				ft->httpPath = mir_a2t(t);
				JabberHttpUrlDecode(ft->httpPath);
				ft->state = FT_INITIALIZING;
				debugLogA("Change to FT_INITIALIZING");
			}
		}
		else {	// FT_INITIALIZING
			if (str[0] == '\0') {
				struct _stati64 statbuf;

				mir_free(str);
				num += 2;

				currentFile = ft->std.currentFileNumber;
				TCHAR *t = _tcsrchr(ft->std.ptszFiles[currentFile], '\\');
				if (t != NULL)
					t++;
				else
					t = ft->std.ptszFiles[currentFile];

				if (ft->httpPath == NULL || mir_tstrcmp(ft->httpPath, t)) {
					if (ft->httpPath == NULL)
						debugLogA("Requested file name does not matched (httpPath == NULL)");
					else
						debugLog(_T("Requested file name does not matched ('%s' vs. '%s')"), ft->httpPath, t);
					ft->state = FT_ERROR;
					break;
				}
				debugLog(_T("Sending [%s]"), ft->std.ptszFiles[currentFile]);
				_tstati64(ft->std.ptszFiles[currentFile], &statbuf);	// file size in statbuf.st_size
				if ((fileId = _topen(ft->std.ptszFiles[currentFile], _O_BINARY | _O_RDONLY)) < 0) {
					debugLogA("File cannot be opened");
					ft->state = FT_ERROR;
					mir_free(ft->httpPath);
					ft->httpPath = NULL;
					break;
				}

				char fileBuffer[2048];
				int bytes = mir_snprintf(fileBuffer, _countof(fileBuffer), "HTTP/1.1 200 OK\r\nContent-Length: %I64u\r\n\r\n", statbuf.st_size);
				WsSend(s, fileBuffer, bytes, MSG_DUMPASTEXT);

				ft->std.flags |= PFTS_SENDING;
				ft->std.currentFileProgress = 0;
				debugLogA("Sending file data...");

				while ((numRead = _read(fileId, fileBuffer, 2048)) > 0) {
					if (Netlib_Send(s, fileBuffer, numRead, 0) != numRead) {
						ft->state = FT_ERROR;
						break;
					}
					ft->std.currentFileProgress += numRead;
					ft->std.totalProgress += numRead;
					ProtoBroadcastAck(ft->std.hContact, ACKTYPE_FILE, ACKRESULT_DATA, ft, (LPARAM)&ft->std);
				}
				_close(fileId);
				if (ft->state != FT_ERROR)
					ft->state = FT_DONE;
				debugLogA("Finishing this file...");
				mir_free(ft->httpPath);
				ft->httpPath = NULL;
				break;
		}	}

		mir_free(str);
		q += 2;
		num += (q-p);
		p = q;
	}

	return num;
}
shared_ptr<PartialGtGenerator> GtGenerator::reducePermutation(shared_ptr<PartialGtGenerator> partialGenerator,
    uint n, Scheme* scheme, Scheme::iterator* targetIter)
{
    debugLog("GtGenerator::reducePermutation()-dump-transposition-count", [&](ostream& out)->void
    {
        const Permutation& perm = partialGenerator->getPermutation();
        uint transpCount = 0;
        static uint stepCount = 0;

        for (auto cycle : perm)
        {
            uint elementCount = cycle->length();
            transpCount += elementCount - 1;
        }

        out << "Step " << ++stepCount << ", transposition count = " << transpCount << '\n';
    });

    shared_ptr<PartialGtGenerator> restGenerator = 0;

    bool isLeftAndRightMultiplicationDiffers = partialGenerator->isLeftAndRightMultiplicationDiffers();
    if(isLeftAndRightMultiplicationDiffers)
    {
        // get left choice
        Permutation leftMultipliedPermutation  = partialGenerator->getResidualPermutation(true);
        shared_ptr<PartialGtGenerator> leftGenerator(new PartialGtGenerator());

        leftGenerator->setPermutation(leftMultipliedPermutation, n);
        leftGenerator->prepareForGeneration();

        // get right choice
        Permutation rightMultipliedPermutation = partialGenerator->getResidualPermutation(false);
        shared_ptr<PartialGtGenerator> rightGenerator(new PartialGtGenerator());

        rightGenerator->setPermutation(rightMultipliedPermutation, n);
        rightGenerator->prepareForGeneration();

        debugLog("GtGenerator::reducePermutation()-dump-left-right", [&](ostream& out)->void
        {
            out << "============================\n";
            out << "Left:\n" << leftMultipliedPermutation << '\n';
            out << "\nRight:\n" << rightMultipliedPermutation << '\n' << endl;
        });

        // compare left and right choices and choose the best
        PartialResultParams leftPartialResultParams  =  leftGenerator->getPartialResultParams();
        PartialResultParams rightPartialResultParams = rightGenerator->getPartialResultParams();

        bool isLeftBetter = leftPartialResultParams.isBetterThan(rightPartialResultParams);

        debugBehavior("GtGenerator::reducePermutation()-right-always-better", [&]()->void
        {
            isLeftBetter = false;
        });
        
        if(isLeftBetter)
        {
            debugLog("GtGenerator::reducePermutation()-dump-left", [&](ostream& out)->void
            {
                out << "Left:\n" << leftMultipliedPermutation << endl;
            });

            implementPartialResult(*partialGenerator, true, scheme, targetIter);
            restGenerator = leftGenerator;
        }
        else
        {
            debugLog("GtGenerator::reducePermutation()-dump-right", [&](ostream& out)->void
            {
                out << "Right:\n" << rightMultipliedPermutation << endl;
            });

            implementPartialResult(*partialGenerator, false, scheme, targetIter);
            restGenerator = rightGenerator;
        }
    }
    else
    {
        implementPartialResult(*partialGenerator, true, scheme, targetIter);

        // get residual permutation and iterate on it
        Permutation residualPermutation = partialGenerator->getResidualPermutation(true);
        if(!residualPermutation.isEmpty())
        {
            debugLog("GtGenerator::reducePermutation()-dump-residual", [&](ostream& out)->void
            {
                out << "Residual:\n" << residualPermutation << endl;
            });

            restGenerator = shared_ptr<PartialGtGenerator>(new PartialGtGenerator());
            restGenerator->setPermutation(residualPermutation, n);
            restGenerator->prepareForGeneration();
        }
    }

    return restGenerator;
}
Exemplo n.º 24
0
void CSametimeProto::DeinitSessionMenu()
{
	debugLog(_T("CSametimeProto::DeinitSessionMenu()"));
	CallService(MO_REMOVEMENUITEM, (WPARAM)hSessionAnnounceMenuItem, 0);
}
Exemplo n.º 25
0
uint8_t rxChar(uint8_t channel) {
  uint8_t x;
  uint8_t parity_bit = 0;
  uint8_t rx_parity_bit = 0;
  uint8_t data = 0x00;
  uint8_t bitplace = 0x1;

  /*
   * Check for a handshake initialization.  Timeout if necessary.
   */
  rx_timeout = RX_TIMEOUT_RELOAD;
  while(pollClockLine(channel)) {
    if(rx_timeout-- == 0) {
      failed_to_rx = TRUE;
      return 0;
    }
  }
   
  //topobo tried to receive a msg from another active that was connected
  debugLog(INIT_RX);

  /*
   * Return the handshake and give the transmitter time to respond.
   */
  setDataLine(channel, 0);
  delay_us(BIT_LOW_TIME);

  /*
   * Relinquish control of the data line by setting it as an input.
   */
  releaseDataLine(channel);

  /*
   * Look for the first bit.  Timeout if necessary.
   */
  rx_timeout = RX_TIMEOUT_RELOAD;
  while(! pollClockLine(channel)) {
    if(rx_timeout-- == 0) {
      failed_to_rx = TRUE;
      debugLog(NO_FIRST_BIT);
      return 0;
    }
  }
  //uart_putchar('h');
  for(x = 0; x < 8; x++) {
    //uart_putchar('0'+x);
    /*
     * Watch the clock line for a sign that a bit is ready
     * to be read.  Timeout if necessary.
     */
    rx_timeout = RX_TIMEOUT_RELOAD;
    while(pollClockLine(channel)) {
      if(rx_timeout-- == 0) {
	failed_to_rx = TRUE;
	debugLog(NO_START_OF_BIT);
	return 0;
      }
    }
    /*
     * Once the bit is ready, read it.
     */
    if(pollDataLine(channel)) {
      data |= bitplace;
      parity_bit ^= 0x01;
    }
    bitplace <<= 1;

    /*
     * Once a bit has been received, wait for the
     * the transmitter to declare the end of the bit.
     * Timeout if necessary.
     */
    rx_timeout = RX_TIMEOUT_RELOAD;
    // meme : something is happening here.
    while(! pollClockLine(channel)) {
      if(rx_timeout-- == 0) {
	failed_to_rx = TRUE;
	debugLog(NO_END_OF_BIT);
	return 0;
      }
    }
  }

  /*
   * Read in the parity bit.
   */
  rx_timeout = RX_TIMEOUT_RELOAD;
  while(pollClockLine(channel)) {  // Wait until bit is ready to read.
    if(rx_timeout-- == 0) {
      failed_to_rx = TRUE;
      debugLog(NO_PARITY_BIT);
      return 0;
    }
  }

  // Read the bit and store it. (initially = 0)
  if(pollDataLine(channel)) { 
    rx_parity_bit = 1;
  }

  rx_timeout = RX_TIMEOUT_RELOAD;
  while(!pollClockLine(channel)) {         // Wait for transmitter to finish.
    if(rx_timeout-- == 0) {
      failed_to_rx = TRUE;
      debugLog(NO_END_OF_MESSAGE);
      return 0;
    }
  }
  rx_parity_error = (rx_parity_bit != parity_bit);   // Check if the parity bits match.

  /*
   * Acknowledge receipt of the byte just received and
   * indicate whether the byte had a parity error or not.
   */
  setClockLine(channel, 1); //to avoid capacitive noise from data_line

  if (rx_parity_error) {
    rx_parity_errors++;
    setClockLine(channel, 0);
    debugLog(PARITY_ERROR);
  }
  setDataLine(channel, 0);    //using data line to clock the parity error
  delay_us(BIT_LOW_TIME);

  /*
   * Relinquish control of the comm lines by setting them as an input.
   */
  releaseDataLine(channel);
  releaseClockLine(channel);

  // update the debug log to acknowledge a successful tx
  debugLog(SUCCESSFUL_RX);

  /*
   * Correctly received a byte, now return it.
   */
  failed_to_rx = FALSE;
  return data;
}
Exemplo n.º 26
0
void CSametimeProto::InitCritSection()
{
	debugLog(_T("CSametimeProto::InitCritSection()"));
	InitializeCriticalSection(&session_cs);
}
void AquariaGuiElement::updateMovement(float dt)
{
	//debugLog("in update movement");
	if (hasFocus && isGuiVisible() && canDirMove && canDirMoveGlobal && hasInput())
	{
		//debugLog("has focus");
		/*
		if (alpha.x <= 0 || alphaMod <= 0)
		{
			setFocus(false);
			return;
		}
		*/

		if (guiMoveTimer > 0)
		{
			guiMoveTimer -= dt;
			if (guiMoveTimer < 0) guiMoveTimer = 0;
		}

		if (guiMoveTimer==0)
		{
			Direction dir = DIR_NONE;
			Vector p = core->joystick.position;
			if (!p.isLength2DIn(0.4))
			{
				if (fabsf(p.x) > fabsf(p.y))
				{
					if (p.x > 0)
						dir = DIR_RIGHT;
					else
						dir = DIR_LEFT;
				}
				else
				{
					if (p.y > 0)
						dir = DIR_DOWN;
					else
						dir = DIR_UP;
				}
			}
			else
			{
				StateObject *obj = dsq->getTopStateObject();
				if (obj)
				{
					if (obj->isActing(ACTION_MENULEFT))			dir = DIR_LEFT;
					else if (obj->isActing(ACTION_MENURIGHT))	dir = DIR_RIGHT;
					else if (obj->isActing(ACTION_MENUUP))		dir = DIR_UP;
					else if (obj->isActing(ACTION_MENUDOWN))	dir = DIR_DOWN;
				}
			}

			if (dir == DIR_NONE) return;

			const float moveDelay = 0.2;

			AquariaGuiElement *gui = 0;
			if (dir > DIR_NONE && dir < DIR_MAX)
			{
				gui = dirMove[dir];
				if (gui)
				{
					gui->setFocus(true);
					//this->setFocus(false);

					

					guiMoveTimer = moveDelay;
				}
			}
			
			if (!gui)
			{
				debugLog("updating closest");
				int smallDist = -1, dist = 0;

				AquariaGuiElement *gui = 0, *closest = 0;
				int ch = 64;
				for (GuiElements::iterator i = guiElements.begin(); i != guiElements.end(); i++)
				{
					gui = (*i);
					if (gui != this && gui->isGuiVisible() && gui->canDirMove)
					{
						int go = 0;
						Vector p1 = getGuiPosition();
						Vector p2 = gui->getGuiPosition();

						if (dir == DIR_DOWN)
						{
							if (fabsf(p1.x - p2.x) < ch)
							{
								if (p2.y > p1.y) go = 1;
								p1.x = p2.x = 0;
							}
						}
						else if (dir == DIR_UP)
						{
							if (fabsf(p1.x - p2.x) < ch)
							{
								if (p2.y < p1.y) go = 1;
								p1.x = p2.x = 0;
							}
						}
						else if (dir == DIR_RIGHT)
						{
							if (fabsf(p1.y - p2.y) < ch)
							{
								if (p2.x > p1.x) go = 1;
								p1.y = p2.y = 0;
							}
						}
						else if (dir == DIR_LEFT)
						{
							if (fabsf(p1.y - p2.y) < ch)
							{
								if (p2.x < p1.x) go = 1;
								p1.y = p2.y = 0;
							}
						}
						else
						{
							continue;
						}

						if (go)
						{
							dist = (p1 - p2).getSquaredLength2D();

							if (smallDist == -1 || dist < smallDist)
							{
								closest = gui;
								smallDist = dist;
							}
						}
						else
						{
							continue;
						}
					}
				}

				if (closest)
				{
					closest->setFocus(true);

					guiMoveTimer = moveDelay;
				}
			}
		}
	}
}
Exemplo n.º 28
0
void CSametimeProto::DeinitCritSection()
{
	debugLog(_T("CSametimeProto::DeinitCritSection()"));
	DeleteCriticalSection(&session_cs);
}
Exemplo n.º 29
0
void FrameBuffer::reloadDevice()
{
	debugLog("frameBuffer::reloadDevice");
	init(_w, _h, _fitToScreen);
}
Exemplo n.º 30
0
void CommManager::ConnectedNotify()
{
    SetConfig(1000 * 30, 1000);
    ::InterlockedExchange(&m_bConnected, TRUE);
    debugLog(_T("CONNECTED"));
}