Example #1
0
int upload(char *filename){
	// For simple, I use 40B hex string instead
	unsigned char fp[20];
	char hash[41];
	int res = 0;
	char fp_filename[MAXLINE];

	// 1. inquiry the server if the file is duplicated by fingerprint (a RTT)
	res = SHA1File(filename, fp);
	if(res){
		printf("Get file sha1 hash failed.\n");
		return -1;
	}
	digestToHash(fp, hash); // rabin.h
	fp_filename[0] = '\0';
	strcat(fp_filename, hash);
	strcat(fp_filename, filename);

	res = isExistsFile(fp_filename);

	if(!res){ // file existed , stop
		// 2. transfer not duplicated chunks to server
		transfer_file(fp_filename, filename);
	}

	return 0;
}
Example #2
0
static void check_magic(files_struct *fsp,connection_struct *conn)
{
	if (!*lp_magicscript(SNUM(conn)))
		return;

	DEBUG(5,("checking magic for %s\n",fsp->fsp_name));

	{
		char *p;
		if (!(p = strrchr_m(fsp->fsp_name,'/')))
			p = fsp->fsp_name;
		else
			p++;

		if (!strequal(lp_magicscript(SNUM(conn)),p))
			return;
	}

	{
		int ret;
		pstring magic_output;
		pstring fname;
		SMB_STRUCT_STAT st;
		int tmp_fd, outfd;

		pstrcpy(fname,fsp->fsp_name);
		if (*lp_magicoutput(SNUM(conn)))
			pstrcpy(magic_output,lp_magicoutput(SNUM(conn)));
		else
			slprintf(magic_output,sizeof(fname)-1, "%s.out",fname);

		chmod(fname,0755);
		ret = smbrun(fname,&tmp_fd);
		DEBUG(3,("Invoking magic command %s gave %d\n",fname,ret));
		unlink(fname);
		if (ret != 0 || tmp_fd == -1) {
			if (tmp_fd != -1)
				close(tmp_fd);
			return;
		}
		outfd = open(magic_output, O_CREAT|O_EXCL|O_RDWR, 0600);
		if (outfd == -1) {
			close(tmp_fd);
			return;
		}

		if (sys_fstat(tmp_fd,&st) == -1) {
			close(tmp_fd);
			close(outfd);
			return;
		}

		transfer_file(tmp_fd,outfd,(SMB_OFF_T)st.st_size);
		close(tmp_fd);
		close(outfd);
	}
}
Example #3
0
int upload(char *filename){
	// For simple, I use 40B hex string instead
	unsigned char fp[20];
	char hash[41];
	int res = 0;
	char fp_filename[MAXLINE];

	// 1. inquiry the server if the file is duplicated by fingerprint (a RTT)
	printf("upload:filename=%s\n", filename);
	res = SHA1File(filename, fp);
	if(res){
		printf("Get file sha1 hash failed.\n");
		return -1;
	}
	digestToHash(fp, hash); // rabin.h
	fp_filename[0] = '\0';
	strcat(fp_filename, hash);
	strcat(fp_filename, filename);

	res = isExistsFile(fp_filename, filename);

	switch(res){
		case 1:
			return 0;
			break;
		case -1:
			transfer_file(fp_filename, filename, 1);
			break;
		case -2:
			transfer_file(fp_filename, filename, 0);
			break;
		default:
			printf("ERROR!!!\n");
	}
	// sleep(1);
	// file_count ++;
	// if(file_count % 10 == 0)
		// sleep(10);
	return 0;
}
Example #4
0
void handle_get_activity()
{
    uint32_t size = 0;
    char* fn = get_data_file(&size);
    if (fn == NULL)
    {
        log_info("handle_get_activity() no valid data\n");
        return;
    }
    log_info("handle_get_activity() return %s\n", fn);

    transfer_file(fn);
}
Example #5
0
static void ldif_write_output(enum netr_SamDatabaseID database_id,
			      struct samsync_ldif_context *l)
{
	/* Write ldif data to the user's file */
	if (database_id == SAM_DATABASE_DOMAIN) {
		fprintf(l->ldif_file,
			"# SAM_DATABASE_DOMAIN: ADD ENTITIES\n");
		fprintf(l->ldif_file,
			"# =================================\n\n");
		fflush(l->ldif_file);
	} else if (database_id == SAM_DATABASE_BUILTIN) {
		fprintf(l->ldif_file,
			"# SAM_DATABASE_BUILTIN: ADD ENTITIES\n");
		fprintf(l->ldif_file,
			"# ==================================\n\n");
		fflush(l->ldif_file);
	}
	fseek(l->add_file, 0, SEEK_SET);
	transfer_file(fileno(l->add_file), fileno(l->ldif_file), (size_t) -1);

