Beispiel #1
0
void
CAudioScrobbler::Handshake()
{
	std::string username="";
	for(unsigned int i = 0; i < Config->getLUsername().length(); i++) {
		username.append(1, tolower(Config->getLUsername().c_str()[i]));
	}
	std::string authtoken(md5sum((char*)"%s%s", username.c_str(), Config->getLPassword().c_str()));

	std::ostringstream query, sig;
	query << "method=auth.getMobileSession&username="******"&authToken=" << authtoken << "&api_key=" << APIKEY;

	sig << "api_key" << APIKEY << "authToken" << authtoken << "methodauth.getMobileSessionusername" << Config->getLUsername() << SECRET;
	std::string sighash(md5sum((char*)"%s", sig.str().c_str()));

	query << "&api_sig=" << sighash;

	OpenURL(ROOTURL, query.str().c_str());

	if(_response.find("<lfm status=\"ok\">") != std::string::npos) {
		size_t start, end;
		start = _response.find("<key>") + 5;
		end = _response.find("</key>");
		_sessionid = _response.substr(start, end-start);
		iprintf("%s%s", "Last.fm handshake successful. SessionID: ", _sessionid.c_str());
		_authed = true;
	}
	else if(_response.find("<lfm status=\"failed\">") != std::string::npos) {
		CheckFailure(_response);
		exit(EXIT_FAILURE);
	}

	CLEANUP();
}
Beispiel #2
0
void * md5sumThreadFunc(void * arg)
{
	ThreadArg * ptarg = (ThreadArg *)arg;
	const char * pathname = ptarg->buf;
	//Database db = *(ptarg->pdb);
	Database db(DBFILENAME);
	printf("************md5sumThreadFunc: %s\n", pathname);   
	string md5str = md5sum(pathname);
	string sizestr = getFilesize(string(pathname));
	cout << "md5sumThreadFunc # filepath: " << pathname << "md5str: " << md5str << "sizestr: " << sizestr << endl;
	
	if (!md5str.empty() && !sizestr.empty())
	{
		std::map<string, string> insertParamMap = {    {"MD5SUM", md5str},
	                                                   {"MD5RAND", "NULL"},
	                                                   {"ABSPATH", pathname},
	                                                   {"SIZE", sizestr} };
		if (db.insert("file", insertParamMap))
        {
			Error::msg("Success: insert new file MD5SUM");
        } else {
           Error::msg("\033[31mDatabase insert error\033[0m");
        }   
	}

	delete ptarg; 
    return(NULL);
}
Beispiel #3
0
string encryptPassword(string password)
{
	string saltedPass = PASSSALT0 + password + PASSSALT1;
	//cout << "***********saltedPass: "******"***********saltedPass: " << saltedPass << endl;
    return saltedPass;     
}
Beispiel #4
0
/*
	Adds the authentication token to the user cache.  The timeout for the
	auth token is based on the type of login as well as (if type=='opac')
	the org location id.
	Returns the event that should be returned to the user.
	Event must be freed
*/
static oilsEvent* oilsAuthHandleLoginOK( jsonObject* userObj, const char* uname,
		const char* type, int orgloc, const char* workstation ) {

	oilsEvent* response;

	long timeout;
	char* wsorg = jsonObjectToSimpleString(oilsFMGetObject(userObj, "ws_ou"));
	if(wsorg) { /* if there is a workstation, use it for the timeout */
		osrfLogDebug( OSRF_LOG_MARK,
				"Auth session trying workstation id %d for auth timeout", atoi(wsorg));
		timeout = oilsAuthGetTimeout( userObj, type, atoi(wsorg) );
		free(wsorg);
	} else {
		osrfLogDebug( OSRF_LOG_MARK,
				"Auth session trying org from param [%d] for auth timeout", orgloc );
		timeout = oilsAuthGetTimeout( userObj, type, orgloc );
	}
	osrfLogDebug(OSRF_LOG_MARK, "Auth session timeout for %s: %ld", uname, timeout );

	char* string = va_list_to_string(
			"%d.%ld.%s", (long) getpid(), time(NULL), uname );
	char* authToken = md5sum(string);
	char* authKey = va_list_to_string(
			"%s%s", OILS_AUTH_CACHE_PRFX, authToken );

	const char* ws = (workstation) ? workstation : "";
	osrfLogActivity(OSRF_LOG_MARK,
		"successful login: username=%s, authtoken=%s, workstation=%s", uname, authToken, ws );

	oilsFMSetString( userObj, "passwd", "" );
	jsonObject* cacheObj = jsonParseFmt( "{\"authtime\": %ld}", timeout );
	jsonObjectSetKey( cacheObj, "userobj", jsonObjectClone(userObj));

	if( !strcmp( type, OILS_AUTH_PERSIST )) {
		// Add entries for endtime and reset_interval, so that we can gracefully
		// extend the session a bit if the user is active toward the end of the 
		// timeout originally specified.
		time_t endtime = time( NULL ) + timeout;
		jsonObjectSetKey( cacheObj, "endtime", jsonNewNumberObject( (double) endtime ) );

		// Reset interval is hard-coded for now, but if we ever want to make it
		// configurable, this is the place to do it:
		jsonObjectSetKey( cacheObj, "reset_interval",
			jsonNewNumberObject( (double) DEFAULT_RESET_INTERVAL ));
	}

	osrfCachePutObject( authKey, cacheObj, (time_t) timeout );
	jsonObjectFree(cacheObj);
	osrfLogInternal(OSRF_LOG_MARK, "oilsAuthHandleLoginOK(): Placed user object into cache");
	jsonObject* payload = jsonParseFmt(
		"{ \"authtoken\": \"%s\", \"authtime\": %ld }", authToken, timeout );

	response = oilsNewEvent2( OSRF_LOG_MARK, OILS_EVENT_SUCCESS, payload );
	free(string); free(authToken); free(authKey);
	jsonObjectFree(payload);

	return response;
}
Beispiel #5
0
/**
 * Returns true if the provided password is correct.
 * Turn the password into the nested md5 hash required of migrated
 * passwords, then check the password in the DB.
 */
