Ejemplo n.º 1
0
void
copy_file (char const *from, char const *to, struct stat *tost,
	   int to_flags, mode_t mode, bool to_dir_known_to_exist)
{
  int tofd;

  if (debug & 4)
    say ("Copying %s %s to %s\n",
	 S_ISLNK (mode) ? "symbolic link" : "file",
	 quotearg_n (0, from), quotearg_n (1, to));

  if (S_ISLNK (mode))
    {
      char *buffer = xmalloc (PATH_MAX);

      if (readlink (from, buffer, PATH_MAX) < 0)
	pfatal ("Can't read %s %s", "symbolic link", from);
      if (symlink (buffer, to) != 0)
	pfatal ("Can't create %s %s", "symbolic link", to);
      if (tost && lstat (to, tost) != 0)
	pfatal ("Can't get file attributes of %s %s", "symbolic link", to);
      free (buffer);
    }
  else
    {
      assert (S_ISREG (mode));
      tofd = create_file (to, O_WRONLY | O_BINARY | to_flags, mode,
			  to_dir_known_to_exist);
      copy_to_fd (from, tofd);
      if (tost && fstat (tofd, tost) != 0)
	pfatal ("Can't get file attributes of %s %s", "file", to);
      if (close (tofd) != 0)
	write_fatal ();
    }
}
Ejemplo n.º 2
0
static void
handle_ended_download(DCUserConn *uc, bool success, const char *reason)
{
    bytes_received += uc->transfer_pos - uc->transfer_start;
    if (uc->occupied_slot) {
        used_dl_slots--;
        uc->occupied_slot = false;
    }
    /* If we removed from the queued item during download,
     * queue_pos will point outside the queue. */
    if (uc->queued_valid) {
        DCQueuedFile *queued;

        /*
        queued = uc->info->download_queue->buf[uc->queue_pos];
        uc->queue_pos++;
        */
        queued = (DCQueuedFile*) ptrv_remove(uc->info->download_queue, uc->queue_pos);
        uc->queued_valid = false;
        if (success) {
            queued->status = DC_QS_DONE;
            if (queued->flag == DC_TF_LIST) {
                if (uc->local_file != NULL) {
                    ptrv_append(delete_files, xstrdup(uc->local_file));
                }
                if (browse_user != NULL && strcmp(browse_user->nick, uc->info->nick) == 0 && browse_list == NULL) {
                    add_parse_request(browse_list_parsed, uc->local_file, xstrdup(browse_user->nick));
                }
            } else {
                char *final_file = xstrndup(uc->local_file, strlen(uc->local_file)-5);
                if (safe_rename(uc->local_file, final_file) != 0) {
                    warn(_("%s: Cannot rename file to %s - %s\n"), quotearg_n(0, uc->local_file), quote_n(1, final_file), errstr);
                    reason = _("cannot rename file"); /* XXX: would like a more elaborate error message here perhaps? */
                    queued->status = DC_QS_ERROR;
                    success = false;
                }
                free(final_file);
            }
        } else {
            queued->status = DC_QS_ERROR;
        }
        display_transfer_ended_msg(false, uc, success, " (%s)", reason);
    } else {
        display_transfer_ended_msg(false, uc, success, " but unqueued (%s)", reason);
    }
    free(uc->transfer_file);
    free(uc->local_file);
    uc->transfer_file = NULL;
    uc->local_file = NULL;
    uc->transfer_start = 0;
    uc->transfer_pos = 0;
    uc->transferring = false;
}
Ejemplo n.º 3
0
static void
display_transfer_ended_msg(bool upload, DCUserConn *uc, bool success, const char *extras_fmt, ...)
{
    char timebuf[LONGEST_ELAPSED_TIME+1];
    char ratebuf[LONGEST_HUMAN_READABLE+1];
    char sizebuf[LONGEST_HUMAN_READABLE+1];
    char *str1;
    char *str2;
    time_t now;
    uint64_t len;
    va_list args;

    len = uc->transfer_pos - uc->transfer_start;

    if (uc->transfer_time == (time_t) -1) {
        str2 = xstrdup("");
    } else {
        time(&now);
        if (now == (time_t) -1) {
            warn(_("Cannot get current time - %s\n"), errstr);
            str2 = xstrdup("");
        } else {
            str2 = xasprintf(_(" in %s (%s/s)"),
                             elapsed_time_to_string(now - uc->transfer_time, timebuf),
                             human_readable(
                                 len/MAX(now - uc->transfer_time, 1), ratebuf,
                                 human_suppress_point_zero|human_autoscale|human_base_1024|human_SI|human_B,
                                 1, 1));
        }
    }

    va_start(args, extras_fmt);
    str1 = xvasprintf(extras_fmt, args);
    va_end(args);

    flag_putf(upload ? DC_DF_UPLOAD : DC_DF_DOWNLOAD,
              _("%s: %s of %s %s%s. %s %s%s.\n"),
              quotearg_n(0, uc->info->nick),
              upload ? _("Upload") : _("Download"),
              quote_n(1, base_name(uc->transfer_file)),
              success ? _("succeeded") : _("failed"),
              str1,
              human_readable(len, sizebuf, human_suppress_point_zero|human_autoscale|human_base_1024|human_SI|human_B, 1, 1),
              ngettext("transferred", "transferred", len),
              str2);

    free(str1);
    free(str2);
}
Ejemplo n.º 4
0
void
move_file (char const *from, bool *from_needs_removal,
	   struct stat const *fromst,
	   char const *to, mode_t mode, bool backup)
{
  struct stat to_st;
  int to_errno;

  to_errno = stat_file (to, &to_st);
  if (backup)
    create_backup (to, to_errno ? NULL : &to_st, false);
  if (! to_errno)
    insert_file_id (&to_st, OVERWRITTEN);

  if (from)
    {
      if (S_ISLNK (mode))
	{
	  bool to_dir_known_to_exist = false;

	  /* FROM contains the contents of the symlink we have patched; need
	     to convert that back into a symlink. */
	  char *buffer = xmalloc (PATH_MAX);
	  int fd, size = 0, i;

	  if ((fd = open (from, O_RDONLY | O_BINARY)) < 0)
	    pfatal ("Can't reopen file %s", quotearg (from));
	  while ((i = read (fd, buffer + size, PATH_MAX - size)) > 0)
	    size += i;
	  if (i != 0 || close (fd) != 0)
	    read_fatal ();
	  buffer[size] = 0;

	  if (! backup)
	    {
	      if (unlink (to) == 0)
		to_dir_known_to_exist = true;
	    }
	  if (symlink (buffer, to) != 0)
	    {
	      if (errno == ENOENT && ! to_dir_known_to_exist)
		makedirs (to);
	      if (symlink (buffer, to) != 0)
		pfatal ("Can't create %s %s", "symbolic link", to);
	    }
	  free (buffer);
	  if (lstat (to, &to_st) != 0)
	    pfatal ("Can't get file attributes of %s %s", "symbolic link", to);
	  insert_file_id (&to_st, CREATED);
	}
      else
	{
	  if (debug & 4)
	    say ("Renaming file %s to %s\n",
		 quotearg_n (0, from), quotearg_n (1, to));

	  if (rename (from, to) != 0)
	    {
	      bool to_dir_known_to_exist = false;

	      if (errno == ENOENT
		  && (to_errno == -1 || to_errno == ENOENT))
		{
		  makedirs (to);
		  to_dir_known_to_exist = true;
		  if (rename (from, to) == 0)
		    goto rename_succeeded;
		}

	      if (errno == EXDEV)
		{
		  struct stat tost;
		  if (! backup)
		    {
		      if (unlink (to) == 0)
			to_dir_known_to_exist = true;
		      else if (errno != ENOENT)
			pfatal ("Can't remove file %s", quotearg (to));
		    }
		  copy_file (from, to, &tost, 0, mode, to_dir_known_to_exist);
		  insert_file_id (&tost, CREATED);
		  return;
		}

	      pfatal ("Can't rename file %s to %s",
		      quotearg_n (0, from), quotearg_n (1, to));
	    }

	rename_succeeded:
	  insert_file_id (fromst, CREATED);
	  /* Do not clear *FROM_NEEDS_REMOVAL if it's possible that the
	     rename returned zero because FROM and TO are hard links to
	     the same file.  */
	  if ((0 < to_errno
	       || (to_errno == 0 && to_st.st_nlink <= 1))
	      && from_needs_removal)
	    *from_needs_removal = false;
	}
    }
  else if (! backup)
    {
      if (debug & 4)
	say ("Removing file %s\n", quotearg (to));
      if (unlink (to) != 0 && errno != ENOENT)
	pfatal ("Can't remove file %s", quotearg (to));
    }
}
Ejemplo n.º 5
0
void
create_backup (char const *to, const struct stat *to_st, bool leave_original)
{
  /* When the input to patch modifies the same file more than once, patch only
     backs up the initial version of each file.

     To figure out which files have already been backed up, patch remembers the
     files that replace the original files.  Files not known already are backed
     up; files already known have already been backed up before, and are
     skipped.

     When a patch tries to delete a file, in order to not break the above
     logic, we merely remember which file to delete.  After the entire patch
     file has been read, we delete all files marked for deletion which have not
     been recreated in the meantime.  */

  if (to_st && ! (S_ISREG (to_st->st_mode) || S_ISLNK (to_st->st_mode)))
    fatal ("File %s is not a %s -- refusing to create backup",
	   to, S_ISLNK (to_st->st_mode) ? "symbolic link" : "regular file");

  if (to_st && lookup_file_id (to_st) == CREATED)
    {
      if (debug & 4)
	say ("File %s already seen\n", quotearg (to));
    }
  else
    {
      int try_makedirs_errno = 0;
      char *bakname;

      if (origprae || origbase || origsuff)
	{
	  char const *p = origprae ? origprae : "";
	  char const *b = origbase ? origbase : "";
	  char const *s = origsuff ? origsuff : "";
	  char const *t = to;
	  size_t plen = strlen (p);
	  size_t blen = strlen (b);
	  size_t slen = strlen (s);
	  size_t tlen = strlen (t);
	  char const *o;
	  size_t olen;

	  for (o = t + tlen, olen = 0;
	       o > t && ! ISSLASH (*(o - 1));
	       o--)
	    /* do nothing */ ;
	  olen = t + tlen - o;
	  tlen -= olen;
	  bakname = xmalloc (plen + tlen + blen + olen + slen + 1);
	  memcpy (bakname, p, plen);
	  memcpy (bakname + plen, t, tlen);
	  memcpy (bakname + plen + tlen, b, blen);
	  memcpy (bakname + plen + tlen + blen, o, olen);
	  memcpy (bakname + plen + tlen + blen + olen, s, slen + 1);

	  if ((origprae
	       && (contains_slash (origprae + FILE_SYSTEM_PREFIX_LEN (origprae))
		   || contains_slash (to)))
	      || (origbase && contains_slash (origbase)))
	    try_makedirs_errno = ENOENT;
	}
      else
	{
	  bakname = find_backup_file_name (to, backup_type);
	  if (!bakname)
	    xalloc_die ();
	}

      if (! to_st)
	{
	  int fd;

	  if (debug & 4)
	    say ("Creating empty file %s\n", quotearg (bakname));

	  try_makedirs_errno = ENOENT;
	  unlink (bakname);
	  while ((fd = creat (bakname, 0666)) < 0)
	    {
	      if (errno != try_makedirs_errno)
		pfatal ("Can't create file %s", quotearg (bakname));
	      makedirs (bakname);
	      try_makedirs_errno = 0;
	    }
	  if (close (fd) != 0)
	    pfatal ("Can't close file %s", quotearg (bakname));
	}
      else if (leave_original)
	create_backup_copy (to, bakname, to_st, try_makedirs_errno == 0);
      else
	{
	  if (debug & 4)
	    say ("Renaming file %s to %s\n",
		 quotearg_n (0, to), quotearg_n (1, bakname));
	  while (rename (to, bakname) != 0)
	    {
	      if (errno == try_makedirs_errno)
		{
		  makedirs (bakname);
		  try_makedirs_errno = 0;
		}
	      else if (errno == EXDEV)
		{
		  create_backup_copy (to, bakname, to_st,
				      try_makedirs_errno == 0);
		  unlink (to);
		  break;
		}
	      else
		pfatal ("Can't rename file %s to %s",
			quotearg_n (0, to), quotearg_n (1, bakname));
	    }
	}
      free (bakname);
    }
}
Ejemplo n.º 6
0
void
move_file (char const *from, int volatile *from_needs_removal,
	   char *to, mode_t mode, int backup)
{
  struct stat to_st;
  int to_errno = ! backup ? -1 : stat (to, &to_st) == 0 ? 0 : errno;

  if (backup)
    {
      int try_makedirs_errno = 0;
      char *bakname;

      if (origprae || origbase)
	{
	  char const *p = origprae ? origprae : "";
	  char const *b = origbase ? origbase : "";
	  char const *o = base_name (to);
	  size_t plen = strlen (p);
	  size_t tlen = o - to;
	  size_t blen = strlen (b);
	  size_t osize = strlen (o) + 1;
	  bakname = xmalloc (plen + tlen + blen + osize);
	  memcpy (bakname, p, plen);
	  memcpy (bakname + plen, to, tlen);
	  memcpy (bakname + plen + tlen, b, blen);
	  memcpy (bakname + plen + tlen + blen, o, osize);
	  for (p += FILESYSTEM_PREFIX_LEN (p);  *p;  p++)
	    if (ISSLASH (*p))
	      {
		try_makedirs_errno = ENOENT;
		break;
	      }
	}
      else
	{
	  bakname = find_backup_file_name (to, backup_type);
	  if (!bakname)
	    memory_fatal ();
	}

      if (to_errno)
	{
	  int fd;

	  if (debug & 4)
	    say ("Creating empty unreadable file %s\n", quotearg (bakname));

	  try_makedirs_errno = ENOENT;
	  unlink (bakname);
	  while ((fd = creat (bakname, 0)) < 0)
	    {
	      if (errno != try_makedirs_errno)
		pfatal ("Can't create file %s", quotearg (bakname));
	      makedirs (bakname);
	      try_makedirs_errno = 0;
	    }
	  if (close (fd) != 0)
	    pfatal ("Can't close file %s", quotearg (bakname));
	}
      else
	{
	  if (debug & 4)
	    say ("Renaming file %s to %s\n",
		 quotearg_n (0, to), quotearg_n (1, bakname));
	  while (rename (to, bakname) != 0)
	    {
	      if (errno != try_makedirs_errno)
		pfatal ("Can't rename file %s to %s",
			quotearg_n (0, to), quotearg_n (1, bakname));
	      makedirs (bakname);
	      try_makedirs_errno = 0;
	    }
	}

      free (bakname);
    }

  if (from)
    {
      if (debug & 4)
	say ("Renaming file %s to %s\n",
	     quotearg_n (0, from), quotearg_n (1, to));

      if (rename (from, to) == 0)
	*from_needs_removal = 0;
      else
	{
	  int to_dir_known_to_exist = 0;

	  if (errno == ENOENT
	      && (to_errno == -1 || to_errno == ENOENT))
	    {
	      makedirs (to);
	      to_dir_known_to_exist = 1;
	      if (rename (from, to) == 0)
		{
		  *from_needs_removal = 0;
		  return;
		}
	    }

	  if (errno == EXDEV)
	    {
	      if (! backup)
		{
		  if (unlink (to) == 0)
		    to_dir_known_to_exist = 1;
		  else if (errno != ENOENT)
		    pfatal ("Can't remove file %s", quotearg (to));
		}
	      if (! to_dir_known_to_exist)
		makedirs (to);
	      copy_file (from, to, 0, mode);
	      return;
	    }

	  pfatal ("Can't rename file %s to %s",
		  quotearg_n (0, from), quotearg_n (1, to));
	}
    }
  else if (! backup)
    {
      if (debug & 4)
	say ("Removing file %s\n", quotearg (to));
      if (unlink (to) != 0)
	pfatal ("Can't remove file %s", quotearg (to));
    }
}
Ejemplo n.º 7
0
static void
hub_handle_command(char *buf, uint32_t len)
{
    char *hub_my_nick; /* XXX */

    hub_my_nick = main_to_hub_string(my_nick);

    if (len >= 6 && strncmp(buf, "$Lock ", 6) == 0) {
        char *key;

        if (!check_state(buf, (DCUserState) DC_HUB_LOCK))
            goto hub_handle_command_cleanup;

        key = (char*) memmem(buf+6, len-6, " Pk=", 4);
        if (key == NULL) {
            warn(_("Invalid $Lock message: Missing Pk value\n"));
            key = buf+len;
        }
        key = decode_lock(buf+6, key-buf-6, DC_CLIENT_BASE_KEY);
        if (strleftcmp("EXTENDEDPROTOCOL", buf+6) == 0) {
            if (!hub_putf("$Supports TTHSearch NoGetINFO NoHello|")) {
                free(key);
                goto hub_handle_command_cleanup;
            }
        }
        if (!hub_putf("$Key %s|", key)) {
            free(key);
            goto hub_handle_command_cleanup;
        }
        free(key);
        if (!hub_putf("$ValidateNick %s|", hub_my_nick))
            goto hub_handle_command_cleanup;
        hub_state = DC_HUB_HELLO;
    }
    else if (len >= 10 && strncmp(buf, "$Supports ", 10) == 0) {
        char *p0, *p1;

        hub_extensions = 0;
        for (p0 = buf+10; (p1 = strchr(p0, ' ')) != NULL; p0 = p1+1) {
            *p1 = '\0';
            parse_hub_extension(p0);
        }
        if (*p0 != '\0')
            parse_hub_extension(p0);
    }
    else if (strcmp(buf, "$GetPass") == 0) {
        if (my_password == NULL) {
            screen_putf(_("Hub requires password.\n"));
            hub_disconnect();
            goto hub_handle_command_cleanup;
        }
        screen_putf(_("Sending password to hub.\n"));
        if (!hub_putf("$MyPass %s|", my_password))
            goto hub_handle_command_cleanup;
    }
    else if (strcmp(buf, "$BadPass") == 0) {
        warn(_("Password not accepted.\n"));
        hub_disconnect();
    }
    else if (strcmp(buf, "$LogedIn") == 0) {
        screen_putf(_("You have received operator status.\n"));
    }
    else if (len >= 9 && strncmp(buf, "$HubName ", 9) == 0) {
        free(hub_name);
        hub_name = hub_to_main_string(buf + 9);
        screen_putf(_("Hub name is %s.\n"), quotearg(hub_name));
    }
    else if (strcmp(buf, "$GetNetInfo") == 0) {
        hub_putf("$NetInfo %d$1$%c|", my_ul_slots, is_active ? 'A' : 'P');
    }
    else if (strcmp(buf, "$ValidateDenide") == 0) {
        if (!check_state(buf, (DCUserState) DC_HUB_HELLO))
            goto hub_handle_command_cleanup;
        /* DC++ disconnects immediately if this is received.
         * But shouldn't we give the client a chance to change the nick?
         * Also what happens if we receive this when correctly logged in?
         */
        warn(_("Hub did not accept nick. Nick may be in use.\n"));
        hub_disconnect();
    }
    else if (len >= 7 && strncmp(buf, "$Hello ", 7) == 0) {
        DCUserInfo *ui;
        char *conv_nick;

        conv_nick = hub_to_main_string(buf + 7);

        if (hub_state == DC_HUB_HELLO) {
            if (strcmp(buf+7, hub_my_nick) == 0) {
                screen_putf(_("Nick accepted. You are now logged in.\n"));
            } else {
                /* This probably won't happen, but better safe... */
                free(my_nick);
                my_nick = xstrdup(conv_nick);
                free(hub_my_nick);
                hub_my_nick = xstrdup(buf + 7);
                screen_putf(_("Nick accepted but modified to %s. You are now logged in.\n"), quotearg(my_nick));
            }

            ui = user_info_new(conv_nick);
            ui->info_quered = true; /* Hub is sending this automaticly */
            hmap_put(hub_users, ui->nick, ui);

            free (conv_nick);

            if (!hub_putf("$Version 1,0091|"))
                goto hub_handle_command_cleanup;
            if (!hub_putf("$GetNickList|"))
                goto hub_handle_command_cleanup;
            if (!send_my_info())
                goto hub_handle_command_cleanup;

            hub_state = DC_HUB_LOGGED_IN;
        } else {
            flag_putf(DC_DF_JOIN_PART, _("User %s logged in.\n"), quotearg(conv_nick));
            ui = user_info_new(conv_nick);
            hmap_put(hub_users, ui->nick, ui);
            free (conv_nick);
            if ((hub_extensions & HUB_EXT_NOGETINFO) == 0) {
                if (!hub_putf("$GetINFO %s %s|", buf+7, hub_my_nick))
                    goto hub_handle_command_cleanup;
                ui->info_quered = true;
            }
        }
    }
    else if (len >= 8 && strncmp(buf, "$MyINFO ", 8) == 0) {
        DCUserInfo *ui;
        char *token;
        uint32_t len;
        char* conv_buf;
        char *work_buf;

        buf += 8;
        work_buf = conv_buf = hub_to_main_string(buf);
        token = strsep(&work_buf, " ");
        if (strcmp(token, "$ALL") != 0) {
            warn(_("Invalid $MyINFO message: Missing $ALL parameter, ignoring\n"));
            free(conv_buf);
            goto hub_handle_command_cleanup;
        }

        token = strsep(&work_buf, " ");
        if (token == NULL) {
            warn(_("Invalid $MyINFO message: Missing nick parameter, ignoring\n"));
            free(conv_buf);
            goto hub_handle_command_cleanup;
        }
        ui = (DCUserInfo*) hmap_get(hub_users, token);
        if (ui == NULL) {
            /*
             * if the full buf has not been converted from hub to local charset,
             * we should try to convert nick only
             */
            /*
            char *conv_nick = hub_to_main_string(token);
            if ((ui = hmap_get(hub_users, conv_nick)) == NULL) {
            */
            ui = user_info_new(token);
            ui->info_quered = true;
            hmap_put(hub_users, ui->nick, ui);
            /*
            }
            free(conv_nick);
            */
        }

        token = strsep(&work_buf, "$");
        if (token == NULL) {
            warn(_("Invalid $MyINFO message: Missing description parameter, ignoring\n"));
            free(conv_buf);
            goto hub_handle_command_cleanup;
        }
        free(ui->description);
        ui->description = xstrdup(token);

        token = strsep(&work_buf, "$");
        if (token == NULL) {
            warn(_("Invalid $MyINFO message: Missing description separator, ignoring\n"));
            free(conv_buf);
            goto hub_handle_command_cleanup;
        }

        token = strsep(&work_buf, "$");
        if (token == NULL) {
            warn(_("Invalid $MyINFO message: Missing connection speed, ignoring\n"));
            free(conv_buf);
            goto hub_handle_command_cleanup;
        }
        len = strlen(token);
        free(ui->speed);
        if (len == 0) {
            ui->speed = xstrdup("");
            ui->level = 0; /* XXX: or 1? acceptable level? */
        } else {
            ui->speed = xstrndup(token, len-1);
            ui->level = token[len-1];
        }

        token = strsep(&work_buf, "$");
        if (token == NULL) {
            warn(_("Invalid $MyINFO message: Missing e-mail address, ignoring\n"));
            free(conv_buf);
            goto hub_handle_command_cleanup;
        }
        free(ui->email);
        ui->email = xstrdup(token);

        token = strsep(&work_buf, "$");
        if (token == NULL) {
            warn(_("Invalid $MyINFO message: Missing share size, ignoring\n"));
            free(conv_buf);
            goto hub_handle_command_cleanup;
        }
        if (!parse_uint64(token, &ui->share_size)) {
            warn(_("Invalid $MyINFO message: Invalid share size, ignoring\n"));
            free(conv_buf);
            goto hub_handle_command_cleanup;
        }

        if (ui->active_state == DC_ACTIVE_RECEIVED_PASSIVE
                || ui->active_state == DC_ACTIVE_KNOWN_ACTIVE)
            ui->active_state = DC_ACTIVE_UNKNOWN;

        /* XXX: Now that user's active_state may have changed, try queue again? */
        free(conv_buf);
    }
    else if (strcmp(buf, "$HubIsFull") == 0) {
        warn(_("Hub is full.\n"));
        /* DC++ does not disconnect immediately. So I guess we won't either. */
        /* Maybe we should be expecting an "hub follow" message? */
        /* hub_disconnect(); */
    }
    else if (len >= 3 && (buf[0] == '<' || strncmp(buf, " * ", 3) == 0)) {
        char *head;
        char *tail;
        char *msg;
        bool first = true;
        /*
        int scrwidth;
        size_t firstlen;
        size_t otherlen;

        screen_get_size(NULL, &scrwidth);
        firstlen = scrwidth - strlen(_("Public:"));
        otherlen = scrwidth - strlen(_(" | "));
        */

        msg = prepare_chat_string_for_display(buf);

        for (head = msg; (tail = strchr(head, '\n')) != NULL; head = tail+1) {
            /*PtrV *wrapped;*/

            if (tail[-1] == '\r') /* end > buf here, buf[0] == '<' or ' ' */
                tail[-1] = '\0';
            else
                tail[0] = '\0';

            /*wrapped = wordwrap(quotearg(buf), first ? firstlen : otherlen, otherlen);
            for (c = 0; c < wrapped->cur; c++)
            flag_putf(DC_DF_PUBLIC_CHAT, first ? _("Public: %s\n") : _(" | %s\n"), );
            ptrv_foreach(wrapped, free);
            ptrv_free(wrapped);*/
            flag_putf(DC_DF_PUBLIC_CHAT, first ? _("Public: %s\n") : _(" | %s\n"), quotearg(head));
            first = false;
        }
        flag_putf(DC_DF_PUBLIC_CHAT, first ? _("Public: %s\n") : _(" | %s\n"), quotearg(head));
        free(msg);
    }
    else if (len >= 5 && strncmp(buf, "$To: ", 5) == 0) {
        char *msg;
        char *tail;
        char *frm;
        char *head;
        bool first = true;

        msg = strchr(buf+5, '$');
        if (msg == NULL) {
            warn(_("Invalid $To message: Missing text separator, ignoring\n"));
            goto hub_handle_command_cleanup;
        }
        *msg = '\0';
        msg++;

        /* FIXME: WTF is this? Remove multiple "From: "? Why!? */
        frm = buf+5;
        while ((tail = strstr(msg, "From: ")) != NULL && tail < msg)
            frm = tail+6;

        msg = prepare_chat_string_for_display(msg);
        frm = prepare_chat_string_for_display(frm);
        for (head = msg; (tail = strchr(head, '\n')) != NULL; head = tail+1) {
            if (tail[-1] == '\r') /* tail > buf here because head[0] == '<' or ' ' */
                tail[-1] = '\0';
            else
                tail[0] = '\0';
            if (first) {
                screen_putf(_("Private: [%s] %s\n"), quotearg_n(0, frm), quotearg_n(1, head));
                first = false;
            } else {
                screen_putf(_(" | %s\n"), quotearg(head));
            }
        }
        if (first) {
            screen_putf(_("Private: [%s] %s\n"), quotearg_n(0, frm), quotearg_n(1, head));
        } else {
            screen_putf(_(" | %s\n"), quotearg(head));
        }
        free(msg);
        free(frm);
    }
    else if (len >= 13 && strncmp(buf, "$ConnectToMe ", 13) == 0) {
        struct sockaddr_in addr;

        buf += 13;
        if (strsep(&buf, " ") == NULL) {
            warn(_("Invalid $ConnectToMe message: Missing or invalid nick\n"));
            goto hub_handle_command_cleanup;
        }
        if (!parse_ip_and_port(buf, &addr, 0)) {
            warn(_("Invalid $ConnectToMe message: Invalid address specification.\n"));
            goto hub_handle_command_cleanup;
        }

        flag_putf(DC_DF_CONNECTIONS, _("Connecting to user on %s\n"), sockaddr_in_str(&addr));
        user_connection_new(&addr, -1);
    }
    else if (len >= 16 && strncmp(buf, "$RevConnectToMe ", 16) == 0) {
        char *nick;
        char *local_nick;
        DCUserInfo *ui;

        nick = strtok(buf+16, " ");
        if (nick == NULL) {
            warn(_("Invalid $RevConnectToMe message: Missing nick parameter\n"));
            goto hub_handle_command_cleanup;
        }
        if (strcmp(nick, hub_my_nick) == 0) {
            warn(_("Invalid $RevConnectToMe message: Remote nick is our nick\n"));
            goto hub_handle_command_cleanup;
        }
        local_nick = hub_to_main_string(nick);
        ui = (DCUserInfo*) hmap_get(hub_users, local_nick);
        if (ui == NULL) {
            warn(_("Invalid $RevConnectToMe message: Unknown user %s, ignoring\n"), quotearg(local_nick));
            free(local_nick);
            goto hub_handle_command_cleanup;
        }
        free(local_nick);

        if (ui->conn_count >= DC_USER_MAX_CONN) {
            warn(_("No more connections to user %s allowed.\n"), quotearg(ui->nick));
            goto hub_handle_command_cleanup;
        }

        if (!is_active) {
            if (ui->active_state == DC_ACTIVE_SENT_PASSIVE) {
                warn(_("User %s is also passive. Cannot establish connection.\n"), quotearg(ui->nick));
                /* We could set this to DC_ACTIVE_UNKNOWN too. This would mean
                 * we would keep sending RevConnectToMe next time the download
                 * queue is modified or some timer expired and told us to retry
                 * download. The remote would then send back RevConnectToMe
                 * and this would happen again. This way we would try again -
                 * maybe remote has become active since last time we checked?
                 * But no - DC++ only replies with RevConnectToMe to our first
                 * RevConnectToMe. After that it ignores them all.
                 */
                ui->active_state = DC_ACTIVE_RECEIVED_PASSIVE;
                if (hmap_remove(pending_userinfo, ui->nick) != NULL)
                    ui->refcount--;
                goto hub_handle_command_cleanup;
            }
            if (ui->active_state != DC_ACTIVE_RECEIVED_PASSIVE) {
                /* Inform remote that we are also passive. */
                if (!hub_putf("$RevConnectToMe %s %s|", hub_my_nick, nick))
                    goto hub_handle_command_cleanup;
            }
        }
        ui->active_state = DC_ACTIVE_RECEIVED_PASSIVE;

        if (!hub_connect_user(ui))
            goto hub_handle_command_cleanup;
    }
    else if ( (len >= 10 && strncmp(buf, "$NickList ", 10) == 0)
              || (len >= 8 && strncmp(buf, "$OpList ", 8) == 0) ) {
        char *nick;
        char *end;
        int oplist;
        char *conv_nick;

        if ( strncmp(buf, "$NickList ", 10) == 0) {
            nick = buf + 10;
            oplist = 0;
        } else {
            nick = buf + 8;
            oplist = 1;
        }

        for (; (end = strstr(nick, "$$")) != NULL; nick = end+2) {
            DCUserInfo *ui;
            *end = '\0';

            conv_nick = hub_to_main_string(nick);

            ui = (DCUserInfo*) hmap_get(hub_users, conv_nick);
            if (ui == NULL) {
                ui = user_info_new(conv_nick);
                hmap_put(hub_users, ui->nick, ui);
            }

            free(conv_nick);

            if (!ui->info_quered && (hub_extensions & HUB_EXT_NOGETINFO) == 0) {
                if (!hub_putf("$GetINFO %s %s|", nick, hub_my_nick))  {
                    goto hub_handle_command_cleanup;
                }
                ui->info_quered = true;
            }

            if (oplist)
                ui->is_operator = true;
        }
    }
    else if (len >= 6 && strncmp(buf, "$Quit ", 6) == 0) {
        DCUserInfo *ui;
        char *conv_nick = hub_to_main_string(buf+6);

        // I don't want these messages.
        //flag_putf(DC_DF_JOIN_PART, "User %s quits.\n", quotearg(conv_nick));
        ui = (DCUserInfo*) hmap_remove(hub_users, conv_nick);
        if (ui == NULL) {
            /* Some hubs print quit messages for users that never joined,
             * so print this as debug only.
             */
            flag_putf(DC_DF_DEBUG, _("Invalid $Quit message: Unknown user %s.\n"), quotearg(conv_nick));
        } else
            user_info_free(ui);
        free(conv_nick);
    }
    else if (len >= 8 && strncmp(buf, "$Search ", 8) == 0) {
        char *source;
        int parse_result = 0;
        DCSearchSelection sel;
        sel.patterns = NULL;

        buf += 8;
        source = strsep(&buf, " ");
        if (source == NULL) {
            warn(_("Invalid $Search message: Missing source specification.\n"));
            goto hub_handle_command_cleanup;
        }
        /* charset handling is in parse_search_selection */
        parse_result = parse_search_selection(buf, &sel);
        if (parse_result != 1) {
            if (sel.patterns != NULL) {
                int i = 0;
                for (i = 0; i < sel.patterncount; i++) {
                    search_string_free(sel.patterns+i);
                }
                free(sel.patterns);
            }
            if (parse_result == 0)
                warn(_("Invalid $Search message: %s: Invalid search specification.\n"), buf);
            goto hub_handle_command_cleanup;
        }
        if (strncmp(source, "Hub:", 4) == 0) {
            DCUserInfo *ui;
            char *conv_nick = hub_to_main_string(source+4);
            ui = (DCUserInfo*) hmap_get(hub_users, conv_nick);

            if (ui == NULL) {
                warn(_("Invalid $Search message: Unknown user %s.\n"), quotearg(conv_nick));
                if (sel.patterns != NULL) {
                    int i = 0;
                    for (i = 0; i < sel.patterncount; i++) {
                        search_string_free(sel.patterns+i);
                    }
                    free(sel.patterns);
                }
                free(conv_nick);
                goto hub_handle_command_cleanup;
            }
            free(conv_nick);

            if (strcmp(ui->nick, my_nick) == 0) {
                if (sel.patterns != NULL) {
                    int i = 0;
                    for (i = 0; i < sel.patterncount; i++) {
                        search_string_free(sel.patterns+i);
                    }
                    free(sel.patterns);
                }
                goto hub_handle_command_cleanup;
            }
            perform_inbound_search(&sel, ui, NULL);
            if (sel.patterns != NULL) {
                int i = 0;
                for (i = 0; i < sel.patterncount; i++) {
                    search_string_free(sel.patterns+i);
                }
                free(sel.patterns);
            }
        } else {
            struct sockaddr_in addr;
            if (!parse_ip_and_port(source, &addr, DC_CLIENT_UDP_PORT)) {
                warn(_("Invalid $Search message: Invalid address specification.\n"));
                if (sel.patterns != NULL) {
                    int i = 0;
                    for (i = 0; i < sel.patterncount; i++) {
                        search_string_free(sel.patterns+i);
                    }
                    free(sel.patterns);
                }
                goto hub_handle_command_cleanup;
            }
            if (local_addr.sin_addr.s_addr == addr.sin_addr.s_addr && listen_port == ntohs(addr.sin_port)) {
                if (sel.patterns != NULL) {
                    int i = 0;
                    for (i = 0; i < sel.patterncount; i++) {
                        search_string_free(sel.patterns+i);
                    }
                    free(sel.patterns);
                }
                goto hub_handle_command_cleanup;
            }
            perform_inbound_search(&sel, NULL, &addr);
            if (sel.patterns != NULL) {
                int i = 0;
                for (i = 0; i < sel.patterncount; i++) {
                    search_string_free(sel.patterns+i);
                }
                free(sel.patterns);
            }
        }
    } else if (len >= 4 && strncmp(buf, "$SR ", 4) == 0) {
        handle_search_result(buf, len);
    } else if (len == 0) {
        /* Ignore empty commands. */
    }
hub_handle_command_cleanup:
    free(hub_my_nick);
}
Ejemplo n.º 8
0
static void
user_result_fd_readable(DCUserConn *uc)
{
    int res;

    res = msgq_read(uc->get_mq);
    if (res == 0 || (res < 0 && errno != EAGAIN)) {
        warn_socket_error(res, false, _("user process %s"), quote(uc->name));
        user_disconnect(uc); /* MSG: socket error above */
        return;
    }
    while (msgq_has_complete_msg(uc->get_mq)) {
        int id;

        msgq_peek(uc->get_mq, MSGQ_INT, &id, MSGQ_END);
        switch (id) {
        case DC_MSG_SCREEN_PUT: {
            char *msg;
            uint32_t flag;

            msgq_get(uc->get_mq, MSGQ_INT, &id, MSGQ_INT32, &flag, MSGQ_STR, &msg, MSGQ_END);
            flag_putf((DCDisplayFlag)flag, _("User %s: %s"), quotearg(uc->name), msg); /* msg already quoted */
            free(msg);
            break;
        }
        case DC_MSG_WANT_DOWNLOAD: {
            bool reply;

            msgq_get(uc->get_mq, MSGQ_INT, &id, MSGQ_END);
            reply = !has_user_conn(uc->info, DC_DIR_RECEIVE)
                    && (uc->queue_pos < uc->info->download_queue->cur);
            msgq_put(uc->put_mq, MSGQ_BOOL, reply, MSGQ_END);
            FD_SET(uc->put_mq->fd, &write_fds);
            break;
        }
        case DC_MSG_VALIDATE_DIR: {
            DCTransferDirection dir;
            bool reply;

            msgq_get(uc->get_mq, MSGQ_INT, &id, MSGQ_INT, &dir, MSGQ_END);
            reply = validate_direction(uc, dir);
            msgq_put(uc->put_mq, MSGQ_BOOL, reply, MSGQ_END);
            FD_SET(uc->put_mq->fd, &write_fds);
            break;
        }
        case DC_MSG_VALIDATE_NICK: {
            char *nick;
            bool reply;

            msgq_get(uc->get_mq, MSGQ_INT, &id, MSGQ_STR, &nick, MSGQ_END);
            reply = validate_nick(uc, nick);
            free(nick);
            if (uc->info != NULL) {
                /* The user can only be DC_ACTIVE_SENT_PASSIVE if we are passive.
                 * So if we managed to connect to them even though we were passive,
                 * they must be active.
                 */
                if (uc->info->active_state == DC_ACTIVE_SENT_PASSIVE)
                    uc->info->active_state = DC_ACTIVE_KNOWN_ACTIVE;
                /* The user can only be DC_ACTIVE_SENT_ACTIVE if we are active.
                 * We must set to DC_ACTIVE_UNKNOWN because otherwise
                 * hub.c:hub_connect_user might say "ConnectToMe already sent to
                 * user" next time we're trying to connect to them.
                 */
                if (uc->info->active_state == DC_ACTIVE_SENT_ACTIVE)
                    uc->info->active_state = DC_ACTIVE_UNKNOWN;
            }
            msgq_put(uc->put_mq, MSGQ_BOOL, reply, MSGQ_END);
            FD_SET(uc->put_mq->fd, &write_fds);
            break;
        }
        case DC_MSG_GET_MY_NICK:
            msgq_get(uc->get_mq, MSGQ_INT, &id, MSGQ_END);
            msgq_put(uc->put_mq, MSGQ_STR, my_nick, MSGQ_END);
            FD_SET(uc->put_mq->fd, &write_fds);
            break;
        case DC_MSG_TRANSFER_STATUS:
            msgq_get(uc->get_mq, MSGQ_INT, &id, MSGQ_INT64, &uc->transfer_pos, MSGQ_END);
            break;
        case DC_MSG_TRANSFER_START: {
            char *share_filename, *local_filename;

            msgq_get(uc->get_mq, MSGQ_INT, &id, MSGQ_STR, &local_filename, MSGQ_STR, &share_filename, MSGQ_INT64
                , &uc->transfer_start, MSGQ_INT64, &uc->transfer_total, MSGQ_END);
            if (uc->transfer_start != 0) {
                flag_putf(DC_DF_CONNECTIONS, _("%s: Starting %s of %s (%" PRIu64 " of %" PRIu64 " %s).\n"),
                          quotearg_n(0, uc->info->nick),
                          uc->dir == DC_DIR_SEND ? _("upload") : _("download"),
                          quote_n(1, base_name(share_filename)),
                          uc->transfer_total - uc->transfer_start,
                          uc->transfer_total,
                          ngettext("byte", "bytes", uc->transfer_total));
            } else {
                flag_putf(DC_DF_CONNECTIONS, _("%s: Starting %s of %s (%" PRIu64 " %s).\n"),
                          quotearg_n(0, uc->info->nick),
                          uc->dir == DC_DIR_SEND ? _("upload") : _("download"),
                          quote_n(1, base_name(share_filename)),
                          uc->transfer_total,
                          ngettext("byte", "bytes", uc->transfer_total));
            }
            free(uc->transfer_file);
            uc->transfer_file = share_filename;
            free(uc->local_file);
            uc->local_file = local_filename;
            uc->transferring = true;
            uc->transfer_pos = uc->transfer_start;
            uc->transfer_time = time(NULL);
            if (uc->transfer_time == (time_t) -1)
                warn(_("Cannot get current time - %s\n"), errstr);
            break;
        }
        case DC_MSG_CHECK_DOWNLOAD:
            msgq_get(uc->get_mq, MSGQ_INT, &id, MSGQ_END);
            for (; uc->queue_pos < uc->info->download_queue->cur; uc->queue_pos++) {
                DCQueuedFile *queued;
                char *local_file;

                queued = (DCQueuedFile*) uc->info->download_queue->buf[uc->queue_pos];
                if (queued->status != DC_QS_DONE) {
                    local_file = resolve_download_file(uc->info, queued);
                    uc->queued_valid = true;
                    uc->transfer_file = xstrdup(queued->filename);
                    uc->local_file = xstrdup(local_file);
                    uc->occupied_slot = true;
                    queued->status = DC_QS_PROCESSING;
                    used_dl_slots++;
                    msgq_put(uc->put_mq, MSGQ_STR, local_file, MSGQ_STR, uc->transfer_file, MSGQ_INT64, queued->length, MSGQ_INT, queued->flag, MSGQ_END);
                    FD_SET(uc->put_mq->fd, &write_fds);
                    free(local_file);
                    return;
                }
            }
            msgq_put(uc->put_mq, MSGQ_STR, NULL, MSGQ_STR, NULL, MSGQ_INT64, (uint64_t) 0, MSGQ_INT, DC_TF_NORMAL, MSGQ_END);
            FD_SET(uc->put_mq->fd, &write_fds);
            break;
        case DC_MSG_DOWNLOAD_ENDED: {
            bool success;
            char *reason;

            msgq_get(uc->get_mq, MSGQ_INT, &id, MSGQ_BOOL, &success, MSGQ_STR, &reason, MSGQ_END);
            handle_ended_download(uc, success, reason);
            free(reason);
            break;
        }
        case DC_MSG_CHECK_UPLOAD: {
            char *remote_file;
            char *local_file;
            int type;
            uint64_t size = 0;
            DCTransferFlag flag = DC_TF_NORMAL;
            bool permit_transfer = false;

            msgq_get(uc->get_mq, MSGQ_INT, &id, MSGQ_INT, &type, MSGQ_STR, &remote_file, MSGQ_END);
            local_file = (char*) resolve_upload_file(uc->info, (DCAdcgetType) type, remote_file, &flag, &size);
            free(remote_file);
            uc->transfer_file = NULL;
            if (local_file != NULL) {
                if (flag == DC_TF_LIST || (flag == DC_TF_NORMAL && size <= minislot_size)) {
                    if (used_mini_slots < minislot_count) {
                        used_mini_slots ++;
                        uc->occupied_minislot = true;
                        permit_transfer = true;
                    } else if (used_ul_slots < my_ul_slots || uc->info->slot_granted) {
                        used_ul_slots ++;
                        uc->occupied_slot = true;
                        permit_transfer = true;
                    }
                } else if (flag == DC_TF_NORMAL && size > minislot_size) {
                    if (used_ul_slots < my_ul_slots || uc->info->slot_granted) {
                        used_ul_slots ++;
                        uc->occupied_slot = true;
                        permit_transfer = true;
                    }
                }
                if (permit_transfer) {
                    uc->transfer_file = local_file;
                } else {
                    free(local_file);
                    local_file = NULL;
                }
            } else {
                permit_transfer = true;
            }
            msgq_put(uc->put_mq, MSGQ_BOOL, permit_transfer, MSGQ_STR, local_file, MSGQ_END);
            FD_SET(uc->put_mq->fd, &write_fds);
            break;
        }
        case DC_MSG_UPLOAD_ENDED: {
            bool success;
            char *reason;

            msgq_get(uc->get_mq, MSGQ_INT, &id, MSGQ_BOOL, &success, MSGQ_STR, &reason, MSGQ_END);
            handle_ended_upload(uc, success, reason);
            free(reason);
            break;
        }
        case DC_MSG_TERMINATING:
            /* The TERMINATING message will be sent from users when they're about to
             * shut down properly.
            * XXX: This message may contain the reason it was terminated in the future.
            */
            msgq_get(uc->get_mq, MSGQ_INT, &id, MSGQ_END);
            user_disconnect(uc); /* MSG: reason from DC_MSG_TERMINATING */
            return; /* not break! this is the last message. */
        default:
            warn(_("Received unknown message %d from user process, shutting down process.\n"), id);
            user_disconnect(uc); /* MSG: local communication error? */
            return; /* not break! this is the last message. */
        }
    }
}