コード例 #1
0
ファイル: qppsobject.cpp プロジェクト: 2gis/2gisqt5android
int QPpsObject::writeMessage(const QString &msg, const QString &id, const QVariantMap &dat)
{
    // Treat empty msg or id as an encoding error
    if (msg.isEmpty() || id.isEmpty())
        return -1;

    bool ok;
    QByteArray byteArray = encodeMessage(msg, id, dat, &ok);

    if (!ok)
        return -1;

    ok = write(byteArray);
    if (!ok)
        return error();

    return EOK;
}
コード例 #2
0
ファイル: chatroomwindow.cpp プロジェクト: sonic414/lmc-clone
void lmcChatRoomWindow::sendMessage(void) {
	if(ui.txtMessage->document()->isEmpty())
		return;

	if(bConnected) {
		QString szHtmlMessage(ui.txtMessage->toHtml());
		encodeMessage(&szHtmlMessage);
		QTextDocument docMessage;
		docMessage.setHtml(szHtmlMessage);
		QString szMessage = docMessage.toPlainText();

		QFont font = ui.txtMessage->font();
		font.setPointSize(ui.txtMessage->fontPointSize());

		MessageType type = groupMode ? MT_GroupMessage : MT_PublicMessage;
		XmlMessage xmlMessage;
		xmlMessage.addHeader(XN_TIME, QString::number(QDateTime::currentDateTime().toMSecsSinceEpoch()));
		xmlMessage.addData(XN_FONT, font.toString());
		xmlMessage.addData(XN_COLOR, messageColor.name());
		xmlMessage.addData(XN_MESSAGE, szMessage);
		if(groupMode) {
			xmlMessage.addData(XN_THREAD, threadId);
			xmlMessage.addData(XN_GROUPMSGOP, GroupMsgOpNames[GMO_Message]);
		}

		appendMessageLog(type, &localId, &localName, &xmlMessage);

		if(groupMode) {
			QHash<QString, QString>::const_iterator index = peerIds.constBegin();
			while (index != peerIds.constEnd()) {
				QString userId = index.value();
				emit messageSent(type, &userId, &xmlMessage);
				index++;
			}
		} else
			emit messageSent(type, NULL, &xmlMessage);
	}
	else
		appendMessageLog(MT_Error, NULL, NULL, NULL);

	ui.txtMessage->clear();
	ui.txtMessage->setFocus();
}
コード例 #3
0
ファイル: broadcastwindow.cpp プロジェクト: Litew/lanmsng
//	send the broadcast message to all selected users
void lmcBroadcastWindow::sendMessage(void) {
	//	return if text box is empty
	if(ui.txtMessage->document()->isEmpty())
		return;

	//	send only if connected
	if(bConnected) {
		QString szHtmlMessage(ui.txtMessage->toHtml());
		encodeMessage(&szHtmlMessage);
		QTextDocument docMessage;
		docMessage.setHtml(szHtmlMessage);
		QString szMessage(docMessage.toPlainText());
		
		//	send broadcast
		int sendCount = 0;
		XmlMessage xmlMessage;
		xmlMessage.addData(XN_BROADCAST, szMessage);
		for(int index = 0; index < ui.tvUserList->topLevelItemCount(); index++) {
			for(int childIndex = 0; childIndex < ui.tvUserList->topLevelItem(index)->childCount(); childIndex++) {
				QTreeWidgetItem* item = ui.tvUserList->topLevelItem(index)->child(childIndex);
				if(item->checkState(0) == Qt::Checked) {
                    QString szUserId = item->data(0, IdRole).toString();
					emit messageSent(MT_Broadcast, &szUserId, &xmlMessage);
					sendCount++;
				}
			}
		}

		if(sendCount == 0) {
			QMessageBox::warning(this, tr("No recipient selected"), 
				tr("Please select at least one recipient to send a broadcast."));
			return;
		}

		ui.txtMessage->clear();
		close();
	}
}
コード例 #4
0
ファイル: AlanTuring.cpp プロジェクト: GastonMontes/Facultad
/*
 * 	METODOS DE CODIFICACION
 */