static int oilsAuthLoginCheckPassword(int user_id, const char* password) {

    growing_buffer* gb = buffer_init(33); // free me 1
    char* salt = oilsAuthGetSalt(user_id); // free me 2
    char* passhash = md5sum(password); // free me 3

    buffer_add(gb, salt); // gb strdup's internally
    buffer_add(gb, passhash);

    free(salt); // free 2
    free(passhash); // free 3

    // salt + md5(password)
    passhash = buffer_release(gb); // free 1 ; free me 4
    char* finalpass = md5sum(passhash); // free me 5

    free(passhash); // free 4

    jsonObject *arr = jsonNewObjectType(JSON_ARRAY);
    jsonObjectPush(arr, jsonNewObject("actor.verify_passwd"));
    jsonObjectPush(arr, jsonNewNumberObject((long) user_id));
    jsonObjectPush(arr, jsonNewObject("main"));
    jsonObjectPush(arr, jsonNewObject(finalpass));
    jsonObject *params = jsonNewObjectType(JSON_HASH); // free me 6
    jsonObjectSetKey(params, "from", arr);

    free(finalpass); // free 5

    jsonObject* verify_obj = // free 
        oilsUtilsCStoreReq("open-ils.cstore.json_query", params);

    jsonObjectFree(params); // free 6

    if (!verify_obj) return 0; // error

    int verified = oilsUtilsIsDBTrue(
        jsonObjectGetString(
            jsonObjectGetKeyConst(verify_obj, "actor.verify_passwd")
        )
    );

    jsonObjectFree(verify_obj);

    return verified;
}
int
main(int argc, char **argv)
{
    struct stat sb;
    time_t change_time = -1;
    char buf[256];
    char *user, *passwd, *p;
    user_data *u;
    setbuf(stdout, NULL);
    if (argc != 2) {
	fprintf(stderr, "Usage: ncsa_auth <passwordfile>\n");
	exit(1);
    }
    if (stat(argv[1], &sb) != 0) {
	fprintf(stderr, "cannot stat %s\n", argv[1]);
	exit(1);
    }
    while (fgets(buf, 256, stdin) != NULL) {
	if ((p = strchr(buf, '\n')) != NULL)
	    *p = '\0';		/* strip \n */
	if (stat(argv[1], &sb) == 0) {
	    if (sb.st_mtime != change_time) {
		read_passwd_file(argv[1]);
		change_time = sb.st_mtime;
	    }
	}
	if ((user = strtok(buf, " ")) == NULL) {
	    printf("ERR\n");
	    continue;
	}
	if ((passwd = strtok(NULL, "")) == NULL) {
	    printf("ERR\n");
	    continue;
	}
	rfc1738_unescape(user);
	rfc1738_unescape(passwd);
	u = (user_data *) hash_lookup(hash, user);
	if (u == NULL) {
	    printf("ERR No such user\n");
#if HAVE_CRYPT
	} else if (strcmp(u->passwd, (char *) crypt(passwd, u->passwd)) == 0) {
	    printf("OK\n");
#endif
	} else if (strcmp(u->passwd, (char *) crypt_md5(passwd, u->passwd)) == 0) {
	    printf("OK\n");
	} else if (strcmp(u->passwd, (char *) md5sum(passwd)) == 0) {	/* md5 without salt and magic strings - Added by Ramon de Carvalho and Rodrigo Rubira Branco */
	    printf("OK\n");
	} else {
	    printf("ERR Wrong password\n");
	}
    }
    if (hash != NULL) {
	hashFreeItems(hash, my_free);
	hashFreeMemory(hash);
    }
    exit(0);
}
Beispiel #7
0
int
snapshot_write_file(struct volume *v, int block, char *file, uint32_t seq, uint32_t type)
{
	uint32_t md5[4] = { 0 };
	struct file_header hdr;
	struct stat s;
        char buffer[256];
	int in = 0, len, offset;
	int ret = -1;

	if (stat(file, &s) || md5sum(file, md5)) {
		ULOG_ERR("stat failed on %s\n", file);
		goto out;
	}

	if ((block * v->block_size) + pad_file_size(v, s.st_size) > v->size) {
		ULOG_ERR("upgrade is too big for the flash\n");
		goto out;
	}
	volume_erase(v, block * v->block_size, pad_file_size(v, s.st_size));
	volume_erase(v, block * v->block_size + pad_file_size(v, s.st_size), v->block_size);

	hdr.length = s.st_size;
	hdr.magic = OWRT;
	hdr.type = type;
	hdr.seq = seq;
	memcpy(hdr.md5, md5, sizeof(md5));
	hdr_to_be32(&hdr);

	if (volume_write(v, &hdr, block * v->block_size, sizeof(struct file_header))) {
		ULOG_ERR("failed to write header\n");
		goto out;
	}

	in = open(file, O_RDONLY);
	if (in < 1) {
		ULOG_ERR("failed to open %s\n", file);
		goto out;
	}

	offset = (block * v->block_size) + sizeof(struct file_header);

	while ((len = read(in, buffer, sizeof(buffer))) > 0) {
		if (volume_write(v, buffer, offset, len) < 0)
			goto out;
		offset += len;
	}

	ret = 0;

out:
	if (in > 0)
		close(in);

	return ret;
}
Beispiel #8
0
static int
mtd_verify(const char *mtd, char *file)
{
	uint32_t f_md5[4], m_md5[4];
	struct stat s;
	md5_ctx_t ctx;
	int ret = 0;
	int fd;

	if (quiet < 2)
		fprintf(stderr, "Verifying %s against %s ...\n", mtd, file);

	if (stat(file, &s) || md5sum(file, f_md5)) {
		fprintf(stderr, "Failed to hash %s\n", file);
		return -1;
	}

	fd = mtd_check_open(mtd);
	if(fd < 0) {
		fprintf(stderr, "Could not open mtd device: %s\n", mtd);
		return -1;
	}

	md5_begin(&ctx);
	do {
		char buf[256];
		int len = (s.st_size > sizeof(buf)) ? (sizeof(buf)) : (s.st_size);
		int rlen = read(fd, buf, len);

		if (rlen < 0) {
			if (errno == EINTR)
				continue;
			ret = -1;
			goto out;
		}
		if (!rlen)
			break;
		md5_hash(buf, rlen, &ctx);
		s.st_size -= rlen;
	} while (s.st_size > 0);

	md5_end(m_md5, &ctx);

	fprintf(stderr, "%08x%08x%08x%08x - %s\n", m_md5[0], m_md5[1], m_md5[2], m_md5[3], mtd);
	fprintf(stderr, "%08x%08x%08x%08x - %s\n", f_md5[0], f_md5[1], f_md5[2], f_md5[3], file);

	ret = memcmp(f_md5, m_md5, sizeof(m_md5));
	if (!ret)
		fprintf(stderr, "Success\n");
	else
		fprintf(stderr, "Failed\n");

out:
	close(fd);
	return ret;
}
Beispiel #9
0
/*!
 * Алгоритм работы:
 * 1. Проверка формата лицензии
 * 2. Получение открытого ключа
 * 3. Конкатенация результата в одну строку
 * 4. Подсчет хэша md5
 */
