Esempio n. 1
0
int main(int argc, char **argv)
{
	FILE *peer;

	parse_opt(argc, argv);
	is_client = !!arg_servername;

	peer = get_peer(!is_client);
	pscom_openib_init(peer);

	if (!is_client) { // server
		printf("Server\n");

		if (!arg_nokill) {
			// Kill the server with SIGSTOP if the peer disappear.
			int fd = fileno(peer);
			SCALL(fcntl(fd, F_SETOWN, getpid()));
			SCALL(fcntl(fd, F_SETSIG, SIGINT));
			SCALL(fcntl(fd, F_SETFL, O_ASYNC));
		}
		run_pp_server();
	} else {
		printf("Client\n");
		do_pp_client();
	}

	return 0;
}
Esempio n. 2
0
static void serve(int client)
{
int nread, level;
short stmp;
char *peer;
char buffer[1024];

    peer = get_peer(client, buffer);
    if (peer != NULL) util_log(1, "connection from %s", peer);

    nread = util_read(client, &stmp, 2, 10);
    if (nread != 2) {
        util_log(1, "can't get level: %s", syserrmsg(errno));
    } else {
        level = ntohs(stmp);
        if (level == 6) {
            util_log(1, "REBOOT ON OPERATOR COMMAND");
            system(REBOOT);
        } else if (level == 0) {
            util_log(1, "SHUTTING DOWN ON OPERATOR COMMAND");
            system(SHUTDOWN);
        } else {
            util_log(1, "ignore unexted level %d", level);
        }
    }
    shutdown(client, 2);
    close(client);
    return;
}
Esempio n. 3
0
void py_chat_update (struct tgl_chat *C, unsigned flags) {
    if (!python_loaded) {
        return;
    }

    PyObject *peer, *types;
    PyObject *arglist, *result;

    if(_py_chat_update == NULL) {
        logprintf("Callback not set for on_chat_update");
        return;
    }

    peer = get_peer (C->id, (void *)C);
    types = get_update_types (flags);

    arglist = Py_BuildValue("(OO)", peer, types);
    result = PyEval_CallObject(_py_chat_update, arglist);
    Py_DECREF(arglist);

    if(result == NULL)
        PyErr_Print();
    else if(PyUnicode_Check(result))
        logprintf ("python: %s\n", PyBytes_AsString(PyUnicode_AsASCIIString(result)));

    Py_XDECREF(result);
}
Esempio n. 4
0
ACE_INT32 Handle_data::handle_close( ACE_HANDLE , ACE_Reactor_Mask )
{	
	get_peer().close();
	ACE_DEBUG( (LM_DEBUG, "handle data close.\n") );
	delete this;
	return 0;
}
Esempio n. 5
0
void py_user_cb (struct tgl_state *TLSR, void *cb_extra, int success, struct tgl_user *C) {
    assert (TLSR == TLS);
    PyObject *callable = cb_extra;
    PyObject *arglist = NULL;
    PyObject *peer = NULL;
    PyObject *result = NULL;

    if(PyCallable_Check(callable)) {
        if (success) {
            peer = get_peer(C->id, (void *)C);
        } else {
            Py_INCREF(Py_None);
            peer = Py_None;
        }

        arglist = Py_BuildValue("(OO)", success ? Py_True : Py_False, peer);
        result = PyEval_CallObject(callable, arglist);
        Py_DECREF(arglist);

        if(result == NULL)
            PyErr_Print();

        Py_XDECREF(result);
    }

    Py_XDECREF(callable);
}
Esempio n. 6
0
int Bcsp_Admin_Handler::handle_process()
{
	char req_buf[2048];
	int	i_rc=0,i_count=0;
	string ret_string;	
	string host;
	int port;
	char* cmd=NULL;
	//step1:recv data
	do
	{
		i_rc=read(req_buf+i_count,2000-i_count,1,1);
	 	if(i_rc<=0)break;//异常关闭
	 		i_count+=i_rc;			
	}while(strstr(req_buf,"XXEE")==NULL);	 	  
	if(i_count >0 ) 
		req_buf[i_count]='\0';
	else
		return -1;//异常处理
	get_peer(host,port);
	
	LOG_INFO_FORMAT("INFO  - [BCSP]: tcp recv [%s:%d] thread=%lu socketid=%d ,recved %d bytes :[%s] \n",host.c_str(),port,pthread_self(),getHandle(),i_count,req_buf);

	//step2:parse data
	if(!strstr(req_buf,"XXEE")) return -1;
	Pubc::replace(req_buf,"XXEE","");
	cJSON *root = cJSON_Parse(req_buf);
	get_status(root, ret_string);
	cJSON_Delete(root);
	write(ret_string.c_str(),ret_string.size(),2);
	root=NULL;
	LOG_INFO_FORMAT("INFO  -[BCSP]: tcp send [%s:%d] %s\n",host.c_str(),port,ret_string.c_str());
	return -1;
}
Esempio n. 7
0
void py_contact_list_cb (struct tgl_state *TLSR, void *cb_extra, int success, int num, struct tgl_user **UL) {
    assert (TLSR == TLS);
    PyObject *callable = cb_extra;
    PyObject *arglist = NULL;
    PyObject *peers = NULL;
    PyObject *result = NULL;

    if(PyCallable_Check(callable)) {
        peers = PyList_New(0);
        if (success) {
            int i;
            for (i = 0; i < num; i++) {
                PyList_Append(peers, get_peer (UL[i]->id, (void *)UL[i]));
            }
        }

        arglist = Py_BuildValue("(OO)", success ? Py_True : Py_False, peers);
        result = PyEval_CallObject(callable, arglist);
        Py_DECREF(arglist);

        if(result == NULL)
            PyErr_Print();

        Py_XDECREF(result);
    }

    Py_XDECREF(callable);
}
Esempio n. 8
0
int main(int argc, char **argv)
{
	FILE *peer;

	parse_opt(argc, argv);

	peer = get_peer();
	init(peer);

	if (is_server) { // server
		if (!arg_nokill) {
			// Kill the server with SIGSTOP if the peer disappear.
			int fd = fileno(peer);
			SCALL(fcntl(fd, F_SETOWN, getpid()));
			SCALL(fcntl(fd, F_SETSIG, SIGINT));
			SCALL(fcntl(fd, F_SETFL, O_ASYNC));
		}
		run_pp_server();
	} else {
		sleep(2);
		do_pp_client();
	}

	return 0;
}
Esempio n. 9
0
void WebSocketServer::_on_peer_packet(int32_t p_peer_id) {

	if (_is_multiplayer) {
		_process_multiplayer(get_peer(p_peer_id), p_peer_id);
	} else {
		emit_signal("data_received", p_peer_id);
	}
}
Esempio n. 10
0
void udp_readable_cb(EV_P_ ev_io *w, int revents)
{
  char b;
  struct sockaddr src;
  socklen_t len;
  struct Peer *p;
  (void) loop;
  (void) w;
  (void) revents;
  len = sizeof(src);
  recvfrom(sock, &b, 1, 0, &src, &len);
  p = get_peer(&src, len);
  switch (b)
  {
    case CON:
      printf("client wants to connect\n");
      if (!p)
      {
        p = new_peer();
        memcpy(&p->addr, &src, len);
        p->state = ACKNOWLEDGING;
        acknowledge(p);
      }
      else if (p->state == DEAD)
      {
        acknowledge(p);
        p->state = ACKNOWLEDGING;
      }  
      return;
    case ACK:
      if (p && (p->state == CONNECTING || p->state == ESTABLISHED))
      {
        establish(p);
        p->state = ESTABLISHED;
        printf("established\n");
      }
      return;
    case EST:
      if (p && p->state == ACKNOWLEDGING)
      {
        printf("established\n");
        p->state = ESTABLISHED;
        return;
      }
    case DIE:
      if (p)
      {
        printf("peer disconected\n");
        remove_peer(p);
      }
  }
}
Esempio n. 11
0
ACE_INT32 Handle_data::open( )
{	
	ACE_INT32 ret = 0;
	ACE_INET_Addr remote_addr;	
	get_peer().get_remote_addr( remote_addr );		
	ACE_DEBUG( (LM_DEBUG, "the remote addr is %s\n", remote_addr.get_host_addr())  );
	
	ret = reactor()->register_handler( this, ACE_Event_Handler::READ_MASK );
	if (ret != -1)	
	{		
		ACE_DEBUG( (LM_DEBUG, "handle data register ok!\n")  );		
	}	
	return ret;
}
Esempio n. 12
0
        void Channel::update()
        {
            if(m_accepting) {
                get_peer();
            } 
            
            sf::Packet packet;
            if(m_server_socket.receive(packet) == sf::Socket::Done) {
                std::string command;
                packet >> command;

                std::cerr << "Channel got command: " << command << std::endl;
                if(command == info_update) {
                    packet >> m_server_info;
                } else if(command == start_game) {
Esempio n. 13
0
peer* core::check_reconnect_peer(const uint32_t id)
{
  peer* p = get_peer(id);
  if (p) {
    outmessage outmsg;
    outmsg.begin(cmd_kick_peer);
    outmsg.write_int(id);
    outmsg.end();
    send_message(&outmsg, p->get_stream_handler());

    // notify other modules that use this peer

    p->get_stream_handler()->set_ud(NULL);
    p->set_stream_handler(NULL);
  }
  return p;
}
Esempio n. 14
0
static void
get_property (GObject *object, guint prop_id,
              GValue *value, GParamSpec *pspec)
{
	NMDeviceVeth *self = NM_DEVICE_VETH (object);
	NMDevice *peer;

	switch (prop_id) {
	case PROP_PEER:
		peer = get_peer (self);
		g_value_set_boxed (value, peer ? nm_device_get_path (peer) : "/");
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
		break;
	}
}
Esempio n. 15
0
int  Rsm_Aim_Handler::handle_process()
{
	char	req_buf[4096];
	int		i_rc=0,i_count=0;
	string	session_id;
	string  ret_string;
	string	host;
	int		port;
	//step1:recv data
	do
	{
		i_rc=read(req_buf+i_count,4000-i_count,1,1);
	 	if(i_rc<=0)break;//异常关闭
	 		i_count+=i_rc;
	}while(strstr(req_buf,"XXEE")==NULL);	  
	if(i_count >0 )
		req_buf[i_count]='\0';
	else
		return -1;//异常处理
	get_peer(host,port);
	
	LOG_INFO_FORMAT("INFO  - [RSM]: tcp recv [%s:%d] thread=%lu socketid=%d ,recved %d bytes :[%s] \n",host.c_str(),port,pthread_self(),getHandle(),i_count,req_buf);
//	printf("INFO  - [RSM]: tcp recv [%s:%d] thread=%lu socketid=%d ,recved %d bytes :[%s] \n",host.c_str(),port,pthread_self(),getHandle(),i_count,req_buf);
	 	  
	//step2:parse data
	if(!strstr(req_buf,"XXEE")) return -1;
	Pubc::replace(req_buf,"XXEE","");
	
	//step3:send data
	opt cmd;
	memset(&cmd,0,sizeof(opt));
	strcpy(cmd.cmd,req_buf);
//	cmd.Sock.setHandle(getHandle());
	cmd.Sock = getHandle();
	gettimeofday(&(cmd.opt_start),NULL);
	RES_oprate::instance()->set_opt(&cmd);
	RES_oprate::instance()->resume_operate();
	
	return -2;
}
Esempio n. 16
0
ACE_INT32 Handle_data::handle_input( ACE_HANDLE )
{	
	ACE_INT8 buf[512] = {0};
	ssize_t len;
	  
	len = get_peer().recv( buf, 500);
	if (len > 0)
	{
		ACE_DEBUG( (LM_DEBUG, "recv data %s, len:%d.\n", buf, len) );		
	    return 0;
	}
	else if (len == 0)
	{
		ACE_DEBUG( (LM_DEBUG, "recv data len is 0, client exit.\n") );
		return -1;
	}
	else
	{
		ACE_DEBUG( (LM_DEBUG, "recv data error len < 0" ) );
		return -1;
	}	
}
static GbDBusTypelib *
get_proxy (GbSourceTypelibCompletionProvider *provider)
{
   GbSourceTypelibCompletionProviderPrivate *priv = provider->priv;
   GDBusConnection *peer;

   if (!priv->proxy) {
      peer = get_peer(provider);
      if (!peer) {
         return NULL;
      }

      priv->proxy = gb_dbus_typelib_proxy_new_sync(peer,
                                                   G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS,
                                                   NULL,
                                                   "/org/gnome/Builder/Typelib",
                                                   NULL,
                                                   NULL);
      g_object_add_weak_pointer(G_OBJECT(priv->proxy),
                                (gpointer *)&priv->proxy);

      /*
       * XXX: temporary for testing.
       */
      gb_dbus_typelib_call_require_sync(priv->proxy, "cairo", "1.0", NULL, NULL);
      gb_dbus_typelib_call_require_sync(priv->proxy, "Gtk", "3.0", NULL, NULL);
      gb_dbus_typelib_call_require_sync(priv->proxy, "Gdk", "3.0", NULL, NULL);
      gb_dbus_typelib_call_require_sync(priv->proxy, "GdkPixbuf", "2.0", NULL, NULL);
      gb_dbus_typelib_call_require_sync(priv->proxy, "GdkX11", "3.0", NULL, NULL);
      gb_dbus_typelib_call_require_sync(priv->proxy, "GLib", "2.0", NULL, NULL);
      gb_dbus_typelib_call_require_sync(priv->proxy, "Gio", "2.0", NULL, NULL);
      gb_dbus_typelib_call_require_sync(priv->proxy, "GObject", "2.0", NULL, NULL);
      gb_dbus_typelib_call_require_sync(priv->proxy, "Pango", "1.0", NULL, NULL);
      gb_dbus_typelib_call_require_sync(priv->proxy, "PangoCairo", "1.0", NULL, NULL);
   }

   return priv->proxy;
}
Esempio n. 18
0
void py_dialog_list_cb (struct tgl_state *TLSR, void *cb_extra, int success, int num, tgl_peer_id_t peers[], int msgs[], int unread[]) {
    assert (TLSR == TLS);
    PyObject *callable = cb_extra;
    PyObject *arglist = NULL;
    PyObject *dialog_list = NULL;
    PyObject *dialog = NULL;
    PyObject *result = NULL;

    if(PyCallable_Check(callable)) {
        dialog_list = PyList_New(0);
        if (success) {
            int i;
            for (i = 0; i < num; i++) {
                dialog = PyDict_New();
                PyDict_SetItemString(dialog, "peer", get_peer(peers[i], tgl_peer_get (TLS, peers[i])));

                struct tgl_message *M = tgl_message_get (TLS, msgs[i]);
                if (M && (M->flags & TGLMF_CREATED)) {
                    PyDict_SetItemString(dialog, "message", get_message(M));
                }
                PyDict_SetItemString(dialog, "unread", unread[i] ? Py_True : Py_False);

                PyList_Append(dialog_list, dialog);
            }
        }

        arglist = Py_BuildValue("(OO)", success ? Py_True : Py_False, dialog_list);
        result = PyEval_CallObject(callable, arglist);
        Py_DECREF(arglist);

        if(result == NULL)
            PyErr_Print();

        Py_XDECREF(result);
    }

    Py_XDECREF(callable);
}
Esempio n. 19
0
void GstPropertiesModule::show_pad_properties()
{
	auto pad = std::dynamic_pointer_cast<PadModel>(controller->get_selected_object());

	if (!pad)
	{
		return;
	}

	PadPropertyModelColumns cols;
	auto model = Gtk::TreeStore::create(cols);
	Gtk::TreeView *tree = Gtk::manage(new Gtk::TreeView());
	tree->append_column(_("Property Name"), cols.m_col_name);
	tree->append_column(_("Property Value"), cols.m_col_value);
	tree->set_model(model);

#define APPEND_ROW(name, value) \
	do { \
		row = *(model->append()); \
		row[cols.m_col_name] = name; \
		row[cols.m_col_value] = value; \
	} while (false);

	std::string peer_pad = pad->get_peer() ? ElementPathProcessor::get_object_path(pad->get_peer()) : std::string("NO PEER PAD");

	Gtk::TreeModel::Row row;
	APPEND_ROW(_("Name"), pad->get_name());

	if (pad->get_template())
	{
		display_template_info(pad->get_template(), model, cols.m_col_name, cols.m_col_value);
	}

	APPEND_ROW(_("Presence"), get_presence_str(pad->get_presence()));
	APPEND_ROW(_("Direction"), get_direction_str(pad->get_direction()));
	APPEND_ROW(_("Peer pad"), peer_pad);

	if (pad->get_current_caps())
	{
		APPEND_ROW(_("Current caps"), "");
		display_caps(pad->get_current_caps(), model, cols.m_col_name, cols.m_col_value, row);
	}
	else
	{
		APPEND_ROW(_("Current caps"), _("unknown"));
	}

	if (pad->get_allowed_caps())
	{
		APPEND_ROW(_("Allowed caps"), "");
		display_caps(pad->get_allowed_caps(), model, cols.m_col_name, cols.m_col_value, row);
	}
	else
	{
		APPEND_ROW(_("Allowed caps"), _("unknown"));
	}

#undef APPEND_ROW

	tree->show();
	properties_box->pack_start(*tree, true, true, 0);
}
Esempio n. 20
0
abstract_actor_ptr remote_actor_impl(stream_ptr_pair io, string_set expected) {
    CPPA_LOGF_TRACE("io{" << io.first.get() << ", " << io.second.get() << "}");
    auto mm = get_middleman();
    auto pinf = mm->node();
    std::uint32_t process_id = pinf->process_id();
    // throws on error
    io.second->write(&process_id, sizeof(std::uint32_t));
    io.second->write(pinf->host_id().data(), pinf->host_id().size());
    // deserialize: actor id, process id, node id, interface
    actor_id remote_aid;
    std::uint32_t peer_pid;
    node_id::host_id_type peer_node_id;
    std::uint32_t iface_size;
    std::set<std::string> iface;
    auto& in = io.first;
    // -> actor id
    in->read(&remote_aid, sizeof(actor_id));
    // -> process id
    in->read(&peer_pid, sizeof(std::uint32_t));
    // -> node id
    in->read(peer_node_id.data(), peer_node_id.size());
    // -> interface
    in->read(&iface_size, sizeof(std::uint32_t));
    if (iface_size > max_iface_size) {
        throw std::invalid_argument("Remote actor claims to have more than"
                                    +std::to_string(max_iface_size)+
                                    " message types? Someone is trying"
                                    " something nasty!");
    }
    std::vector<char> strbuf;
    for (std::uint32_t i = 0; i < iface_size; ++i) {
        std::uint32_t str_size;
        in->read(&str_size, sizeof(std::uint32_t));
        if (str_size > max_iface_clause_size) {
            throw std::invalid_argument("Remote actor claims to have a"
                                        " reply_to<...>::with<...> clause with"
                                        " more than"
                                        +std::to_string(max_iface_clause_size)+
                                        " characters? Someone is"
                                        " trying something nasty!");
        }
        strbuf.reserve(str_size + 1);
        strbuf.resize(str_size);
        in->read(strbuf.data(), str_size);
        strbuf.push_back('\0');
        iface.insert(std::string{strbuf.data()});
    }
    // deserialization done, check interface
    if (iface != expected) {
        auto tostr = [](const std::set<std::string>& what) -> std::string {
            if (what.empty()) return "actor";
            std::string tmp;
            tmp = "typed_actor<";
            auto i = what.begin();
            auto e = what.end();
            tmp += *i++;
            while (i != e) tmp += *i++;
            tmp += ">";
            return tmp;
        };
        auto iface_str = tostr(iface);
        auto expected_str = tostr(expected);
        if (expected.empty()) {
            throw std::invalid_argument("expected remote actor to be a "
                                        "dynamically typed actor but found "
                                        "a strongly typed actor of type "
                                        + iface_str);
        }
        if (iface.empty()) {
            throw std::invalid_argument("expected remote actor to be a "
                                        "strongly typed actor of type "
                                        + expected_str +
                                        " but found a dynamically typed actor");
        }
        throw std::invalid_argument("expected remote actor to be a "
                                    "strongly typed actor of type "
                                    + expected_str +
                                    " but found a strongly typed actor of type "
                                    + iface_str);
    }
    auto pinfptr = make_counted<node_id>(peer_pid, peer_node_id);
    if (*pinf == *pinfptr) {
        // this is a local actor, not a remote actor
        CPPA_LOGF_INFO("remote_actor() called to access a local actor");
        auto ptr = get_actor_registry()->get(remote_aid);
        return ptr;
    }
    struct remote_actor_result { remote_actor_result* next; actor value; };
    std::mutex qmtx;
    std::condition_variable qcv;
    intrusive::single_reader_queue<remote_actor_result> q;
    mm->run_later([mm, io, pinfptr, remote_aid, &q, &qmtx, &qcv] {
        CPPA_LOGC_TRACE("cppa",
                        "remote_actor$create_connection", "");
        auto pp = mm->get_peer(*pinfptr);
        CPPA_LOGF_INFO_IF(pp, "connection already exists (re-use old one)");
        if (!pp) mm->new_peer(io.first, io.second, pinfptr);
        auto res = mm->get_namespace().get_or_put(pinfptr, remote_aid);
        q.synchronized_enqueue(qmtx, qcv, new remote_actor_result{0, res});
    });
    std::unique_ptr<remote_actor_result> result(q.synchronized_pop(qmtx, qcv));
    CPPA_LOGF_DEBUG(CPPA_MARG(result, get));
    return raw_access::get(result->value);
}
Esempio n. 21
0
// task_download(t, tracker_task)
//	Downloads the file specified by the input task 't' into the current
//	directory.  't' was created by start_download().
//	Starts with the first peer on 't's peer list, then tries all peers
//	until a download is successful.
static void task_download(task_t *t, task_t *tracker_task)
{
	int i, ret = -1;
	size_t messagepos;
	assert((!t || t->type == TASK_DOWNLOAD)
	       && tracker_task->type == TASK_TRACKER);

	//Read the checksum of the file from tracker:
	
	char *file_digest = 0;
	osp2p_writef(tracker_task->peer_fd, "MD5SUM %s\n", t->filename);

	messagepos = read_tracker_response(tracker_task);
	message("Tracker buf: %s\n", tracker_task->buf);
	if (tracker_task->buf[messagepos] != '2') {
	  error("* Tracker error message while requesting checksum of '%s':\n%s",
		t->filename, &tracker_task->buf[messagepos]);
	}
	else{
	  file_digest = malloc(MD5_TEXT_DIGEST_SIZE+1);
	  memcpy(file_digest, tracker_task->buf, MD5_TEXT_DIGEST_SIZE);
	  file_digest[MD5_TEXT_DIGEST_SIZE] = 0;
	}

	// Quit if no peers, and skip this peer
	if (!t || !t->peer_list) {
		error("* No peers are willing to serve '%s'\n",
		      (t ? t->filename : "that file"));
		task_free(t);
		return;
	} else if (t->peer_list->addr.s_addr == listen_addr.s_addr
		   && t->peer_list->port == listen_port)
		goto try_again;

	t->disk_fd = open(t->disk_filename, O_WRONLY | O_CREAT | O_EXCL, 0666);
	if (t->disk_fd == -1 && errno != EEXIST) {
	  error("* Cannot open local file");
	  goto try_again;
	} else if (t->disk_fd != -1) 
	  message("* Saving result to '%s'\n", t->disk_filename);
	
	int blockno = 0;
	int i_peer = 0;
	peer_t *apeer;
	while(1){
	  apeer = get_peer(t->peer_list, i_peer);
	
	// Connect to the peer and write the GET command
	message("* Connecting to %s:%d to download '%s'\n",
		inet_ntoa(apeer->addr), apeer->port,
		t->filename);
	t->peer_fd = open_socket(apeer->addr, apeer->port);
	if (t->peer_fd == -1) {
		error("* Cannot connect to peer: %s\n", strerror(errno));
		goto try_again;
	}
	if(evil_mode == 0)
	  osp2p_writef(t->peer_fd, "GET %s%d OSP2P\n", t->filename, blockno);
	else{
	  //*******************************
	  //Exercise 3: try to overflow a peer's buffer by requesting a file with a long name
	  
	  char evil_name[2*FILENAMESIZ];
	  int i_name;
	  for(i_name = 0; i_name < 2*FILENAMESIZ - 1; i_name++)
	    evil_name[i_name] = 'a';
	  evil_name[i_name] = 0;
	  osp2p_writef(t->peer_fd, "GET %s OSP2P\n", evil_name);

	  //**********************************
	}

	// Open disk file for the result.
	// If the filename already exists, save the file in a name like
	// "foo.txt~1~".  However, if there are 50 local files, don't download
	// at all.
	/*	for (i = 0; i < 50; i++) {
		if (i == 0)
			strcpy(t->disk_filename, t->filename);
		else
			sprintf(t->disk_filename, "%s~%d~", t->filename, i);
		t->disk_fd = open(t->disk_filename,
				  O_WRONLY | O_CREAT | O_EXCL, 0666);
		if (t->disk_fd == -1 && errno != EEXIST) {
			error("* Cannot open local file");
			goto try_again;
		} else if (t->disk_fd != -1) {
			message("* Saving result to '%s'\n", t->disk_filename);
			break;
		}
	}
	if (t->disk_fd == -1) {
		error("* Too many local files like '%s' exist already.\n\
* Try 'rm %s.~*~' to remove them.\n", t->filename, t->filename);
		task_free(t);
		return;
	}*/





	lseek(t->disk_fd, BLKSIZE, SEEK_CUR);

	// Read the file into the task buffer from the peer,
	// and write it from the task buffer onto disk.
	while (1) {
		int ret = read_to_taskbuf(t->peer_fd, t);
		if (ret == TBUF_ERROR) {
			error("* Peer read error");
			goto try_again;
		} else if (ret == TBUF_END && t->head == t->tail)
			/* End of file */
			break;

		ret = write_from_taskbuf(t->disk_fd, t);
		if (ret == TBUF_ERROR) {
			error("* Disk write error");
			goto try_again;
		}

		//*********************************
		//Exercise 2: prevent from downloading a file that is too large

		if(t->total_written > MAX_FILE_SIZE){
		  error("* Error: file too big for download\n");
		  goto try_again;
		}

		//**********************************
	}

	if(ret == TBUF_END && t->head == t->tail)
	  break;

	//Compare the checksum of file on disk to checksum reported by tracker: 
	if(file_digest){
	char *download_digest = create_digest(t->disk_filename);
	message("* Tracker's checksum for file '%s' is: %s\n", t->filename,
		file_digest);
	message("* Checksum of the downloaded file is: %s\n", download_digest);
	if(strcmp(file_digest, download_digest) != 0){
	  error("* Downloaded a corrupted file!!! Try download again...\n");
	}
	}

	blockno++;
	i_peer++;
	}

	// Empty files are usually a symptom of some error.
	if (t->total_written > 0) {
		message("* Downloaded '%s' was %lu bytes long\n",
			t->disk_filename, (unsigned long) t->total_written);
		// Inform the tracker that we now have the file,
		// and can serve it to others!  (But ignore tracker errors.)
		if (strcmp(t->filename, t->disk_filename) == 0) {
			osp2p_writef(tracker_task->peer_fd, "HAVE %s\n",
				     t->filename);
			(void) read_tracker_response(tracker_task);
		}
		task_free(t);
		return;
	}
	error("* Download was empty, trying next peer\n");

    try_again:
	if (t->disk_filename[0])
		unlink(t->disk_filename);
	// recursive call
	task_pop_peer(t);
	task_download(t, tracker_task);
}