unsigned long CFile::Read(void* lpBuf, int64_t uiBufSize) { if (m_fd == -1) return 0; CLockObject lock(smb); // Init not called since it has to be "inited" by now smb.SetActivityTime(); /* work around stupid bug in samba */ /* some samba servers have a bug in it where the */ /* 17th bit will be ignored in a request of data */ /* this can lead to a very small return of data */ /* also worse, a request of exactly 64k will return */ /* as if eof, client has a workaround for windows */ /* thou it seems other servers are affected too */ if ( uiBufSize >= 64*1024-2 ) uiBufSize = 64*1024-2; int bytesRead = smbc_read(m_fd, lpBuf, (int)uiBufSize); if ( bytesRead < 0 && errno == EINVAL ) { XBMC->Log(LOG_ERROR, "%s - Error( %d, %d, %s ) - Retrying", __FUNCTION__, bytesRead, errno, strerror(errno)); bytesRead = smbc_read(m_fd, lpBuf, (int)uiBufSize); } if ( bytesRead < 0 ) { XBMC->Log(LOG_ERROR, "%s - Error( %d, %d, %s )", __FUNCTION__, bytesRead, errno, strerror(errno)); return 0; } return (unsigned int) bytesRead; }
/***************************************************** a wrapper for pread() there should really be an smbc_pread() to avoid the two lseek()s required in this kludge. *******************************************************/ ssize_t smbw_pread(int smbw_fd, void *buf, size_t count, SMBW_OFF_T ofs) { int client_fd; ssize_t ret; int saved_errno; SMBW_OFF_T old_ofs; if (count == 0) { return 0; } client_fd = smbw_fd_map[smbw_fd]; if ((old_ofs = smbc_lseek(client_fd, 0, SEEK_CUR)) < 0 || smbc_lseek(client_fd, ofs, SEEK_SET) < 0) { return -1; } if ((ret = smbc_read(client_fd, buf, count)) < 0) { saved_errno = errno; (void) smbc_lseek(client_fd, old_ofs, SEEK_SET); errno = saved_errno; return -1; } return ret; }
int FileRead( FHANDLE handle, void *buffer, int size ) { int ret = 0; if( handle.dt == DT_CD ) { ret = fioRead( handle.fh, buffer, size ); } else if( handle.dt == DT_HDD ) { ret = fileXioRead( handle.fh, buffer, size ); } else if( handle.dt == DT_MC ) { ret = fioRead( handle.fh, buffer, size ); } else if( handle.dt == DT_USB ) { ret = fioRead( handle.fh, buffer, size ); } else if( handle.dt == DT_HOST ) { ret = fioRead( handle.fh, buffer, size ); } else if( handle.dt == DT_SMB_SHARE ) { ret = smbc_read( handle.fh, buffer, size ); } return ret; }
int main(int argc, char** argv) { int err = -1; int fd = 0; char* message = "Testing"; memset(g_workgroup, '\0', MAX_BUFF_SIZE); if ( argc == 4 ) { strncpy(g_workgroup,argv[1],strlen(argv[1])); strncpy(g_username,argv[2],strlen(argv[2])); strncpy(g_password,argv[3],strlen(argv[3])); fd = 10345; /* Random value for File Descriptor */ smbc_init(auth_fn, 0); err = smbc_read(fd, message, sizeof(message)); if ( err < 0 ) err = 1; else err = 0; } return err; }
/***************************************************** a wrapper for read() *******************************************************/ ssize_t smbw_read(int smbw_fd, void *buf, size_t count) { int client_fd; client_fd = smbw_fd_map[smbw_fd]; return smbc_read(client_fd, buf, count); }
size_t smbc_wrapper_read(connection* con, int fd, void *buf, size_t bufsize) { if(con->mode== SMB_BASIC) return smbc_read(fd, buf, bufsize); else if(con->mode == SMB_NTLM) return smbc_cli_read(con->smb_info->cli, fd, buf, bufsize); return -1; }
int FSSmb::Read( int fd, void* buf, int size, int* err, FSCInfo* info ) { FREPARE_SMB_OPER( lock, info, &_param ); int n = smbc_read( fd, buf, size ); if ( n < 0 ) { SetError( err, errno ); return -1; } return n; }
int main(int argc, char** argv) { int err = -1; int fd = 0; int msg_len = 0; char url[MAX_BUFF_SIZE]; char* message; char* response; bzero(g_workgroup,MAX_BUFF_SIZE); bzero(url,MAX_BUFF_SIZE); if ( argc == 6 ) { strncpy(g_workgroup,argv[1],strlen(argv[1])); strncpy(g_username,argv[2],strlen(argv[2])); strncpy(g_password,argv[3],strlen(argv[3])); strncpy(url,argv[4],strlen(argv[4])); msg_len = strlen(argv[5])+1; message = malloc(msg_len); response = malloc(msg_len); message[msg_len - 1] = 0; strncpy(message,argv[5],msg_len); smbc_init(auth_fn, 0); smbc_unlink(url); fd = smbc_open(url,O_RDWR | O_CREAT, 0666); smbc_write(fd, message, msg_len); smbc_close(fd); fd = smbc_open(url,O_RDWR, 0666); err = smbc_read(fd,response,msg_len); free(message); free(response); if ( err < 0 ) err = 1; else if ( err != msg_len ) err = 1; else err = 0; } return err; }
static ssize_t _read(csync_vio_method_handle_t *fhandle, void *buf, size_t count) { smb_fhandle_t *handle = NULL; if (fhandle == NULL) { errno = EBADF; return (ssize_t) -1; } handle = (smb_fhandle_t *) fhandle; return smbc_read(handle->fd, buf, count); }
/***************************************************************************** * Read: *****************************************************************************/ static ssize_t Read( stream_t *p_access, void *p_buffer, size_t i_len ) { access_sys_t *p_sys = p_access->p_sys; int i_read; i_read = smbc_read( p_sys->i_smb, p_buffer, i_len ); if( i_read < 0 ) { msg_Err( p_access, "read failed (%s)", vlc_strerror_c(errno) ); i_read = 0; } return i_read; }
/***************************************************************************** * Read: *****************************************************************************/ static ssize_t Read( access_t *p_access, uint8_t *p_buffer, size_t i_len ) { access_sys_t *p_sys = p_access->p_sys; int i_read; if( p_access->info.b_eof ) return 0; i_read = smbc_read( p_sys->i_smb, p_buffer, i_len ); if( i_read < 0 ) { msg_Err( p_access, "read failed (%m)" ); return -1; } if( i_read == 0 ) p_access->info.b_eof = true; else if( i_read > 0 ) p_access->info.i_pos += i_read; return i_read; }
/***************************************************************************** * Read: *****************************************************************************/ static ssize_t Read( access_t *p_access, uint8_t *p_buffer, size_t i_len ) { access_sys_t *p_sys = p_access->p_sys; int i_read; if( p_access->info.b_eof ) return 0; i_read = smbc_read( p_sys->i_smb, p_buffer, i_len ); if( i_read < 0 ) { msg_Err( p_access, "read failed (%s)", vlc_strerror_c(errno) ); p_access->info.b_eof = true; return -1; } if( i_read == 0 ) p_access->info.b_eof = true; return i_read; }
int main(int argc, char** argv) { int err = -1; int fd = 0; int msg_len = 0; char url[MAX_BUFF_SIZE]; char* message = NULL; memset(g_workgroup, '\0', MAX_BUFF_SIZE); memset(url, '\0', MAX_BUFF_SIZE); if ( argc == 5 ) { strncpy(g_workgroup,argv[1],strlen(argv[1])); strncpy(g_username,argv[2],strlen(argv[2])); strncpy(g_password,argv[3],strlen(argv[3])); strncpy(url,argv[4],strlen(argv[4])); smbc_init(auth_fn, 0); smbc_unlink(url); fd = smbc_open(url,O_RDWR | O_CREAT, 0666); smbc_close(fd); msg_len = 10; fd = smbc_open(url, O_RDWR, 0666); err = smbc_read(fd, message, msg_len); smbc_close(fd); if ( err < 0 ) err = 1; else err = 0; } return err; }
static int smbcfs_read(const char* const path, char* const buf, const std::size_t size, const off_t offset, struct fuse_file_info* const fi) { const int fh = fi->fh; #ifdef MUTEX_LOCK pthread_mutex_lock(&mutex_lock); #endif const int ret_lseek = smbc_lseek(fh, offset, SEEK_SET); #ifdef MUTEX_LOCK pthread_mutex_unlock(&mutex_lock); #endif #ifdef SMBCFS_DEBUG fprintf(stderr, "[smbc_lseek] %d %lld %d => %d\n", fh, offset, SEEK_SET, ret_lseek); #endif if(ret_lseek<0) return ret_lseek; #ifdef MUTEX_LOCK pthread_mutex_lock(&mutex_lock); #endif const int ret_read = smbc_read(fh, buf, size); #ifdef MUTEX_LOCK pthread_mutex_unlock(&mutex_lock); #endif #ifdef SMBCFS_DEBUG fprintf(stderr, "[smbc_read] %d %p %ld => %d\n", fh, buf, size, ret_read); #endif return ret_read; }
static gint xmms_samba_read (xmms_xform_t *xform, void *buffer, gint len, xmms_error_t *error) { xmms_samba_data_t *data; gint ret; g_return_val_if_fail (xform, -1); g_return_val_if_fail (buffer, -1); g_return_val_if_fail (error, -1); data = xmms_xform_private_data_get (xform); g_return_val_if_fail (data, -1); G_LOCK (mutex); ret = smbc_read (data->fd, buffer, len); G_UNLOCK (mutex); if (ret < 0) { xmms_error_set (error, XMMS_ERROR_GENERIC, strerror (errno)); } return ret; }
int smb_download_file(const char *base, const char *name, int recursive, int resume, char *outfile) { int remotehandle, localhandle; time_t start_time = time(NULL); const char *newpath; char path[SMB_MAXPATHLEN]; char checkbuf[2][RESUME_CHECK_SIZE]; char *readbuf = NULL; off_t offset_download = 0, offset_check = 0, curpos = 0, start_offset = 0; struct stat localstat, remotestat; snprintf(path, SMB_MAXPATHLEN-1, "%s%s%s", base, (*base && *name && name[0] != '/' && base[strlen(base)-1] != '/')?"/":"", name); remotehandle = smbc_open(path, O_RDONLY, 0755); if(remotehandle < 0) { switch(errno) { case EISDIR: if(!recursive) { fprintf(stderr, "%s is a directory. Specify -R to download recursively\n", path); return 0; } smb_download_dir(base, name, resume); return 0; case ENOENT: fprintf(stderr, "%s can't be found on the remote server\n", path); return 0; case ENOMEM: fprintf(stderr, "Not enough memory\n"); exit(1); return 0; case ENODEV: fprintf(stderr, "The share name used in %s does not exist\n", path); return 0; case EACCES: fprintf(stderr, "You don't have enough permissions to access %s\n", path); return 0; default: perror("smbc_open"); return 0; } } if(smbc_fstat(remotehandle, &remotestat) < 0) { fprintf(stderr, "Can't stat %s: %s\n", path, strerror(errno)); return 0; } if(outfile) newpath = outfile; else if(!name[0]) { newpath = strrchr(base, '/'); if(newpath)newpath++; else newpath = base; } else newpath = name; if(newpath[0] == '/')newpath++; /* Open local file and, if necessary, resume */ localhandle = open(newpath, O_CREAT | O_NONBLOCK | O_RDWR | (!resume?O_EXCL:0), 0755); if(localhandle < 0) { fprintf(stderr, "Can't open %s: %s\n", newpath, strerror(errno)); smbc_close(remotehandle); return 0; } fstat(localhandle, &localstat); start_offset = localstat.st_size; if(localstat.st_size && localstat.st_size == remotestat.st_size) { if(verbose)fprintf(stderr, "%s is already downloaded completely.\n", path); else if(!quiet)fprintf(stderr, "%s\n", path); smbc_close(remotehandle); close(localhandle); return 1; } if(localstat.st_size > RESUME_CHECK_OFFSET && remotestat.st_size > RESUME_CHECK_OFFSET) { offset_download = localstat.st_size - RESUME_DOWNLOAD_OFFSET; offset_check = localstat.st_size - RESUME_CHECK_OFFSET; if(verbose)printf("Trying to start resume of %s at "OFF_T_FORMAT"\n" "At the moment "OFF_T_FORMAT" of "OFF_T_FORMAT" bytes have been retrieved\n", newpath, offset_check, localstat.st_size, remotestat.st_size); } if(offset_check) { off_t off1, off2; /* First, check all bytes from offset_check to offset_download */ off1 = lseek(localhandle, offset_check, SEEK_SET); if(off1 < 0) { fprintf(stderr, "Can't seek to "OFF_T_FORMAT" in local file %s\n", offset_check, newpath); smbc_close(remotehandle); close(localhandle); return 0; } off2 = smbc_lseek(remotehandle, offset_check, SEEK_SET); if(off2 < 0) { fprintf(stderr, "Can't seek to "OFF_T_FORMAT" in remote file %s\n", offset_check, newpath); smbc_close(remotehandle); close(localhandle); return 0; } if(off1 != off2) { fprintf(stderr, "Offset in local and remote files is different (local: "OFF_T_FORMAT", remote: "OFF_T_FORMAT")\n", off1, off2); return 0; } if(smbc_read(remotehandle, checkbuf[0], RESUME_CHECK_SIZE) != RESUME_CHECK_SIZE) { fprintf(stderr, "Can't read %d bytes from remote file %s\n", RESUME_CHECK_SIZE, path); smbc_close(remotehandle); close(localhandle); return 0; } if(read(localhandle, checkbuf[1], RESUME_CHECK_SIZE) != RESUME_CHECK_SIZE) { fprintf(stderr, "Can't read %d bytes from local file %s\n", RESUME_CHECK_SIZE, name); smbc_close(remotehandle); close(localhandle); return 0; } if(memcmp(checkbuf[0], checkbuf[1], RESUME_CHECK_SIZE) == 0) { if(verbose)printf("Current local and remote file appear to be the same. Starting download from offset "OFF_T_FORMAT"\n", offset_download); } else { fprintf(stderr, "Local and remote file appear to be different, not doing resume for %s\n", path); smbc_close(remotehandle); close(localhandle); return 0; } } readbuf = malloc(blocksize); /* Now, download all bytes from offset_download to the end */ for(curpos = offset_download; curpos < remotestat.st_size; curpos+=blocksize) { ssize_t bytesread = smbc_read(remotehandle, readbuf, blocksize); if(bytesread < 0) { fprintf(stderr, "Can't read %d bytes at offset "OFF_T_FORMAT", file %s\n", blocksize, curpos, path); smbc_close(remotehandle); close(localhandle); free(readbuf); return 0; } total_bytes += bytesread; if(write(localhandle, readbuf, bytesread) < 0) { fprintf(stderr, "Can't write %d bytes to local file %s at offset "OFF_T_FORMAT"\n", bytesread, path, curpos); free(readbuf); smbc_close(remotehandle); close(localhandle); return 0; } if(dots)fputc('.', stderr); else if(!quiet) { print_progress(newpath, start_time, time(NULL), start_offset, curpos, remotestat.st_size); } } free(readbuf); if(dots){ fputc('\n', stderr); printf("%s downloaded\n", path); } else if(!quiet) { int i; fprintf(stderr, "\r%s", path); if(columns) { for(i = strlen(path); i < columns; i++) { fputc(' ', stderr); } } fputc('\n', stderr); } if(keep_permissions) { if(fchmod(localhandle, remotestat.st_mode) < 0) { fprintf(stderr, "Unable to change mode of local file %s to %o\n", path, remotestat.st_mode); smbc_close(remotehandle); close(localhandle); return 0; } } smbc_close(remotehandle); close(localhandle); return 1; }
static void copy() { int fd, fd2; int ret; int i; int debug=0; int rTime,justread; char buffer[40048]; i=( random() % config.number); char *Dateiname1; char *Dateiname2; rTime= (random() % 2); justread= (random() %2); // wether to write to the target share or not /* at this point we have the full filenames. In case of * recording, we save them here. In case of replay, we * replace them with the strings from the file. */ if (config.record!=NULL) { fprintf(config.recorder,"file1: %i\n",i); fprintf(config.recorder,"file2: %i\n",i); fprintf(config.recorder,"just read: %i\n",justread); } if (config.replay!=NULL) { fscanf(config.player,"file1: %i\n",&i); fscanf(config.player,"file2: %i\n",&i); fscanf(config.player,"just read: %i\n",&justread); } Dateiname1 = (char *) malloc(sizeof(char) * (strlen(config.share1)+strlen(config.share2)+strlen(fnamelist[i]))); Dateiname2 = (char *) malloc(sizeof(char) * (strlen(config.share1)+strlen(config.share2)+strlen(fnamelist[i]))); switch (rTime) { case 0: strcpy(Dateiname1, config.share1); strcpy(Dateiname2, config.share2); break; case 1: strcpy(Dateiname1, config.share2); strcpy(Dateiname2, config.share1); break; } strcat(Dateiname1, fnamelist[i]); strcat(Dateiname2, fnamelist[i]); smbc_init(get_auth_data_fn, debug); if ((fd = smbc_open(Dateiname1, O_RDONLY, 0)) < 0) { perror("smbc_open failed"); exit(1); } if (justread!=1 && (fd2 = smbc_open(Dateiname2, O_WRONLY | O_CREAT | O_TRUNC, 0)) < 0) { perror("smbc_open: writing failed"); exit(1); } do { ret = smbc_read(fd, buffer, sizeof(buffer)); if (ret > 0 && justread!=1) smbc_write(fd2, buffer, ret); } while (ret > 0); smbc_close(fd); if (justread!=1) smbc_close(fd2); if (config.time==0) rTime=0; else rTime = (random() % config.time)+1; if (config.record!=NULL) { /* when recording, store the time to wait here */ fprintf(config.recorder,"wait: %i\n",rTime); } if (config.replay!=NULL) { /* when in playback, load the time to wait here */ fscanf(config.player,"wait: %i\n",&rTime); } if(config.verbose == 1) { if (justread!=1) printf("File %s copied to %s\n", Dateiname1, Dateiname2); else printf("Read file %s into memory.\n",Dateiname1); printf("Sleeping %i seconds...\n", rTime); } sleep(rTime); free(Dateiname1); free(Dateiname2); if (config.verbose ==1) printf("Transferring data...\n"); }
const char *Spider::DetectMimeType(const std::string &path) { int smb_fd = smbc_open(path.c_str(), O_RDONLY, 0); if (UNLIKELY(smb_fd < 0)) { if (LIKELY(errno == EISDIR)) return "inode/directory"; DetectError(); MSS_ERROR(("smbc_open " + path).c_str(), error_); return "unknown"; } // Extract name of the file // Don't detele '/' symbol it need to form path. std::string name(path, path.rfind("/")); // Create a storage for file header in TMPDIR and open it int fd = open((TMPDIR + name).c_str(), O_CREAT | O_RDWR | O_EXCL, 00744 /* rwxr--r-- */); if (UNLIKELY(fd == -1)) { if (LIKELY(errno = ENOTDIR)) { // TODO(yulyugin): Check if TMPDIR doesn't exists create it. } DetectError(); MSS_ERROR("open", error_); if (UNLIKELY(smbc_close(smb_fd))) { DetectError(); MSS_ERROR("smbc_close", error_); } return "unknown"; } void *buf = malloc(HEADERSIZE); // Buffer to store header. // Copy file header to TMPDIR if (UNLIKELY(smbc_read(smb_fd, buf, HEADERSIZE) < 0)) { DetectError(); MSS_ERROR("smbc_read", error_); if (UNLIKELY(smbc_close(smb_fd))) { DetectError(); MSS_ERROR("smbc_close", error_); } if (UNLIKELY(close(fd))) { DetectError(); MSS_ERROR("close", error_); } free(buf); return "unknown"; } if (UNLIKELY(write(fd, buf, HEADERSIZE) < 0)) { DetectError(); MSS_ERROR("write", error_); if (UNLIKELY(smbc_close(smb_fd))) { DetectError(); MSS_ERROR("smbc_close", error_); } if (UNLIKELY(close(fd))) { DetectError(); MSS_ERROR("close", error_); } free(buf); return "unknown"; } // Move to the begining of the file if (UNLIKELY(lseek(fd, 0, SEEK_SET) != 0)) { DetectError(); MSS_ERROR("lseek", error_); if (UNLIKELY(smbc_close(smb_fd))) { DetectError(); MSS_ERROR("smbc_close", error_); } if (UNLIKELY(close(fd))) { DetectError(); MSS_ERROR("close", error_); } free(buf); return "unknown"; } const char *mime_type = magic_descriptor(cookie_, fd); if (UNLIKELY(mime_type == NULL)) { error_ = magic_errno(cookie_); MSS_ERROR("magic_descriptor", error_); if (UNLIKELY(smbc_close(smb_fd))) { DetectError(); MSS_ERROR("smbc_close", error_); } if (UNLIKELY(close(fd))) { DetectError(); MSS_ERROR("close", error_); } free(buf); return "unknown"; } if (UNLIKELY(smbc_close(smb_fd))) { DetectError(); MSS_ERROR("smbc_close", error_); } free(buf); // Remove temporary file. if (UNLIKELY(unlink((TMPDIR + name).c_str()))) { DetectError(); MSS_ERROR("unlink", error_); } return mime_type; }
/* download file */ int SMB_download(char *serverpath, int index) { char buffer[4096] = {0}; int buflen; char *localpath = serverpath_to_localpath(serverpath, index); //char *localpath_td = my_malloc(strlen(localpath) + strlen(".asus.td") + 1); char *localpath_td = my_malloc(strlen(localpath) + 9); //2014.10.20 by sherry malloc申请内存是否成功 //if(localpath_td==NULL) // return NULL; sprintf(localpath_td, "%s%s", localpath, ".asus.td"); write_log(S_DOWNLOAD, "", serverpath, index); unsigned long long halfsize = 0; int dst_fd; if(access(localpath_td, F_OK) != 0) { dst_fd = open(localpath_td, O_RDWR|O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); if(dst_fd < 0){ printf("open() - %s failed\n", localpath_td); return -1; } } else { dst_fd = open(localpath_td, O_RDWR|O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); if(dst_fd < 0){ printf("open() - %s failed\n", localpath_td); return -1; } halfsize = lseek(dst_fd, 0L, SEEK_END); lseek(dst_fd, halfsize, SEEK_SET); } SMB_init(index); int fd = -1; if((fd = smbc_open(serverpath, O_RDONLY, FILE_MODE)) > 0) { unsigned long long cli_filesize = 0; unsigned long long smb_filesize = 0; smb_filesize = smbc_lseek(fd, 0L, SEEK_END); smbc_lseek(fd, halfsize, SEEK_SET); while((buflen = smbc_read(fd, buffer, sizeof(buffer))) > 0 && exit_loop == 0) { //2014.11.20 by sherry 判断是否write成功 write(dst_fd, buffer, buflen); cli_filesize += buflen; printf("\rDownload [%s] percent - %f ", serverpath, (float)cli_filesize/(float)smb_filesize); } if(cli_filesize == smb_filesize) { rename(localpath_td, localpath); free(localpath); free(localpath_td); smbc_close(fd); close(dst_fd); } else { free(localpath); free(localpath_td); smbc_close(fd); close(dst_fd); return -1; } } else { printf("smbc_open() - %s failed\n", serverpath); close(dst_fd); free(localpath); free(localpath_td); return COULD_NOT_CONNECNT_TO_SERVER; } return 0; }
int main(int argc, char * argv[]) { int fd; int ret; int debug = 0; int mode = 0666; int savedErrno; char buffer[2048]; char * pSmbPath = NULL; time_t t0; time_t t1; struct stat st; if (argc == 1) { pSmbPath = "smb://RANDOM/Public/bigfile"; } else if (argc == 2) { pSmbPath = argv[1]; } else { printf("usage: " "%s [ smb://path/to/file ]\n", argv[0]); return 1; } smbc_init(get_auth_data_fn, debug); printf("Open file %s\n", pSmbPath); t0 = time(NULL); if ((fd = smbc_open(pSmbPath, O_RDONLY, 0)) < 0) { perror("smbc_open"); return 1; } printf("Beginning read loop.\n"); do { ret = smbc_read(fd, buffer, sizeof(buffer)); savedErrno = errno; if (ret > 0) fwrite(buffer, 1, ret, stdout); } while (ret > 0); smbc_close(fd); if (ret < 0) { errno = savedErrno; perror("read"); return 1; } t1 = time(NULL); printf("Elapsed time: %d seconds\n", t1 - t0); return 0; }
int main(int argc, char *argv[]) { int err, fd, dh1, dsize, dirc; const char *file = "smb://samba/public/testfile.txt"; const char *file2 = "smb://samba/public/testfile2.txt"; char buff[256]; char dirbuf[512]; char *dirp; struct stat st1, st2; err = smbc_init(get_auth_data_fn, 10); /* Initialize things */ if (err < 0) { fprintf(stderr, "Initializing the smbclient library ...: %s\n", strerror(errno)); } if (argc > 1) { if ((dh1 = smbc_opendir(argv[1]))<1) { fprintf(stderr, "Could not open directory: %s: %s\n", argv[1], strerror(errno)); exit(1); } fprintf(stdout, "Directory handle: %u\n", dh1); /* Now, list those directories, but in funny ways ... */ dirp = (char *)dirbuf; if ((dirc = smbc_getdents(dh1, (struct smbc_dirent *)dirp, sizeof(dirbuf))) < 0) { fprintf(stderr, "Problems getting directory entries: %s\n", strerror(errno)); exit(1); } /* Now, process the list of names ... */ fprintf(stdout, "Directory listing, size = %u\n", dirc); while (dirc > 0) { dsize = ((struct smbc_dirent *)dirp)->dirlen; fprintf(stdout, "Dir Ent, Type: %u, Name: %s, Comment: %s\n", ((struct smbc_dirent *)dirp)->smbc_type, ((struct smbc_dirent *)dirp)->name, ((struct smbc_dirent *)dirp)->comment); dirp += dsize; dirc -= dsize; } dirp = (char *)dirbuf; exit(1); } /* For now, open a file on a server that is hard coded ... later will * read from the command line ... */ fd = smbc_open(file, O_RDWR | O_CREAT | O_TRUNC, 0666); if (fd < 0) { fprintf(stderr, "Creating file: %s: %s\n", file, strerror(errno)); exit(0); } fprintf(stdout, "Opened or created file: %s\n", file); /* Now, write some date to the file ... */ memset(buff, '\0', sizeof(buff)); snprintf(buff, sizeof(buff), "%s", "Some test data for the moment ..."); err = smbc_write(fd, buff, sizeof(buff)); if (err < 0) { fprintf(stderr, "writing file: %s: %s\n", file, strerror(errno)); exit(0); } fprintf(stdout, "Wrote %lu bytes to file: %s\n", (unsigned long) sizeof(buff), buff); /* Now, seek the file back to offset 0 */ err = smbc_lseek(fd, SEEK_SET, 0); if (err < 0) { fprintf(stderr, "Seeking file: %s: %s\n", file, strerror(errno)); exit(0); } fprintf(stdout, "Completed lseek on file: %s\n", file); /* Now, read the file contents back ... */ err = smbc_read(fd, buff, sizeof(buff)); if (err < 0) { fprintf(stderr, "Reading file: %s: %s\n", file, strerror(errno)); exit(0); } fprintf(stdout, "Read file: %s\n", buff); /* Should check the contents */ fprintf(stdout, "Now fstat'ing file: %s\n", file); err = smbc_fstat(fd, &st1); if (err < 0) { fprintf(stderr, "Fstat'ing file: %s: %s\n", file, strerror(errno)); exit(0); } /* Now, close the file ... */ err = smbc_close(fd); if (err < 0) { fprintf(stderr, "Closing file: %s: %s\n", file, strerror(errno)); } /* Now, rename the file ... */ err = smbc_rename(file, file2); if (err < 0) { fprintf(stderr, "Renaming file: %s to %s: %s\n", file, file2, strerror(errno)); } fprintf(stdout, "Renamed file %s to %s\n", file, file2); /* Now, create a file and delete it ... */ fprintf(stdout, "Now, creating file: %s so we can delete it.\n", file); fd = smbc_open(file, O_RDWR | O_CREAT, 0666); if (fd < 0) { fprintf(stderr, "Creating file: %s: %s\n", file, strerror(errno)); exit(0); } fprintf(stdout, "Opened or created file: %s\n", file); err = smbc_close(fd); if (err < 0) { fprintf(stderr, "Closing file: %s: %s\n", file, strerror(errno)); exit(0); } /* Now, delete the file ... */ fprintf(stdout, "File %s created, now deleting ...\n", file); err = smbc_unlink(file); if (err < 0) { fprintf(stderr, "Deleting file: %s: %s\n", file, strerror(errno)); exit(0); } /* Now, stat the file, file 2 ... */ fprintf(stdout, "Now stat'ing file: %s\n", file); err = smbc_stat(file2, &st2); if (err < 0) { fprintf(stderr, "Stat'ing file: %s: %s\n", file, strerror(errno)); exit(0); } fprintf(stdout, "Stat'ed file: %s. Size = %d, mode = %04X\n", file2, (int)st2.st_size, (unsigned int)st2.st_mode); fprintf(stdout, " time: %s\n", ctime(&st2.st_atime)); fprintf(stdout, "Earlier stat: %s, Size = %d, mode = %04X\n", file, (int)st1.st_size, (unsigned int)st1.st_mode); fprintf(stdout, " time: %s\n", ctime(&st1.st_atime)); /* Now, make a directory ... */ fprintf(stdout, "Making directory smb://samba/public/make-dir\n"); if (smbc_mkdir("smb://samba/public/make-dir", 0666) < 0) { fprintf(stderr, "Error making directory: smb://samba/public/make-dir: %s\n", strerror(errno)); if (errno == EEXIST) { /* Try to delete the directory */ fprintf(stdout, "Trying to delete directory: smb://samba/public/make-dir\n"); if (smbc_rmdir("smb://samba/public/make-dir") < 0) { /* Error */ fprintf(stderr, "Error removing directory: smb://samba/public/make-dir: %s\n", strerror(errno)); exit(0); } fprintf(stdout, "Making directory: smb://samba/public/make-dir\n"); if (smbc_mkdir("smb://samba/public/make-dir", 666) < 0) { fprintf(stderr, "Error making directory: smb://samba/public/make-dir: %s\n", strerror(errno)); fprintf(stderr, "I give up!\n"); exit(1); } } exit(0); } fprintf(stdout, "Made dir: make-dir\n"); return 0; }
void SMBSlave::smbCopy(const QUrl& ksrc, const QUrl& kdst, int permissions, KIO::JobFlags flags) { SMBUrl src; SMBUrl dst; mode_t initialmode; ssize_t n; int dstflags; int srcfd = -1; int dstfd = -1; int errNum = 0; KIO::filesize_t processed_size = 0; unsigned char buf[MAX_XFER_BUF_SIZE]; qCDebug(KIO_SMB) << "SMBSlave::copy with src = " << ksrc << "and dest = " << kdst; // setup urls src = ksrc; dst = kdst; // Obtain information about source errNum = cache_stat(src, &st ); if( errNum != 0 ) { if ( errNum == EACCES ) { error( KIO::ERR_ACCESS_DENIED, src.toDisplayString()); } else { error( KIO::ERR_DOES_NOT_EXIST, src.toDisplayString()); } return; } if ( S_ISDIR( st.st_mode ) ) { error( KIO::ERR_IS_DIRECTORY, src.toDisplayString() ); return; } totalSize(st.st_size); // Check to se if the destination exists errNum = cache_stat(dst, &st); if( errNum == 0 ) { if(S_ISDIR(st.st_mode)) { error( KIO::ERR_DIR_ALREADY_EXIST, dst.toDisplayString()); return; } if(!(flags & KIO::Overwrite)) { error( KIO::ERR_FILE_ALREADY_EXIST, dst.toDisplayString()); return; } } // Open the source file srcfd = smbc_open(src.toSmbcUrl(), O_RDONLY, 0); if (srcfd < 0){ errNum = errno; } else { errNum = 0; } if(srcfd < 0) { if(errNum == EACCES) { error( KIO::ERR_ACCESS_DENIED, src.toDisplayString() ); } else { error( KIO::ERR_DOES_NOT_EXIST, src.toDisplayString() ); } return; } // Determine initial creation mode if(permissions != -1) { initialmode = permissions | S_IWUSR; } else { initialmode = 0 | S_IWUSR;//0666; } // Open the destination file dstflags = O_CREAT | O_TRUNC | O_WRONLY; if(!(flags & KIO::Overwrite)) { dstflags |= O_EXCL; } dstfd = smbc_open(dst.toSmbcUrl(), dstflags, initialmode); if (dstfd < 0){ errNum = errno; } else { errNum = 0; } if(dstfd < 0) { if(errNum == EACCES) { error(KIO::ERR_WRITE_ACCESS_DENIED, dst.toDisplayString()); } else { error(KIO::ERR_CANNOT_OPEN_FOR_READING, dst.toDisplayString()); } if(srcfd >= 0 ) { smbc_close(srcfd); } return; } // Perform copy while(1) { n = smbc_read(srcfd, buf, MAX_XFER_BUF_SIZE ); if(n > 0) { n = smbc_write(dstfd, buf, n); if(n == -1) { qCDebug(KIO_SMB) << "SMBSlave::copy copy now KIO::ERR_COULD_NOT_WRITE"; error( KIO::ERR_COULD_NOT_WRITE, dst.toDisplayString()); break; } processed_size += n; processedSize(processed_size); } else if(n == 0) { break; // finished } else { error( KIO::ERR_COULD_NOT_READ, src.toDisplayString()); break; } } // FINISHED: if(srcfd >= 0 ) { smbc_close(srcfd); } if(dstfd >= 0) { if(smbc_close(dstfd) == 0) { // TODO: set final permissions } else { error( KIO::ERR_COULD_NOT_WRITE, dst.toDisplayString()); return; } } finished(); }
static void do_smb(struct connection *conn) { struct uri *uri = conn->uri; struct auth_entry *auth = find_auth(uri); struct string string; unsigned char *url; int dir; if ((uri->userlen && uri->passwordlen) || !auth) { url = get_uri_string(uri, URI_BASE); } else { unsigned char *uri_string = get_uri_string(uri, URI_HOST | URI_PORT | URI_DATA); if (!uri_string || !init_string(&string)) { smb_error(connection_state(S_OUT_OF_MEM)); } /* Must URI-encode the username and password to avoid * ambiguity if they contain "/:@" characters. * Libsmbclient then decodes them again, and the * server gets them as they were in auth->user and * auth->password, i.e. as the user typed them in the * auth dialog. This implies that, if the username or * password contains some characters or bytes that the * user cannot directly type, then she cannot enter * them. If that becomes an actual problem, it should * be fixed in the auth dialog, e.g. by providing a * hexadecimal input mode. */ add_to_string(&string, "smb://"); encode_uri_string(&string, auth->user, -1, 1); add_char_to_string(&string, ':'); encode_uri_string(&string, auth->password, -1, 1); add_char_to_string(&string, '@'); add_to_string(&string, uri_string); url = string.source; } if (!url) { smb_error(connection_state(S_OUT_OF_MEM)); } if (smbc_init(smb_auth, 0)) { smb_error(connection_state_for_errno(errno)); }; dir = smbc_opendir(url); if (dir >= 0) { struct string prefix; init_string(&prefix); add_to_string(&prefix, url); add_char_to_string(&prefix, '/'); smb_directory(dir, &prefix, conn->uri); done_string(&prefix); } else { const int errno_from_opendir = errno; char buf[READ_SIZE]; struct stat sb; int r, res, fdout; int file = smbc_open(url, O_RDONLY, 0); if (file < 0) { /* If we're opening the list of shares without * proper authentication, then smbc_opendir * fails with EACCES and smbc_open fails with * ENOENT. In this case, return the EACCES so * that the parent ELinks process will prompt * for credentials. */ if (errno == ENOENT && errno_from_opendir == EACCES) errno = errno_from_opendir; smb_error(connection_state_for_errno(errno)); } res = smbc_fstat(file, &sb); if (res) { smb_error(connection_state_for_errno(res)); } /* filesize */ fprintf(header_out, "%" OFF_PRINT_FORMAT, (off_print_T) sb.st_size); fclose(header_out); fdout = fileno(data_out); while ((r = smbc_read(file, buf, READ_SIZE)) > 0) { if (safe_write(fdout, buf, r) <= 0) break; } smbc_close(file); exit(0); } }
static int fill_buffer(stream_t *s, char* buffer, int max_len){ struct priv *p = s->priv; int r = smbc_read(p->fd,buffer,max_len); return (r <= 0) ? -1 : r; }
//=========================================================================== void SMBSlave::get( const KURL& kurl ) { char buf[MAX_XFER_BUF_SIZE]; int filefd = 0; ssize_t bytesread = 0; // time_t curtime = 0; time_t lasttime = 0; time_t starttime = 0; KIO::filesize_t totalbytesread = 0; QByteArray filedata; SMBUrl url; kdDebug(KIO_SMB) << "SMBSlave::get on " << kurl << endl; // check (correct) URL KURL kvurl = checkURL(kurl); // if URL is not valid we have to redirect to correct URL if (kvurl != kurl) { redirection(kvurl); finished(); return; } if(!auth_initialize_smbc()) return; // Stat url = kurl; if(cache_stat(url,&st) == -1 ) { if ( errno == EACCES ) error( KIO::ERR_ACCESS_DENIED, url.prettyURL()); else error( KIO::ERR_DOES_NOT_EXIST, url.prettyURL()); return; } if ( S_ISDIR( st.st_mode ) ) { error( KIO::ERR_IS_DIRECTORY, url.prettyURL()); return; } // Set the total size totalSize( st.st_size ); // Open and read the file filefd = smbc_open(url.toSmbcUrl(),O_RDONLY,0); if(filefd >= 0) { if(buf) { bool isFirstPacket = true; lasttime = starttime = time(NULL); while(1) { bytesread = smbc_read(filefd, buf, MAX_XFER_BUF_SIZE); if(bytesread == 0) { // All done reading break; } else if(bytesread < 0) { error( KIO::ERR_COULD_NOT_READ, url.prettyURL()); return; } filedata.setRawData(buf,bytesread); if (isFirstPacket) { // We need a KMimeType::findByNameAndContent(filename,data) // For now we do: find by extension, and if not found (or extension not reliable) // then find by content. bool accurate = false; KMimeType::Ptr mime = KMimeType::findByURL( kurl, st.st_mode, false, true, &accurate ); if ( !mime || mime->name() == KMimeType::defaultMimeType() || !accurate ) { KMimeType::Ptr p_mimeType = KMimeType::findByContent(filedata); if ( p_mimeType && p_mimeType->name() != KMimeType::defaultMimeType() ) mime = p_mimeType; } mimeType(mime->name()); isFirstPacket = false; } data( filedata ); filedata.resetRawData(buf,bytesread); // increment total bytes read totalbytesread += bytesread; processedSize(totalbytesread); } } smbc_close(filefd); data( QByteArray() ); processedSize(static_cast<KIO::filesize_t>(st.st_size)); } else { error( KIO::ERR_CANNOT_OPEN_FOR_READING, url.prettyURL()); return; } finished(); }
static int fill_buffer(stream_t *s, char* buffer, int max_len){ int r = smbc_read(s->fd,buffer,max_len); return (r <= 0) ? -1 : r; }
void SMBSlave::smbCopyGet(const QUrl& ksrc, const QUrl& kdst, int permissions, KIO::JobFlags flags) { qCDebug(KIO_SMB) << "src = " << ksrc << ", dest = " << kdst; // check if destination is ok ... const QString dstFile = kdst.toLocalFile(); const QFileInfo dstInfo (dstFile); if(dstInfo.exists()) { if(dstInfo.isDir()) { error (ERR_IS_DIRECTORY, kdst.toDisplayString()); return; } if(!(flags & KIO::Overwrite)) { error(ERR_FILE_ALREADY_EXIST, kdst.toDisplayString()); return; } } bool bResume = false; const QFileInfo partInfo (dstFile + QLatin1String(".part")); const bool bPartExists = partInfo.exists(); const bool bMarkPartial = config()->readEntry("MarkPartial", true); if (bMarkPartial && bPartExists && partInfo.size() > 0) { if (partInfo.isDir()) { error(ERR_IS_DIRECTORY, partInfo.absoluteFilePath()); return; } bResume = canResume(partInfo.size()); } if (bPartExists && !bResume) // get rid of an unwanted ".part" file QFile::remove(partInfo.absoluteFilePath()); // open the output file... QFile::OpenMode mode; QString filename; if (bResume) { filename = partInfo.absoluteFilePath(); mode = QFile::WriteOnly | QFile::Append; } else { filename = (bMarkPartial ? partInfo.absoluteFilePath() : dstFile); mode = QFile::WriteOnly | QFile::Truncate; } QFile file (filename); if (!bResume) { QFile::Permissions perms; if (permissions == -1) { perms = QFile::ReadOwner | QFile::WriteOwner; } else { perms = KIO::convertPermissions(permissions | QFile::WriteOwner); } file.setPermissions(perms); } if (!file.open(mode)) { qCDebug(KIO_SMB) << "could not write to" << dstFile; switch (file.error()) { case QFile::OpenError: if (bResume) { error (ERR_CANNOT_RESUME, kdst.toDisplayString()); } else { error(ERR_CANNOT_OPEN_FOR_WRITING, kdst.toDisplayString()); } break; case QFile::PermissionsError: error(ERR_WRITE_ACCESS_DENIED, kdst.toDisplayString()); break; default: error(ERR_CANNOT_OPEN_FOR_WRITING, kdst.toDisplayString()); break; } return; } // setup the source urls const SMBUrl src(ksrc); // Obtain information about source int errNum = cache_stat (src, &st); if (errNum != 0) { if (errNum == EACCES) { error (KIO::ERR_ACCESS_DENIED, src.toDisplayString()); } else { error (KIO::ERR_DOES_NOT_EXIST, src.toDisplayString()); } return; } if (S_ISDIR( st.st_mode )) { error (KIO::ERR_IS_DIRECTORY, src.toDisplayString()); return; } totalSize(st.st_size); // Open the source file KIO::filesize_t processed_size = 0; int srcfd = smbc_open(src.toSmbcUrl(), O_RDONLY, 0); if (srcfd < 0){ errNum = errno; } else { errNum = 0; if (bResume) { qCDebug(KIO_SMB) << "seeking to size" << partInfo.size(); off_t offset = smbc_lseek(srcfd, partInfo.size(), SEEK_SET); if (offset == -1) { error(KIO::ERR_COULD_NOT_SEEK, src.toDisplayString()); smbc_close(srcfd); return; } else { processed_size += offset; } } } if (srcfd < 0) { if(errNum == EACCES) { error( KIO::ERR_ACCESS_DENIED, src.toDisplayString() ); } else { error( KIO::ERR_DOES_NOT_EXIST, src.toDisplayString() ); } return; } // Perform the copy char buf[MAX_XFER_BUF_SIZE]; bool isErr = false; while (1) { const ssize_t bytesRead = smbc_read(srcfd, buf, MAX_XFER_BUF_SIZE); if (bytesRead <= 0) { if (bytesRead < 0) { error( KIO::ERR_COULD_NOT_READ, src.toDisplayString()); isErr = true; } break; } const qint64 bytesWritten = file.write(buf, bytesRead); if (bytesWritten == -1) { qCDebug(KIO_SMB) << "copy now KIO::ERR_COULD_NOT_WRITE"; error( KIO::ERR_COULD_NOT_WRITE, kdst.toDisplayString()); isErr = true; break; } processed_size += bytesWritten; processedSize(processed_size); } // FINISHED smbc_close(srcfd); // Handle error condition. if (isErr) { const QString sPart = partInfo.absoluteFilePath(); if (bMarkPartial) { const int size = config()->readEntry("MinimumKeepSize", DEFAULT_MINIMUM_KEEP_SIZE); if (partInfo.size() < size) { QFile::remove(sPart); } } return; } // Rename partial file to its original name. if (bMarkPartial) { const QString sPart = partInfo.absoluteFilePath(); // Remove old dest file if it exists.. if (dstInfo.exists()) { QFile::remove(dstFile); } if (!QFile::rename(sPart, dstFile)) { qCDebug(KIO_SMB) << "failed to rename" << sPart << "to" << dstFile; error(ERR_CANNOT_RENAME_PARTIAL, sPart); return; } } // Restore the mtime on the file. const QString mtimeStr = metaData("modified"); qCDebug(KIO_SMB) << "modified:" << mtimeStr; if (!mtimeStr.isEmpty()) { QDateTime dt = QDateTime::fromString(mtimeStr, Qt::ISODate); if (dt.isValid()) { struct utimbuf utbuf; utbuf.actime = QFileInfo(file).lastRead().toTime_t(); // access time, unchanged utbuf.modtime = dt.toTime_t(); // modification time utime(QFile::encodeName(dstFile).constData(), &utbuf); } } finished(); }