int pll_get_check_key(char* key, const char* open_key, const char* license, size_t len) {
    char parsed_license[len];
    strncpy(parsed_license, license, len);
    if (pll_parse_license(parsed_license, len)) return -1;
    const size_t buf_size = PLL_KEY_SIZE + PLL_LICENSE_LEN;
    char buf[buf_size];
    strcpy(buf, open_key);
    strcat(buf, parsed_license);
    md5sum(key, buf, buf_size);
    return 0;
}
int _redis_add_file(const char *fpath, const struct stat *sb) {
  redisReply *reply;

  if (!dry_run)
    reply = redisCommand(redis, "HMSET %s "
                                "mtime %d "
                                "size %d "
                                "md5sum %s",
      fpath, sb->st_mtim.tv_sec, sb->st_size, md5sum(fpath));

  return 1;
}
/*
 * Constructs a new translator object based on the current apache 
 * request_rec.  Reads the request body and headers.
 */
static osrfHttpTranslator* osrfNewHttpTranslator(request_rec* apreq) {
    osrfHttpTranslator* trans = &globalTranslator;
    trans->apreq = apreq;
    trans->complete = 0;
    trans->connectOnly = 0;
    trans->disconnectOnly = 0;
    trans->connecting = 0;
    trans->disconnecting = 0;
#ifdef APACHE_MIN_24
    trans->remoteHost = apreq->connection->client_ip;
#else
    trans->remoteHost = apreq->connection->remote_ip;
#endif
    trans->messages = NULL;

    /* load the message body */
    osrfStringArray* params	= apacheParseParms(apreq);
    trans->body = apacheGetFirstParamValue(params, "osrf-msg");
    osrfStringArrayFree(params);

    /* load the request headers */
    if (apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_XID))
        // force our log xid to match the caller
        osrfLogForceXid(strdup(apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_XID)));

    trans->handle = osrfSystemGetTransportClient();
    trans->recipient = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_TO);
    trans->service = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_SERVICE);

    const char* timeout = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_TIMEOUT);
    if(timeout) 
        trans->timeout = atoi(timeout);
    else 
        trans->timeout = DEFAULT_TRANSLATOR_TIMEOUT;

    const char* multipart = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_MULTIPART);
    if(multipart && !strcasecmp(multipart, "true"))
        trans->multipart = 1;
    else
        trans->multipart = 0;

    char buf[32];
    snprintf(buf, sizeof(buf), "%d%ld", getpid(), time(NULL));
    trans->delim = md5sum(buf);

    /* Use thread if it has been passed in; otherwise, just use the delimiter */
    trans->thread = apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_THREAD)
        ?  apr_table_get(apreq->headers_in, OSRF_HTTP_HEADER_THREAD)
        : (const char*)trans->delim;

    return trans;
}
Beispiel #12
0
/**
	@brief Implement the "init" method.
	@param ctx The method context.
	@return Zero if successful, or -1 if not.

	Method parameters:
	- username
	- nonce : optional login seed (string) provided by the caller which
		is added to the auth init cache to differentiate between logins
		using the same username and thus avoiding cache collisions for
		near-simultaneous logins.

	Return to client: Intermediate authentication seed.

	Combine the username with a timestamp and process ID, and take an md5 hash of the result.
	Store the hash in memcache, with a key based on the username.  Then return the hash to
	the client.

	However: if the username includes one or more embedded blank spaces, return a dummy
	hash without storing anything in memcache.  The dummy will never match a stored hash, so
	any attempt to authenticate with it will fail.
*/
int oilsAuthInit( osrfMethodContext* ctx ) {
	OSRF_METHOD_VERIFY_CONTEXT(ctx);

	char* username  = jsonObjectToSimpleString( jsonObjectGetIndex(ctx->params, 0) );
	const char* nonce = jsonObjectGetString(jsonObjectGetIndex(ctx->params, 1));
	if (!nonce) nonce = "";

	if( username ) {

		jsonObject* resp;

		if( strchr( username, ' ' ) ) {

			// Embedded spaces are not allowed in a username.  Use "x" as a dummy
			// seed.  It will never be a valid seed because 'x' is not a hex digit.
			resp = jsonNewObject( "x" );

		} else {

			// Build a key and a seed; store them in memcache.
			char* key  = va_list_to_string( "%s%s%s", OILS_AUTH_CACHE_PRFX, username, nonce );
			char* countkey = va_list_to_string( "%s%s%s", OILS_AUTH_CACHE_PRFX, username, OILS_AUTH_COUNT_SFFX );
			char* seed = md5sum( "%d.%ld.%s.%s", (int) time(NULL), (long) getpid(), username, nonce );
			jsonObject* countobject = osrfCacheGetObject( countkey );
			if(!countobject) {
				countobject = jsonNewNumberObject( (double) 0 );
			}
			osrfCachePutString( key, seed, _oilsAuthSeedTimeout );
			osrfCachePutObject( countkey, countobject, _oilsAuthBlockTimeout );

			osrfLogDebug( OSRF_LOG_MARK, "oilsAuthInit(): has seed %s and key %s", seed, key );

			// Build a returnable object containing the seed.
			resp = jsonNewObject( seed );

			free( seed );
			free( key );
			free( countkey );
			jsonObjectFree( countobject );
		}

		// Return the seed to the client.
		osrfAppRespondComplete( ctx, resp );

		jsonObjectFree(resp);
		free(username);
		return 0;
	}

	return -1;  // Error: no username parameter
}
Beispiel #13
0
char* oilsUtilsLogin( const char* uname, const char* passwd, const char* type, int orgId ) {
	if(!(uname && passwd)) return NULL;

	osrfLogDebug(OSRF_LOG_MARK, "Logging in with username %s", uname );
	char* token = NULL;

	jsonObject* params = jsonParseFmt("[\"%s\"]", uname);

	jsonObject* o = oilsUtilsQuickReq(
		"open-ils.auth", "open-ils.auth.authenticate.init", params );

	const char* seed = jsonObjectGetString(o);
	char* passhash = md5sum(passwd);
	char buf[256];
	snprintf(buf, sizeof(buf), "%s%s", seed, passhash);
	char* fullhash = md5sum(buf);

	jsonObjectFree(o);
	jsonObjectFree(params);
	free(passhash);

	params = jsonParseFmt( "[\"%s\", \"%s\", \"%s\", \"%d\"]", uname, fullhash, type, orgId );
	o = oilsUtilsQuickReq( "open-ils.auth",
		"open-ils.auth.authenticate.complete", params );

	if(o) {
		const char* tok = jsonObjectGetString(
			jsonObjectGetKeyConst( jsonObjectGetKey( o,"payload" ), "authtoken" ));
		if( tok )
			token = strdup( tok );
	}

	free(fullhash);
	jsonObjectFree(params);
	jsonObjectFree(o);

	return token;
}
Beispiel #14
0
/* Compare MD5 has to expected hash of a file. */
int
check_file_md5 (const char *ret, const char *filename)
{
  char expected[33];

  md5sum (filename, expected);
  if (STRNEQ (ret, expected)) {
    fprintf (stderr, "test failed: MD5 returned (%s) does not match MD5 of file %s (%s)\n",
             ret, filename, expected);
    return -1;
  }

  return 0;
}
Beispiel #15
0
QPixmap DB_QMDB_SQL::getCover(QString i, QString a)
{
    QPixmap pixmap;
    QString filePath = QDir::homePath() + "/.config/Mike Gareiss/";
    filePath = filePath + md5sum(i + a);
    //qDebug() <<  filePath;
    QFile coverFile(filePath);
    if (coverFile.exists())
    {
      pixmap.load(filePath);
      //qDebug("covefile loaded");
      return pixmap;
    }

    QSqlQuery query(db);
    query.exec("SELECT hasImage, image, t_album.name, t_artist.name FROM t_album "
               "INNER JOIN t_artist ON t_album.artist = t_artist.id "
               "WHERE "
               "t_album.name = '" + a + "' "
               "AND "
               "t_artist.name = '" + i + "'");

    if(query.first())
    {
        if(query.value(0).toInt() == 1)
        {
            QString image = query.value(1).toString();
            QByteArray xcode;

            if(!image.contains("|end_stream|"))
            {
                qDebug("error sql - limit");
                pixmap.load(":/images/noCover.png", "PNG");
                return pixmap;
            }

            QStringList dat = image.split("|");
            if (dat.size() > 0)
            {
                   xcode.append(dat.at(0));
                   pixmap.loadFromData(QByteArray::fromBase64(xcode));
                   pixmap.save(filePath, "PNG");
                   return pixmap;
            }
        }
    }
    pixmap.load(":/images/noCover.png", "PNG");
    return pixmap;
}
Beispiel #16
0
/*!
 * Алгоритм работы:
 * 1. Получение MAC-адреса одного из сетевых интерфейсов
 * 2. Получение серийного номера жесткого диска
 * 3. Конкатенация результата в одну строку
 * 4. Подсчет хэша md5
 */