void AlanTuring::fillMsgData(NetworkMessage* netMsg, const Mensaje mensaje)
{
	bzero(netMsg->msg_Data,MESSAGE_DATA_SIZE);

	if ((strcmp(mensaje.tipo.c_str(), "int")) == 0)
	{
		netMsg->msg_Code[0] = 'i';
		netMsg->msg_Code[1] = 'n';
		netMsg->msg_Code[2] = 't';
		encodeMessage(netMsg, mensaje);
	}
	if ((strcmp(mensaje.tipo.c_str(), "char")) == 0)
	{
		netMsg->msg_Code[0] = 'c';
		netMsg->msg_Code[1] = 'h';
		netMsg->msg_Code[2] = 'r';
		encodeMessage(netMsg, mensaje);
	}
	if ((strcmp(mensaje.tipo.c_str(), "double")) == 0)
	{
		netMsg->msg_Code[0] = 'd';
		netMsg->msg_Code[1] = 'b';
		netMsg->msg_Code[2] = 'l';
		encodeMessage(netMsg, mensaje);
	}
	if ((strcmp(mensaje.tipo.c_str(), "string")) == 0)
	{
		netMsg->msg_Code[0] = 's';
		netMsg->msg_Code[1] = 't';
		netMsg->msg_Code[2] = 'r';
		encodeMessage(netMsg, mensaje);
	}
	if ((strcmp(mensaje.tipo.c_str(), "exit")) == 0)
	{
		netMsg->msg_Code[0] = 'e';
		netMsg->msg_Code[1] = 'x';
		netMsg->msg_Code[2] = 't';
		encodeMessage(netMsg, mensaje);
	}
	if ((strcmp(mensaje.tipo.c_str(), "connected")) == 0)
	{
		netMsg->msg_Code[0] = 'c';
		netMsg->msg_Code[1] = 'n';
		netMsg->msg_Code[2] = 't';
		encodeMessage(netMsg, mensaje);
	}
	if ((strcmp(mensaje.tipo.c_str(), "serverfull")) == 0)
	{
		netMsg->msg_Code[0] = 'f';
		netMsg->msg_Code[1] = 'u';
		netMsg->msg_Code[2] = 'l';
		encodeMessage(netMsg, mensaje);
	}
	if ((strcmp(mensaje.tipo.c_str(), "timeoutACK")) == 0)
	{
		netMsg->msg_Code[0] = 't';
		netMsg->msg_Code[1] = 'm';
		netMsg->msg_Code[2] = 'o';
		encodeMessage(netMsg, mensaje);
	}
}
コード例 #5
0
ファイル: Websocket.c プロジェクト: GangXu/Websocket-1
/**
 * This function listens for input from STDIN and tries to match it to a 
 * pattern that will trigger different actions.
 */