	if (database_id == SAM_DATABASE_DOMAIN) {
		fprintf(l->ldif_file,
			"# SAM_DATABASE_DOMAIN: MODIFY ENTITIES\n");
		fprintf(l->ldif_file,
			"# ====================================\n\n");
		fflush(l->ldif_file);
	} else if (database_id == SAM_DATABASE_BUILTIN) {
		fprintf(l->ldif_file,
			"# SAM_DATABASE_BUILTIN: MODIFY ENTITIES\n");
		fprintf(l->ldif_file,
			"# =====================================\n\n");
		fflush(l->ldif_file);
	}
	fseek(l->mod_file, 0, SEEK_SET);
	transfer_file(fileno(l->mod_file), fileno(l->ldif_file), (size_t) -1);
}
Example #6
0
int
main(int argc, char **argv)
{
	int					sockfd, sockfd2;
	struct sockaddr_in	servaddr;

	if (argc != 2)
		err_quit("usage: tcpcli <IPaddress>");

	// 1. inquiry the server if the file is duplicated by fingerprint (a RTT)

	sockfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(SERV_PORT+1); //
	Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);

	Connect(sockfd, (SA *) &servaddr, sizeof(servaddr));

	inquiry_by_fp(sockfd, "not_used");		/* do it all */

	close(sockfd); // yes close sockfd

	// 2. transfer not duplicated chunks to server 
	sockfd2 = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(SERV_PORT); //
	Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);

	Connect(sockfd2, (SA *) &servaddr, sizeof(servaddr));

	transfer_file(sockfd2, 0);

	close(sockfd2);

	exit(0);
}
Example #7
0
static NTSTATUS check_magic(struct files_struct *fsp)
{
	int ret;
	const char *magic_output = NULL;
	SMB_STRUCT_STAT st;
	int tmp_fd, outfd;
	TALLOC_CTX *ctx = NULL;
	const char *p;
	struct connection_struct *conn = fsp->conn;
	char *fname = NULL;
	NTSTATUS status;

	if (!*lp_magic_script(talloc_tos(), SNUM(conn))) {
		return NT_STATUS_OK;
	}

	DEBUG(5,("checking magic for %s\n", fsp_str_dbg(fsp)));

	ctx = talloc_stackframe();

	fname = fsp->fsp_name->base_name;

	if (!(p = strrchr_m(fname,'/'))) {
		p = fname;
	} else {
		p++;
	}

	if (!strequal(lp_magic_script(talloc_tos(), SNUM(conn)),p)) {
		status = NT_STATUS_OK;
		goto out;
	}

	if (*lp_magic_output(talloc_tos(), SNUM(conn))) {
		magic_output = lp_magic_output(talloc_tos(), SNUM(conn));
	} else {
		magic_output = talloc_asprintf(ctx,
				"%s.out",
				fname);
	}
	if (!magic_output) {
		status = NT_STATUS_NO_MEMORY;
		goto out;
	}

	/* Ensure we don't depend on user's PATH. */
	p = talloc_asprintf(ctx, "./%s", fname);
	if (!p) {
		status = NT_STATUS_NO_MEMORY;
		goto out;
	}

	if (chmod(fname, 0755) == -1) {
		status = map_nt_error_from_unix(errno);
		goto out;
	}
	ret = smbrun(p,&tmp_fd);
	DEBUG(3,("Invoking magic command %s gave %d\n",
		p,ret));

	unlink(fname);
	if (ret != 0 || tmp_fd == -1) {
		if (tmp_fd != -1) {
			close(tmp_fd);
		}
		status = NT_STATUS_UNSUCCESSFUL;
		goto out;
	}
	outfd = open(magic_output, O_CREAT|O_EXCL|O_RDWR, 0600);
	if (outfd == -1) {
		int err = errno;
		close(tmp_fd);
		status = map_nt_error_from_unix(err);
		goto out;
	}

	if (sys_fstat(tmp_fd, &st, false) == -1) {
		int err = errno;
		close(tmp_fd);
		close(outfd);
		status = map_nt_error_from_unix(err);
		goto out;
	}

	if (transfer_file(tmp_fd,outfd,(off_t)st.st_ex_size) == (off_t)-1) {
		int err = errno;
		close(tmp_fd);
		close(outfd);
		status = map_nt_error_from_unix(err);
		goto out;
	}
	close(tmp_fd);
	if (close(outfd) == -1) {
		status = map_nt_error_from_unix(errno);
		goto out;
	}

	status = NT_STATUS_OK;

 out:
	TALLOC_FREE(ctx);
	return status;
}
Example #8
0
int main(int argc, char *argv[])
{
    int ret = 0;
    int fd;

    parse_opts(argc, argv);

    fd = open(device, O_RDWR);
    if (fd < 0)
        pabort("can't open device");

    /*
     * spi mode
     */
    ret = ioctl(fd, SPI_IOC_WR_MODE32, &mode);
    if (ret == -1)
        pabort("can't set spi mode");

    ret = ioctl(fd, SPI_IOC_RD_MODE32, &mode);
    if (ret == -1)
        pabort("can't get spi mode");

    /*
     * bits per word
     */
    ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
    if (ret == -1)
        pabort("can't set bits per word");

    ret = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits);
    if (ret == -1)
        pabort("can't get bits per word");

    /*
     * max speed hz
     */
    ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
    if (ret == -1)
        pabort("can't set max speed hz");

    ret = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed);
    if (ret == -1)
        pabort("can't get max speed hz");

    printf("spi mode: 0x%x\n", mode);
    printf("bits per word: %d\n", bits);
    printf("max speed: %d Hz (%d KHz)\n", speed, speed/1000);

    if (input_tx && input_file)
        pabort("only one of -p and --input may be selected");

    if (input_tx)
        transfer_escaped_string(fd, input_tx);
    else if (input_file)
        transfer_file(fd, input_file);
    else
        transfer(fd, default_tx, default_rx, sizeof(default_tx));

    close(fd);

    return ret;
}
Example #9
0
static int copy_reg(const char *source, const char *dest)
{
	SMB_STRUCT_STAT source_stats;
	int saved_errno;
	int ifd = -1;
	int ofd = -1;

	if (sys_lstat (source, &source_stats) == -1)
		return -1;

	if (!S_ISREG (source_stats.st_mode))
		return -1;

	if((ifd = sys_open (source, O_RDONLY, 0)) < 0)
		return -1;

	if (unlink (dest) && errno != ENOENT)
		return -1;

#ifdef O_NOFOLLOW
	if((ofd = sys_open (dest, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0600)) < 0 )
#else
	if((ofd = sys_open (dest, O_WRONLY | O_CREAT | O_TRUNC , 0600)) < 0 )
#endif
		goto err;

	if (transfer_file(ifd, ofd, (size_t)-1) == -1)
		goto err;

	/*
	 * Try to preserve ownership.  For non-root it might fail, but that's ok.
	 * But root probably wants to know, e.g. if NFS disallows it.
	 */

#ifdef HAVE_FCHOWN
	if ((fchown(ofd, source_stats.st_uid, source_stats.st_gid) == -1) && (errno != EPERM))
#else
	if ((chown(dest, source_stats.st_uid, source_stats.st_gid) == -1) && (errno != EPERM))
#endif
		goto err;

	/*
	 * fchown turns off set[ug]id bits for non-root,
	 * so do the chmod last.
	 */

#if defined(HAVE_FCHMOD)
	if (fchmod (ofd, source_stats.st_mode & 07777))
#else
	if (chmod (dest, source_stats.st_mode & 07777))
#endif
		goto err;

	if (close (ifd) == -1)
		goto err;

	if (close (ofd) == -1)
		return -1;

	/* Try to copy the old file's modtime and access time.  */
	{
		struct utimbuf tv;

		tv.actime = source_stats.st_atime;
		tv.modtime = source_stats.st_mtime;
		utime(dest, &tv);
	}

	if (unlink (source) == -1)
		return -1;

	return 0;

  err:

	saved_errno = errno;
	if (ifd != -1)
		close(ifd);
	if (ofd != -1)
		close(ofd);
	errno = saved_errno;
	return -1;
}
Example #10
0
void handle_get_file(char* name)
{
    log_info("handle_get_file(%s)\n", name);
    transfer_file(name);
}
Example #11
0
int main(int argc, char *argv[])
{
	int ret = 0;
	int fd;

	parse_opts(argc, argv);

	fd = open(device, O_RDWR);
	if (fd < 0)
		pabort("can't open device");

	/*
	 * spi mode
	 */
	ret = ioctl(fd, SPI_IOC_WR_MODE32, &mode);
	if (ret == -1)
		pabort("can't set spi mode");

	ret = ioctl(fd, SPI_IOC_RD_MODE32, &mode);
	if (ret == -1)
		pabort("can't get spi mode");

	/*
	 * bits per word
	 */
	ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
	if (ret == -1)
		pabort("can't set bits per word");

	ret = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits);
	if (ret == -1)
		pabort("can't get bits per word");

	/*
	 * max speed hz
	 */
	ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
	if (ret == -1)
		pabort("can't set max speed hz");

	ret = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed);
	if (ret == -1)
		pabort("can't get max speed hz");

	printf("spi mode: 0x%x\n", mode);
	printf("bits per word: %d\n", bits);
	printf("max speed: %d Hz (%d KHz)\n", speed, speed/1000);

	if (input_tx && input_file)
		pabort("only one of -p and --input may be selected");

	if (input_tx)
		transfer_escaped_string(fd, input_tx);
	else if (input_file)
		transfer_file(fd, input_file);
	else if (transfer_size) {
		struct timespec last_stat;

		clock_gettime(CLOCK_MONOTONIC, &last_stat);

		while (iterations-- > 0) {
			struct timespec current;

			transfer_buf(fd, transfer_size);

			clock_gettime(CLOCK_MONOTONIC, &current);
			if (current.tv_sec - last_stat.tv_sec > interval) {
				show_transfer_rate();
				last_stat = current;
			}
		}
		printf("total: tx %.1fKB, rx %.1fKB\n",
		       _write_count/1024.0, _read_count/1024.0);
	} else
		transfer(fd, default_tx, default_rx, sizeof(default_tx));

	close(fd);

	return ret;
}
Example #12
0
static int retrieve_url(AbstractClient *const client, const std::wstring &url_string, const http_verb_t &http_verb, const URL &url, const std::wstring &post_data, const std::wstring &referrer, const std::wstring &outFileName, const bool &set_ftime, const bool &update_mode, const bool &alert, const bool &keep_failed)
{
	//Initialize the post data string
	const std::string post_data_encoded = post_data.empty() ? std::string() : ((post_data.compare(L"-") != 0) ? URL::urlEncode(Utils::wide_str_to_utf8(post_data)) : URL::urlEncode(stdin_get_line()));

	//Detect filestamp of existing file
	const uint64_t timestamp_existing = update_mode ? Utils::get_file_time(outFileName) : AbstractClient::TIME_UNKNOWN;
	if(update_mode && (timestamp_existing == AbstractClient::TIME_UNKNOWN))
	{
		std::wcerr << L"WARNING: Local file does not exist yet, going to download unconditionally!\n" << std::endl;
	}

	//Create the HTTPS connection/request
	std::wcerr << L"Connecting to " << url.getHostName() << L':' << url.getPortNo() << L", please wait..." << std::endl;
	std::unique_ptr<ConnectorThread> connector_thread (new ConnectorThread(client, http_verb, url, post_data_encoded, referrer, timestamp_existing));
	if(!connector_thread->start())
	{
		TRIGGER_SYSTEM_SOUND(alert, false);
		std::wcerr << L"ERROR: Failed to start the file connector thread!\n" << std::endl;
		return EXIT_FAILURE;
	}

	//Wait for connection
	while(!connector_thread->join(Zero::g_sigUserAbort))
	{
		//Check for user abort
		if(ABORTED_BY_USER)
		{
			std::wcerr << L"--> Aborting!\n"<< std::endl;
			connector_thread->stop(1250, true);
			std::wcerr << L"SIGINT: Operation aborted by the user !!!\n" << std::endl;
			return EXIT_FAILURE;
		}
	}

	//Add extra space
	std::wcerr << std::endl;

	//Check thread result
	const uint32_t thread_result = connector_thread->get_result();
	if(thread_result != ConnectorThread::CONNECTION_COMPLETE)
	{
		const std::wstring error_text = connector_thread->get_error_text();
		switch(thread_result)
		{
		case ConnectorThread::CONNECTION_ERR_INET:
			if(!error_text.empty())
			{
				std::wcerr << error_text << L'\n' << std::endl;
			}
			std::wcerr << "ERROR: Connection could not be established!\n" << std::endl;
			break;
		case ConnectorThread::CONNECTION_ERR_ABRT:
			std::wcerr << L"ERROR: The operation has been aborted !!!\n" << std::endl;
			break;
		default:
			std::wcerr << L"ERROR: The operation failed for an unknwon reason!\n" << std::endl;
			break;
		}
		TRIGGER_SYSTEM_SOUND(alert, false);
		return EXIT_FAILURE;
	}

	//Check for user abort
	if(ABORTED_BY_USER)
	{
		std::wcerr << L"SIGINT: Operation aborted by the user !!!\n" << std::endl;
		return EXIT_FAILURE;
	}

	//Initialize local variables
	bool success;
	uint32_t status_code;
	std::wstring content_type, content_encd;
	uint64_t file_size, timestamp;

	//Query result information
	if(!client->result(success, status_code, file_size, timestamp, content_type, content_encd))
	{
		TRIGGER_SYSTEM_SOUND(alert, false);
		const std::wstring error_text = client->get_error_text();
		if(!error_text.empty())
		{
			std::wcerr << error_text << L'\n' << std::endl;
		}
		std::wcerr << "ERROR: Failed to query the response status!\n" << std::endl;
		return EXIT_FAILURE;
	}

	//Skip download this time?
	if(update_mode && (status_code == 304))
	{
		TRIGGER_SYSTEM_SOUND(alert, true);
		std::wcerr << L"SKIPPED: Server currently does *not* provide a newer version of the file." << std::endl;
		std::wcerr << L"         Version created at '" << Utils::timestamp_to_str(timestamp_existing) << L"' was retained.\n" << std::endl;
		return EXIT_SUCCESS;
	}

	//Print some status information
	std::wcerr << L"HTTP response successfully received from server:\n";
	print_response_info(status_code, file_size, timestamp, content_type, content_encd);

	//Request successful?
	if(!success)
	{
		TRIGGER_SYSTEM_SOUND(alert, false);
		std::wcerr << "ERROR: The server failed to handle this request! [Status " << status_code << "]\n" << std::endl;
		return EXIT_FAILURE;
	}

	//Check for user abort
	if(ABORTED_BY_USER)
	{
		std::wcerr << L"SIGINT: Operation aborted by the user !!!\n" << std::endl;
		return EXIT_FAILURE;
	}

	return transfer_file(client, url_string, file_size, (set_ftime ? timestamp : 0), outFileName, alert, keep_failed);
}
Example #13
0
static void check_magic(struct files_struct *fsp)
{
    int ret;
    const char *magic_output = NULL;
    SMB_STRUCT_STAT st;
    int tmp_fd, outfd;
    TALLOC_CTX *ctx = NULL;
    const char *p;
    struct connection_struct *conn = fsp->conn;

    if (!*lp_magicscript(SNUM(conn))) {
        return;
    }

    DEBUG(5,("checking magic for %s\n",fsp->fsp_name));

    if (!(p = strrchr_m(fsp->fsp_name,'/'))) {
        p = fsp->fsp_name;
    } else {
        p++;
    }

    if (!strequal(lp_magicscript(SNUM(conn)),p)) {
        return;
    }

    ctx = talloc_stackframe();

    if (*lp_magicoutput(SNUM(conn))) {
        magic_output = lp_magicoutput(SNUM(conn));
    } else {
        magic_output = talloc_asprintf(ctx,
                                       "%s.out",
                                       fsp->fsp_name);
    }
    if (!magic_output) {
        TALLOC_FREE(ctx);
        return;
    }

    /* Ensure we don't depend on user's PATH. */
    p = talloc_asprintf(ctx, "./%s", fsp->fsp_name);
    if (!p) {
        TALLOC_FREE(ctx);
        return;
    }

    if (chmod(fsp->fsp_name,0755) == -1) {
        TALLOC_FREE(ctx);
        return;
    }
    ret = smbrun(p,&tmp_fd);
    DEBUG(3,("Invoking magic command %s gave %d\n",
             p,ret));

    unlink(fsp->fsp_name);
    if (ret != 0 || tmp_fd == -1) {
        if (tmp_fd != -1) {
            close(tmp_fd);
        }
        TALLOC_FREE(ctx);
        return;
    }
    outfd = open(magic_output, O_CREAT|O_EXCL|O_RDWR, 0600);
    if (outfd == -1) {
        close(tmp_fd);
        TALLOC_FREE(ctx);
        return;
    }

    if (sys_fstat(tmp_fd,&st) == -1) {
        close(tmp_fd);
        close(outfd);
        return;
    }

#ifdef AVM_VERY_SMALL
    AVM_VERY_SMALL_LOG
#else
    transfer_file(tmp_fd,outfd,(SMB_OFF_T)st.st_size);
#endif

    close(tmp_fd);
    close(outfd);
    TALLOC_FREE(ctx);
}
Example #14
0
int main(int argc, char *argv[]){
  ts.tv_sec = 100 / 1000;
  ts.tv_nsec = (1 % 1000) * 1000000;
  
  int socket_fd, n;
  char packaged[PACKET_SIZE];
  char buffer[PACKET_SIZE-5];
  
  //not given hostname and port
  if(argc <3){
    fprintf(stderr, "usage %s hostname port\n", argv[0]);
    exit(0);
  }
  
  //init socket
  socket_fd = socket(AF_INET, SOCK_STREAM, 0);
  
  if(socket_fd < 0){
    perror("Error opening socket");
    exit(1);
  }

  struct addrinfo hints, *servinfo, *p;
  int rv;

  memset(&hints, 0, sizeof hints);
  hints.ai_family = AF_UNSPEC; // use AF_INET6 to force IPv6
  hints.ai_socktype = SOCK_STREAM;
  
  if ((rv = getaddrinfo(argv[1], argv[2], &hints, &servinfo)) != 0)
  {
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
    exit(1);
  }
  // loop through all the results and connect to the first we can
  for(p = servinfo; p != NULL; p = p->ai_next)
  {
    if ((socket_fd = socket(p->ai_family, p->ai_socktype,
			 p->ai_protocol)) == -1)
    {
      perror("socket");
      continue;
    }

    if (connect(socket_fd, p->ai_addr, p->ai_addrlen) == -1)
    {
      close(socket_fd);
      //perror("connect");
      continue;
    }
    
    break; // if we get here, we must have connected successfully
  }
  

  // Identifying Connect command
  printf("Please enter your nickname: ");
  //create message for server
  bzero(packaged, PACKET_SIZE-1);
  bzero(buffer, PACKET_SIZE-5);
  fgets(buffer, PACKET_SIZE-5, stdin);
  buffer[strcspn(buffer, "\r\n")] = 0; // Trim newlines
  sprintf(packaged, "/CONN");
  strcat(packaged, buffer);
  
  //send message to server
  n = write(socket_fd, packaged, strlen(packaged));
  if(n < 0)
  { perror("Error identifying to server"); exit(1); }
  
  pthread_t reader_thread;
  
  if(pthread_create(&reader_thread, NULL, read_chat, &socket_fd)){
    fprintf(stderr, "Error creating reader thread\n");
    exit(1);
  }

  printf("Please enter your messages: ");
  while(1){
    
    //create message for server
    bzero(packaged, PACKET_SIZE-1);
    bzero(buffer, PACKET_SIZE-5);
    fgets(buffer, PACKET_SIZE-6, stdin);
    buffer[strcspn(buffer, "\r\n")] = 0; // Trim newlines

    //sprintf(packaged, "%04d", friend_fd);  

    // Check if file-transfer has started.
    if(strstr(buffer, "/FILE") == buffer)
    {
      if(friend_fd == 0)
      {
	printf("Cannot send file while in queue.\n");
	continue;
      }
      buffer[strcspn(buffer, "\r\n")] = 0; // Trim newlines
      char filename [PACKET_SIZE-12];
      memcpy(filename, &buffer[6], PACKET_SIZE-12);
      int size;
      struct stat st;
      stat(filename, &st);
      size = st.st_size;

      if(size > SIZE_FILE_MAX)
      {
	printf("File size exceeded.");
	continue;
      }

      strcat(packaged, "/FILE/");
      strcat(packaged, filename);

      FILE *fp;
      fp = fopen(filename, "rb"); 
      if(fp == NULL)
      { 
	perror("Error opening file");
      }
      else
      {
	//send message to server
	n = write(socket_fd, packaged, strlen(packaged));
	nanosleep(&ts, NULL);
	if(n < 0)
	  { perror("Error writing to server"); continue; }

	transfer_file(socket_fd, filename);
      }
    }

    // Majority case
    else
    {
      //strcat(packaged, buffer);
      //send message to server
      n = write(socket_fd, buffer, strlen(buffer));
      nanosleep(&ts, NULL);
      if(n < 0)
      { perror("Error writing to server"); exit(1); }
    }
  }	
  close(socket_fd);
}
Example #15
0
// get request from client socket
void parseClientRequest(player p, char * buffer) {

    // socket closed
    if(readline(p->fd, buffer, MAXBUF-1) == 0)
        removeClient(p);

    else if(strlen(buffer) > 3 && buffer[3] == '#') { // new message
#ifdef DEBUG
        printf("\r[DEBUG] : %s\n", buffer);
#endif
        buffer[3] = 0;

        // broadcast message
        if(strcmp(buffer, CMD_MESSAGE) == 0)
            broadcastMessage(p, buffer);

        // broadcast action
        else if(strcmp(buffer, CMD_ACTION) == 0)
            broadcastMessage(p, buffer);

        // bind to a game
        else if(strlen(buffer+4) > 6 && buffer[9] == '#' && strcmp(buffer, CMD_BIND) == 0)
            bindToGame(p, buffer);

        // create a game
        else if(strlen(buffer+4) > 6 && buffer[9] == '#' && strcmp(buffer, CMD_CREATE_GAME) == 0)
            createGame(p, buffer);

        // list existing games
        else if(strcmp(buffer, CMD_LIST) == 0)
            listGames(p);

        // Get available id to creage a game
        else if(strcmp(buffer, CMD_CREATE) == 0)
            getAvailableId(p);

        // Create new socket to send a file
        else if(strlen(buffer+4) > 7 && buffer[10] == '#' && strcmp(buffer, CMD_FILE) == 0)
            transfer_file(p, buffer);

        // Register as a Game Master
        else if(strcmp(buffer, CMD_REGISTER_GM) == 0)
            register_game_master(p);

        // Send a message to game master
        else if(strcmp(buffer, CMD_SEND_GM) == 0)
            send_to_game_master(p, buffer);

        // Send a message to a specific player
        else if(strcmp(buffer, CMD_SEND_TO_PLAYER) == 0)
            send_to_player(p, buffer);

        else
            senderror(p->fd, NULL, ERR_NOT_RECOGNIZED);
    }
    else {
#ifdef DEBUG
        printf("\r[DEBUG] : %s\n", buffer);
#endif
        senderror(p->fd, NULL, ERR_NOT_RECOGNIZED);
    }
}
Example #16
0
static int copy_reg(const char *source, const char *dest)
{
	SMB_STRUCT_STAT source_stats;
	int saved_errno;
	int ifd = -1;
	int ofd = -1;

	if (sys_lstat(source, &source_stats, false) == -1)
		return -1;

	if (!S_ISREG (source_stats.st_ex_mode))
		return -1;

	if (source_stats.st_ex_size > module_sizelimit) {
		DEBUG(5,
			("%s: size of %s larger than sizelimit (%lld > %lld), rename prohititted\n",
			MODULE, source,
			(long long)source_stats.st_ex_size,
			(long long)module_sizelimit));
		return -1;
	}

	if((ifd = open (source, O_RDONLY, 0)) < 0)
		return -1;

	if (unlink (dest) && errno != ENOENT) {
		close(ifd);
		return -1;
	}

#ifdef O_NOFOLLOW
	if((ofd = open (dest, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0600)) < 0 )
#else
	if((ofd = open (dest, O_WRONLY | O_CREAT | O_TRUNC , 0600)) < 0 )
#endif
		goto err;

	if (transfer_file(ifd, ofd, source_stats.st_ex_size) == -1)
		goto err;

	/*
	 * Try to preserve ownership.  For non-root it might fail, but that's ok.
	 * But root probably wants to know, e.g. if NFS disallows it.
	 */

#ifdef HAVE_FCHOWN
	if ((fchown(ofd, source_stats.st_ex_uid, source_stats.st_ex_gid) == -1) && (errno != EPERM))
#else
	if ((chown(dest, source_stats.st_ex_uid, source_stats.st_ex_gid) == -1) && (errno != EPERM))
#endif
		goto err;

	/*
	 * fchown turns off set[ug]id bits for non-root,
	 * so do the chmod last.
	 */

#if defined(HAVE_FCHMOD)
	if ((fchmod (ofd, source_stats.st_ex_mode & 07777) == -1) &&
			(errno != EPERM))
#else
	if ((chmod (dest, source_stats.st_ex_mode & 07777) == -1) &&
			(errno != EPERM))
#endif
		goto err;

	if (close (ifd) == -1)
		goto err;

	if (close (ofd) == -1)
		return -1;

	/* Try to copy the old file's modtime and access time.  */
#if defined(HAVE_UTIMENSAT)
	{
		struct timespec ts[2];

		ts[0] = source_stats.st_ex_atime;
		ts[1] = source_stats.st_ex_mtime;
		utimensat(AT_FDCWD, dest, ts, AT_SYMLINK_NOFOLLOW);
	}
#elif defined(HAVE_UTIMES)
	{
		struct timeval tv[2];

		tv[0] = convert_timespec_to_timeval(source_stats.st_ex_atime);
		tv[1] = convert_timespec_to_timeval(source_stats.st_ex_mtime);
#ifdef HAVE_LUTIMES
		lutimes(dest, tv);
#else
		utimes(dest, tv);
#endif
	}
#elif defined(HAVE_UTIME)
	{
		struct utimbuf tv;

		tv.actime = convert_timespec_to_time_t(source_stats.st_ex_atime);
		tv.modtime = convert_timespec_to_time_t(source_stats.st_ex_mtime);
		utime(dest, &tv);
	}
#endif

	if (unlink (source) == -1)
		return -1;

	return 0;

  err:

	saved_errno = errno;
	if (ifd != -1)
		close(ifd);
	if (ofd != -1)
		close(ofd);
	errno = saved_errno;
	return -1;
}