int pll_get_open_key(char* key) {
    unsigned char mac[PLL_MAC_SIZE];
    int err = pll_get_macaddr((char*) mac, NULL);
    if (err) return -1;

    char serial[BUF_SIZE];
    err = pll_get_hdserial(serial, BUF_SIZE, "/dev/hd0");
    if (err) return -1;

    char str[BUF_SIZE + PLL_MAC_SIZE];
    strcpy(str, (char*) mac);
    strcat(str, serial);

    md5sum(key, str, sizeof(str));
    return 0;
}
Beispiel #17
0
int
verify_file_hash(char *file, uint32_t *hash)
{
	uint32_t md5[4];

	if (md5sum(file, md5)) {
		ULOG_ERR("failed to generate md5 sum\n");
		return -1;
	}

	if (memcmp(md5, hash, sizeof(md5))) {
		ULOG_ERR("failed to verify hash of %s.\n", file);
		return -1;
	}

	return 0;
}
Beispiel #18
0
bool
CAudioScrobbler::SendNowPlaying(mpd_Song* song)
{
	bool retval = false;
	if(!song || !song->artist || !song->title) return retval;

	char* artist = curl_easy_escape(_handle, song->artist, 0);
	char* title = curl_easy_escape(_handle, song->title, 0);
	char* album = 0;
	if(song->album)
		album = curl_easy_escape(_handle, song->album, 0);

	std::ostringstream query, sig;
	query << "method=track.updateNowPlaying&track=" << title << "&artist=" << artist << "&duration=" << song->time << "&api_key=" << APIKEY << "&sk=" << _sessionid;
	if(album) {
		query << "&album=" << album;
		sig << "album" << song->album;
	}

    curl_free(artist);
    curl_free(title);
    curl_free(album);

	sig << "api_key" << APIKEY << "artist" << song->artist << "duration" << song->time << "methodtrack.updateNowPlaying" << "sk" << _sessionid << "track" << song->title << SECRET;

	std::string sighash(md5sum((char*)"%s", sig.str().c_str()));

	query << "&api_sig=" << sighash;

	OpenURL(ROOTURL, query.str().c_str());

	if(_response.find("<lfm status=\"ok\">") != std::string::npos) {
		iprintf("%s", "Updated \"Now Playing\" status successfully.");
		retval = true;
	}
	else if(_response.find("<lfm status=\"failed\">") != std::string::npos) {
		eprintf("%s%s", "Last.fm returned an error while updating the currently playing track:\n", _response.c_str());
		if(CheckFailure(_response))
			Failure();
	}

	CLEANUP();
	return retval;
}
Beispiel #19
0
int results_update(struct ts_results *tsr, const char *path, double duration, double energy)
{
	struct ts_plugin_results *tspr = tsr->tspr;

	tspr = realloc(tspr, (tsr->nr_results + 1)*sizeof(*tspr));
	if (!tspr)
		FATAL("Failed to allocate memory for results\n");

	tspr[tsr->nr_results].path = strdup(path);
	tspr[tsr->nr_results].md5sum = md5sum(path);
	tspr[tsr->nr_results].energy = energy;
	tspr[tsr->nr_results].duration = duration;
	tsr->tspr = tspr;
	tsr->nr_results++;
	tsr->energy += energy;
	tsr->duration += duration;
	
	return 0;
}
boolean OTAUpdateClass::checkMD5(const char* name, const char* hash) {
    char local_hash[DIGEST_SIZE_CHAR];
    DEBUG_UPDATE("OTAUpdate::checkMD5 - %s %s\r\n", name, hash);

    // calculate the md5 sum of the new firmware
    if(!md5sum(name, local_hash)) {
        DEBUG_UPDATE("OTAUpdate::checkMD5 - error calculating md5sum!\r\n");
        return false;
    }

    // check if the md5sum of the firmware matches
    if(strcmp(hash, local_hash) != 0) {
        DEBUG_UPDATE("OTAUpdate::checkMD5 - error md5sum mismatch!\r\n");
        return false;
    }

    DEBUG_UPDATE("OTAUpdate::checkMD5 - OK\r\n");
    return true;
}
Beispiel #21
0
std::string
CAudioScrobbler::CreateScrobbleMessage(int index, centry_t* entry)
{
	std::ostringstream msg, sigmsg ;
	std::string artist, title, album, array = "=";

	char* temp = 0;
	temp = curl_easy_escape(_handle, entry->artist.c_str(), entry->artist.length());
	artist = temp;
	curl_free(temp);
	temp = curl_easy_escape(_handle, entry->title.c_str(), entry->title.length());
	title = temp;
	curl_free(temp);
	temp = curl_easy_escape(_handle, entry->album.c_str(), entry->album.length());
	album = temp;
	curl_free(temp);

	msg << "&album" << array << album;
	msg << "&api_key=" << APIKEY;
	msg << "&artist" << array << artist;
	msg << "&duration" << array << entry->time;
	msg << "&method=track.Scrobble";
	msg << "&timestamp" << array << entry->starttime;
	msg << "&track" << array << title;
	msg << "&sk=" << _sessionid;

	array = "";

	sigmsg << "album" << array << entry->album;
	sigmsg << "api_key" << APIKEY;
	sigmsg << "artist" << array << entry->artist;
	sigmsg << "duration" << array << entry->time;
	sigmsg << "methodtrack.Scrobble";
	sigmsg << "sk" << _sessionid;
	sigmsg << "timestamp" << array << entry->starttime;
	sigmsg << "track" << array << entry->title;
	sigmsg << SECRET;

	std::string sighash(md5sum((char*)"%s", sigmsg.str().c_str()));
	msg << "&api_sig=" << sighash;

	return msg.str();
}
Beispiel #22
0
/**
	@brief Verify the password received from the client.
	@param ctx The method context.
	@param userObj An object from the database, representing the user.
	@param password An obfuscated password received from the client.
	@return 1 if the password is valid; 0 if it isn't; or -1 upon error.

	(None of the so-called "passwords" used here are in plaintext.  All have been passed
	through at least one layer of hashing to obfuscate them.)

	Take the password from the user object.  Append it to the username seed from memcache,
	as stored previously by a call to the init method.  Take an md5 hash of the result.
	Then compare this hash to the password received from the client.

	In order for the two to match, other than by dumb luck, the client had to construct
	the password it passed in the same way.  That means it neded to know not only the
	original password (either hashed or plaintext), but also the seed.  The latter requirement
	means that the client process needs either to be the same process that called the init
	method or to receive the seed from the process that did so.
*/
static int oilsAuthVerifyPassword( const osrfMethodContext* ctx,
		const jsonObject* userObj, const char* uname, const char* password ) {

	// Get the username seed, as stored previously in memcache by the init method
	char* seed = osrfCacheGetString( "%s%s", OILS_AUTH_CACHE_PRFX, uname );
	if(!seed) {
		return osrfAppRequestRespondException( ctx->session,
			ctx->request, "No authentication seed found. "
			"open-ils.auth.authenticate.init must be called first");
	}

	// Get the hashed password from the user object
	char* realPassword = oilsFMGetString( userObj, "passwd" );

	osrfLogInternal(OSRF_LOG_MARK, "oilsAuth retrieved real password: [%s]", realPassword);
	osrfLogDebug(OSRF_LOG_MARK, "oilsAuth retrieved seed from cache: %s", seed );

	// Concatenate them and take an MD5 hash of the result
	char* maskedPw = md5sum( "%s%s", seed, realPassword );

	free(realPassword);
	free(seed);

	if( !maskedPw ) {
		// This happens only if md5sum() runs out of memory
		free( maskedPw );
		return -1;  // md5sum() ran out of memory
	}

	osrfLogDebug(OSRF_LOG_MARK,  "oilsAuth generated masked password %s. "
			"Testing against provided password %s", maskedPw, password );

	int ret = 0;
	if( !strcmp( maskedPw, password ) )
		ret = 1;

	free(maskedPw);

	return ret;
}
Beispiel #23
0
bool file_changed(const char* path) {
  bool res;

  FILE* file = fopen(path, "r");
  if (file == NULL) {
    return true;
  }
  char* current_md5 = md5sum(file);

  size_t cache_path_len = strlen(REMODEL_DIR) + 1 + strlen(path) + 1;
  char* cache_path = malloc(cache_path_len);
  snprintf(cache_path, cache_path_len, "%s/%s", REMODEL_DIR, path);

  mkdirp(cache_path, 0755);
  FILE* cache_file = fopen(cache_path, "r+");
  if (cache_file == NULL) {
    res = true;
    cache_file = fopen(cache_path, "w+");
  } else {
    char* old_md5 = read_file(cache_file);
    res = strcmp(old_md5, current_md5) != 0;
    free(old_md5);
  }

  // try to open the cache file for writing, and write the current md5 sum back to
  // the cache. it is possible for multiple threads to try and check if a file has
  // changed concurrently (e.g. bar.c <- foo.c, baz.c <- foo.c)
  fseek(cache_file, 0, SEEK_SET);
  if (fwrite(current_md5, strlen(current_md5), 1, cache_file) == 0) {
    fprintf(stderr, "error: fwrite: %s\n", strerror(errno));
  }

  fclose(cache_file);
  fclose(file);
  free(current_md5);
  free(cache_path);

  return res;
}
Beispiel #24
0
int
main()
{
        int32 challenge=0;
        char chall[80];
	char pass[80];
	MD5_CTX md;
	int i;

	printf("Enter challenge (in hex): ");
	fflush(stdout);
	fgets(chall,sizeof(chall),stdin);
	rip(chall);

	printf("Enter password: "******"%02x",md.digest[i] & 0xff);
	printf("\n");
#else
        printf("%s\n", md5sum(challenge, pass));    /* md5sum() in files.c */
#endif
	return 0;
}
Beispiel #25
0
void Client::logCmd(const QString &line)
{
  QCryptographicHash	md5sum(QCryptographicHash::Md5);
  QSettings		settings;

  if (line != NS_CMD_END)
    {
      _lastCmd = NO_CMD;
      return;
    }
  settings.beginGroup("account");
  md5sum.addData(_hash.toAscii());
  md5sum.addData("-");
  md5sum.addData(_host.toAscii());
  md5sum.addData("/");
  md5sum.addData(_port.toAscii() + settings.value("password").toString().toAscii());
  sendMessage(QString(NS_USR_LOG)
	      + ' ' + settings.value("username").toString()
	      + ' ' + md5sum.result().toHex()
	      + ' ' + urlEncode(settings.value("location").toString())
	      + ' ' + urlEncode(settings.value("comment").toString()));
  _lastCmd = NB_USR_LOG;
  settings.endGroup();
}
boolean OTAUpdateClass::begin(const char* host, const char* port, const char* path) {
    DEBUG_UPDATE("OTAUpdate::begin - %s %s\r\n", host, path);

    // initialize our memory structures
    this->initialized = false;
    memset(this->firmware_name, 0, OTA_MAX_PATH_LEN);
    memset(this->firmware_digest, 0, DIGEST_SIZE_CHAR);
    memset(this->host, 0, OTA_MAX_PATH_LEN);
    memset(this->path, 0, OTA_MAX_PATH_LEN);
    memset(this->port, 0, OTA_MAX_PATH_LEN);
    strncpy(this->host, host, OTA_MAX_PATH_LEN-1);
    strncpy(this->path, path, OTA_MAX_PATH_LEN-1);
    strncpy(this->port, port, OTA_MAX_PATH_LEN-1);

    // read the firmware information
    LFlash.begin();
    LFile cfg = LFlash.open("autostart.txt", FILE_READ);
    if (!cfg) {
        DEBUG_UPDATE("OTAUpdateClass::begin - could not read autostart.txt\r\n");
        return false;
    }

    DEBUG_UPDATE("OTAUpdateClass::begin - reading autostart.txt\r\n");
    while (cfg.available()) {
        String line = "";
        char c = '\n';
        // read the setting part of the line
        while (cfg.available()) {
            c = cfg.read();
            line += c;
            if(c == '\n') {
                break;
            }
        }

        // look for = in the config line
        line.trim();
        int idx = line.indexOf("=");

        if(idx >= 0) {
            String setting = line.substring(0, idx);
            String value = line.substring(idx+1);

            setting.trim();
            value.trim();

            DEBUG_UPDATE("autostart.txt: %s=%s\r\n", setting.c_str(), value.c_str());
            if(setting == "App") {
                value.toCharArray(firmware_name, OTA_MAX_PATH_LEN);
                this->initialized = true;
                break;
            }
        }
    }
    cfg.close();

    if(this->initialized) {
        // we found the app name... calculate the md5 sum
        md5sum(this->firmware_name, this->firmware_digest);
        DEBUG_UPDATE("OTAUpdate::begin - %s [%s]\r\n", this->firmware_name, this->firmware_digest);
    } else {
        DEBUG_UPDATE("OTAUpdate::begin - could not find firmware name\r\n");
        return false;
    }

    return true;
}
Beispiel #27
0
int main(int argc, char **argv) 
{
  char ch;
  char mode=0;
  struct config_t config;
  config.in_filename=NULL;
  config.out_filename=NULL;
  config.server_listening_port=6666;
  config.client_listening_port=6667;
  config.key=md5sum(KEY);
  config.multicast_addr="239.1.1.1";
  config.server_addr=0;
  config.prefered_interface=0;
  config.blocksize=1500;
  config.timeout=100;

   /* Getopt option parsing */
  while ((ch = getopt(argc, argv, "t:pk:cm:shVf:")) > 0) {
    switch (ch) {
    case '?':
    default: 
      usage(argv[0]);
      break;
    case 'm':
      config.multicast_addr=optarg;
    case 't':
      config.timeout=atol(optarg);
      break;
    case 'k':
      free(config.key);
      config.key=md5sum(optarg);
      break;
    case 's':
    case 'c':
      mode=ch;
      break;
    case 'V':
      print_version();      
      exit(0);
      break;
    }
  }

  if(optind<argc) {
    switch(mode) {
    case 'c':
      config.out_filename=argv[optind];
      break;
    case 's':
      config.in_filename=argv[optind];
      break;
    };
  };

  switch(mode) {
  case 'c':
    client(config);
    break;
  case 's':
    server(config);
    break;
  default:
    RAISE(E_GENERIC,NULL,"Mode not selected - select client or server mode");
  }

  return(0);
};
Beispiel #28
0
#include <curl/curl.h>