void *cmdline(void *arg) {
	pthread_detach(pthread_self());
	(void) arg; char buffer[1024];
	
	while (1) {
		memset(buffer, '\0', 1024);
		printf("> ");
		fflush(stdout);
		fgets(buffer, 1024, stdin);
		
		if (strncasecmp(buffer, "users", 5) == 0 || 
				strncasecmp(buffer, "online", 6) == 0 ||
				strncasecmp(buffer, "clients", 7) == 0) {
			list_print(l);
			continue;
		} else if (strncasecmp(buffer, "exit", 4) == 0 || 
				strncasecmp(buffer, "quit", 4) == 0) {
			raise(SIGINT);
			break;
		} else if ( strncasecmp(buffer, "help", 4) == 0 ) {
			printf("------------------------ HELP ------------------------\n");
			printf("|   To display information about the online users,   |\n");
			printf("|   type: 'users', 'online', or 'clients'.           |\n");
			printf("|                                                    |\n");
			printf("|   To send a message to a specific user from the    |\n");
			printf("|   server type: 'send <IP> <SOCKET> <MESSAGE>' or   |\n");
			printf("|   'write <IP> <SOCKET> <MESSAGE>'.                 |\n");
			printf("|                                                    |\n");
			printf("|   To send a message to all users from the server   |\n");
			printf("|   type: 'sendall <MESSAGE>' or 'writeall           |\n");
			printf("|   <MESSAGE>'.                                      |\n");
			printf("|                                                    |\n");
 			printf("|   To kick a user from the server and close the     |\n");
			printf("|   socket connection type: 'kick <IP> <SOCKET>'     |\n");
			printf("|   or 'close <IP> <SOCKET>'.                        |\n");
			printf("|                                                    |\n"); 
 			printf("|   To kick all users from the server and close      |\n");
			printf("|   all socket connections type: 'kickall' or        |\n");
			printf("|   'closeall'.                                      |\n");
			printf("|                                                    |\n");
			printf("|   To quit the server type: 'quit' or 'exit'.       |\n");
			printf("------------------------------------------------------\n");
			fflush(stdout);
			continue;
		} else if ( strncasecmp(buffer, "kickall", 7) == 0 ||
				strncasecmp(buffer, "closeall", 8) == 0) {
			list_remove_all(l);	
		} else if ( strncasecmp(buffer, "kick", 4) == 0 ||
				strncasecmp(buffer, "close", 5) == 0) {
			char *token = strtok(buffer, " "), *addr, *sock;

			if (token != NULL) {
				token = strtok(NULL, " ");

				if (token == NULL) {
					printf("The command was executed without parameters. Type "
						   "'help' to see how to execute the command properly."
						   "\n");
					fflush(stdout);
					continue;
				} else {
					addr = token;	
				}

				token = strtok(NULL, "");

				if (token == NULL) {
					printf("The command was executed with too few parameters. Type "
						   "'help' to see how to execute the command properly."
						   "\n");
					fflush(stdout);
					continue;
				} else {
					sock = token;	
				}

				ws_client *n = list_get(l, addr, 
						strtol(sock, (char **) NULL, 10));

				if (n == NULL) {
					printf("The client that was supposed to receive the "
						   "message, was not found in the userlist.\n");
					fflush(stdout);
					continue;
				}

				ws_closeframe(n, CLOSE_SHUTDOWN);
			}
		} else if ( strncasecmp(buffer, "sendall", 7) == 0 ||
			   strncasecmp(buffer, "writeall", 8) == 0) {
			char *token = strtok(buffer, " ");
			ws_connection_close status;

			if (token != NULL) {
				token = strtok(NULL, "");

				if (token == NULL) {
					printf("The command was executed without parameters. Type "
						   "'help' to see how to execute the command properly."
						   "\n");
					fflush(stdout);
					continue;
				} else {
					ws_message *m = message_new();
					m->len = strlen(token);
					
					char *temp = malloc( sizeof(char)*(m->len+1) );
					if (temp == NULL) {
						raise(SIGINT);		
						break;
					}
					memset(temp, '\0', (m->len+1));
					memcpy(temp, token, m->len);
					m->msg = temp;
					temp = NULL;

					if ( (status = encodeMessage(m)) != CONTINUE) {
						message_free(m);
						free(m);
						raise(SIGINT);
						break;;
					}

					list_multicast_all(l, m);
					message_free(m);
					free(m);
				}
			}
		} else if ( strncasecmp(buffer, "send", 4) == 0 ||
				strncasecmp(buffer, "write", 5) == 0) {
			char *token = strtok(buffer, " "), *addr, *sock, *msg;
			ws_connection_close status;

			if (token != NULL) {
				token = strtok(NULL, " ");

				if (token == NULL) {
					printf("The command was executed without parameters. Type "
						   "'help' to see how to execute the command properly."
						   "\n");
					fflush(stdout);
					continue;
				} else {
					addr = token;	
				}

				token = strtok(NULL, " ");

				if (token == NULL) {
					printf("The command was executed with too few parameters. Type "
						   "'help' to see how to execute the command properly."
						   "\n");
					fflush(stdout);
					continue;
				} else {
					sock = token;	
				}

				token = strtok(NULL, "");
				
				if (token == NULL) {
					printf("The command was executed with too few parameters. Type "
						   "'help' to see how to execute the command properly."
						   "\n");
					fflush(stdout);
					continue;
				} else {
					msg = token;	
				}

				ws_client *n = list_get(l, addr, 
						strtol(sock, (char **) NULL, 10));

				if (n == NULL) {
					printf("The client that was supposed to receive the "
						   "message, was not found in the userlist.\n");
					fflush(stdout);
					continue;
				}

				ws_message *m = message_new();
				m->len = strlen(msg);
				
				char *temp = malloc( sizeof(char)*(m->len+1) );
				if (temp == NULL) {
					raise(SIGINT);		
					break;
				}
				memset(temp, '\0', (m->len+1));
				memcpy(temp, msg, m->len);
				m->msg = temp;
				temp = NULL;

				if ( (status = encodeMessage(m)) != CONTINUE) {
					message_free(m);
					free(m);
					raise(SIGINT);
					break;;
				}

				list_multicast_one(l, n, m);
				message_free(m);
				free(m);
			}
		} else {
			printf("To see functions available type: 'help'.\n");
			fflush(stdout);
			continue;
		}
	}

	pthread_exit((void *) EXIT_SUCCESS);
}
コード例 #6
0
ファイル: seller.cpp プロジェクト: suhangpro/asterix
/// This function runs in a thread for every client, and reads incomming data.
/// It also writes the incomming data to all other clients.
void Seller::processMessage(int rfd) {
	// std::cout << "This is a seller (peer " << _peerId << "). I am selling " << goodsNames[_goods] << ". " << _amount << " items left.\n";

    char buf[MAXLEN];
    int buflen;

    //read incomming message.
    buflen = read(rfd, buf, sizeof(buf));

    pthread_mutex_lock(&_mutex_state);
    FD_CLR(rfd, &_the_state);      // free fd's from  clients
    pthread_mutex_unlock(&_mutex_state);

    if (buflen <= 0)
    {
        std::cerr<<"[sellr-"<<_peerId<<"] Client disconnected."<<std::endl;
        close(rfd);
        pthread_exit(NULL);
        return;
    }

    // process the purchase request
    // check Fish 0
    // purchase Salt 1
    // std::cout << "[seller-" << _peerId << "] ";// << buf << std::endl;
    // printMessage(buf);

    std::string requestType;
    Goods goods;
    int var;
    std::vector<int> path;
    decodeMessage(buf, requestType, goods, var, path);

    int originPeerId = path[0];
    int lastNbPeerId = path.back();

    pthread_mutex_lock(&_mutex_state);

    bool isCloseSocket = true;

    if(requestType == "purchase") {
        if(goods == _goods) {
        	if(_amount > 0) {
//                std::cout << "================================== end of the deal ==========================================\n";
        		// sendPeerMessage(originPeerId, msg.c_str());
                std::string msg = encodeMessage("deal", _goods, -1, -1);
                reply(rfd, msg.c_str());
                
                if(_amount > 1) {
                    std::printf("[sellr-%03d] I just #sold# %s to peer #%d. I still have %d %s.\n", _peerId, goodsNames[_goods], path.front(), _amount - 1, goodsNames[_goods]);
                }
                else {
                    std::printf("[sellr-%03d] I just #sold# %s to peer #%d. It's last one.\n", _peerId, goodsNames[_goods], path.front());
                }

        		_amount--;
                isCloseSocket = false;

        		if(_amount == 0) {
                    // std::cout << goodsNames[_goods] << " seld out.\n";
        			randPickGoods(goodsAmount);
                }
        	}
            else {
                std::string msg = encodeMessage("fail_deal", _goods, -1, -1);
                reply(rfd, msg.c_str());

                std::printf("[sellr-%03d] Peer #%d wants to buy %s from me. Too late!\n", _peerId, path.front(), goodsNames[goods]);
            }
        }
        else {
            std::string msg = encodeMessage("fail_deal", _goods, -1, -1);
            reply(rfd, msg.c_str());

            std::printf("[sellr-%03d] Peer #%d wants to buy %s from me. Too late!\n", _peerId, path.front(), goodsNames[goods]);
        }
    } 
    else if(requestType == "look_up") {
    	if(goods == _goods && _amount > 0) {
  //          std::cout << "\n============================ start of the deal (maybe) ====================================\n";
            std::string msg = encodeMessage("reply", _goods, _peerId, path.begin(), path.end() - 1);
    		sendPeerMessage(lastNbPeerId, msg.c_str());

            std::printf("[sellr-%03d] Trying to sell %s to buyer %d. Path back is ", _peerId, goodsNames[_goods], path.front());
            for(size_t i = path.size() - 1; i > 0; --i)
                std::printf("%d->", path[i]);
            std::printf("%d.\n", path[0]);
        }
        else {
        	floodingMessage(buf);

            //std::printf("[messager-%03d] Peer #%d wants to buy %s. Hop count: %d. Path is ", _peerId, path.front(), goodsNames[goods], var);
            std::printf("[msger-%03d] Peer #%d wants to buy %s. Path is ", _peerId, path.front(), goodsNames[goods]);
            for(size_t i = 0; i < path.size() - 1; ++i)
                std::printf("%d->", path[i]);
            std::printf("%d.\n", path.back());
        }
    } 
    else if(requestType == "reply") {
        int sellerPeerId = var;
        std::string msg = encodeMessage("reply", goods, sellerPeerId, path.begin(), path.end() - 1);
        sendPeerMessage(lastNbPeerId, msg.c_str());

        std::printf("[msger-%03d] Peer #%d wants to sell %s to peer #%d. Path back is ", _peerId, sellerPeerId, goodsNames[goods], path.front());
        for(size_t i = path.size() - 1; i > 0; --i)
            std::printf("%d->", path[i]);
        std::printf("%d.\n", path[0]);
    } 
    else {
        std::cerr << "[Error] Unrecognized request type " << requestType << std::endl;
    }

    _activeConnect--;

    pthread_mutex_unlock(&_mutex_state);

    //std::cout << std::endl;

    if(isCloseSocket)
        close(rfd);

    pthread_exit(NULL);
}
コード例 #7
0
ファイル: multiple.c プロジェクト: LiangJunqiang/RSA
/**
 * Main method to demostrate the system. Sets up primes p, q, and proceeds to encode and
 * decode the message given in "text.txt"
 */
int main(void) {
	int i, bytes, len;
	bignum *p = bignum_init(), *q = bignum_init(), *n = bignum_init();
	bignum *phi = bignum_init(), *e = bignum_init(), *d = bignum_init();
	bignum *bbytes = bignum_init(), *shift = bignum_init();
	bignum *temp1 = bignum_init(), *temp2 = bignum_init();
	
	bignum *encoded;
	int *decoded;
	char *buffer;
	FILE* f;
	
	srand(time(NULL));
	
	randPrime(FACTOR_DIGITS, p);
	printf("Got first prime factor, p = ");
	bignum_print(p);
	printf(" ... ");
	getchar();
	
	randPrime(FACTOR_DIGITS, q);
	printf("Got second prime factor, q = ");
	bignum_print(q);
	printf(" ... ");
	getchar();
	
	bignum_multiply(n, p, q);
	printf("Got modulus, n = pq = ");
	bignum_print(n);
	printf(" ... ");
	getchar();
	
	bignum_subtract(temp1, p, &NUMS[1]);
	bignum_subtract(temp2, q, &NUMS[1]);
	bignum_multiply(phi, temp1, temp2); /* phi = (p - 1) * (q - 1) */
	printf("Got totient, phi = ");
	bignum_print(phi);
	printf(" ... ");
	getchar();
	
	randExponent(phi, EXPONENT_MAX, e);
	printf("Chose public exponent, e = ");
	bignum_print(e);
	printf("\nPublic key is (");
	bignum_print(e);
	printf(", ");
	bignum_print(n);
	printf(") ... ");
	getchar();
	
	bignum_inverse(e, phi, d);
	printf("Calculated private exponent, d = ");
	bignum_print(d);
	printf("\nPrivate key is (");
	bignum_print(d);
	printf(", ");
	bignum_print(n);
	printf(") ... ");
	getchar();
	
	/* Compute maximum number of bytes that can be encoded in one encryption */
	bytes = -1;
	bignum_fromint(shift, 1 << 7); /* 7 bits per char */
	bignum_fromint(bbytes, 1);
	while(bignum_less(bbytes, n)) {
		bignum_imultiply(bbytes, shift); /* Shift by one byte, NB: we use bitmask representative so this can actually be a shift... */
		bytes++;
	}

	printf("Opening file \"text.txt\" for reading\n");
	f = fopen("text.txt", "r");
	if(f == NULL) {
		printf("Failed to open file \"text.txt\". Does it exist?\n");
		return EXIT_FAILURE;
	}
	len = readFile(f, &buffer, bytes); /* len will be a multiple of bytes, to send whole chunks */
	
	printf("File \"text.txt\" read successfully, %d bytes read. Encoding byte stream in chunks of %d bytes ... ", len, bytes);
	getchar();
	printf("\n");
	encoded = encodeMessage(len, bytes, buffer, e, n);
	printf("\n\nEncoding finished successfully ... ");
	getchar();
	
	printf("Decoding encoded message ... ");
	getchar();
	printf("\n");
	decoded = decodeMessage(len/bytes, bytes, encoded, d, n);
	printf("\n\nFinished RSA demonstration!");
	
	/* Eek! This is why we shouldn't of calloc'd those! */
	for(i = 0; i < len/bytes; i++) free(encoded[i].data);
	free(encoded);
	free(decoded);
	free(buffer);
	bignum_deinit(p);
	bignum_deinit(q);
	bignum_deinit(n);
	bignum_deinit(phi);
	bignum_deinit(e);
	bignum_deinit(d);
	bignum_deinit(bbytes);
	bignum_deinit(shift);
	bignum_deinit(temp1);
	bignum_deinit(temp2);
	fclose(f);
	
	return EXIT_SUCCESS;
}
コード例 #8
0
ファイル: main.c プロジェクト: j0nas/PG3400-HomeExam2
int main() {
    encodeMessage();
    decodeMessage();
    crack();
}