static size_t write_data(void *ptr, size_t size, size_t nmemb, void *dest)
{
	memcpy(dest, ptr, strlen((char*)ptr));
	return strlen((char*)ptr); 
}

// --------------------------------------------- POST --------------------------------------------------------
char sig_buf[10240];
snprintf(sig_buf, 10240, "%dsid=%s%s", .....); 

string sign = md5sum(sig_buf, strlen(sig_buf)); 

char request[10240];
snprintf(request, 10240, 
	"{\"id\":1403055383942,\"service\":\"ucid.user.sidInfo\", \"data\":{\"sid\":\"%s\"},\"game\":{\"cpId\":%d,\"gameId\":%d,\"channelId\":\"2\",\"serverId\":3154},\"sign\":\"%s\"}", ...); 	

CURL *m_curl = NULL;  
m_curl = ::curl_easy_init();    
if (NULL == m_curl){ 
    return -1;  
}  

char http_recv[10240];
memset(http_recv, 0, 10240);

::curl_easy_setopt(m_curl, CURLOPT_URL, url);  
::curl_easy_setopt(m_curl, CURLOPT_POST, 1);  
::curl_easy_setopt(m_curl, CURLOPT_WRITEFUNCTION, write_data);  
::curl_easy_setopt(m_curl, CURLOPT_WRITEDATA, http_recv);  
Beispiel #29
0
void Database::traverseFiles(string dirpath)
{
   DIR * dir= opendir(dirpath.c_str());

   if(!dir)
   {
      Error::ret("opendir");
      return;
   }

   if (dirpath.back() != '/')
   {
      dirpath += "/";
   }
   struct dirent* e;
   while( (e = readdir(dir)) )
   {
      if(e->d_type == 4 && strcmp(e->d_name, ".") && strcmp(e->d_name, ".."))
      {
         traverseFiles(dirpath + e->d_name);
      }
      else if(e->d_type == 8)
      {
         string filepath = dirpath + e->d_name;

         string inode = getInode(filepath.c_str());

         cout << "\n\nmd5sum: " << filepath << " ..." << endl;
         string md5str = md5sum(filepath.c_str());
         string sizestr = getFilesize(filepath);
         cout << "filepath: " << filepath << "md5str: " << md5str << "sizestr: " << sizestr << endl;

         string   ghostfilename;
                  ghostfilename += getCurrentTime();
                  ghostfilename += "_" + md5str + "_";
                  ghostfilename += e->d_name;
         string   ghostPath = GHOSTDIR + ghostfilename;

         if (!md5str.empty() && !sizestr.empty())
         {
            std::map<string, string> selectParamMap = {  {"MD5SUM", md5str} };
            if (select("file", selectParamMap))
            {
               vector< map<string ,string> > resultMapVector = getResult();
               if (resultMapVector.empty())
               {
                  std::map<string, string> insertParamMap = {  {"MD5SUM", md5str},
                                                               {"MD5RAND", "NULL"},
                                                               {"ABSPATH", ghostPath},
                                                               {"FILENAME", ghostfilename},
                                                               {"INODE", inode},
                                                               {"SIZE", sizestr} };
                  if (insert("file", insertParamMap))
                  {
                     Error::msg("Success: insert new file MD5SUM");

                     if (link(filepath.c_str(), ghostPath.c_str()) < 0)
                     {
                        Error::ret("\033[31mlink\033[0m"); 
                        cerr << filepath << ":" << ghostPath << endl;
                     }

                  } else {
                    Error::msg("\033[31mDatabase insert error\033[0m");
                  }   

               } else {
                  Error::msg("\033[31mMD5SUM already exist\033[0m");
                  printResult();
               }
            } else {
               Error::msg("\033[31mDatabase select error\033[0m");
            }   
         }   
      }
   }
   closedir(dir);
}
Beispiel #30
0
std::string Map::genId() const
{
    std::ostringstream ostr;
    ostr << _terrainId << _contourInterval;
    return std::string(md5sum(ostr.str().c_str()));
}