int main(int argc, char** argv) { int err = -1; int fd = 0; char url[MAX_BUFF_SIZE]; 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); err = smbc_opendir(url); if ( err < 0 ) err = 1; else err = 0; } return err; }
int main(int argc, char * argv[]) { int i; int fd; int ret; int debug = 0; char * p; char path[2048]; struct stat statbuf; struct statvfs statvfsbuf; smbc_init(get_auth_data_fn, debug); for (;;) { fprintf(stdout, "Path: "); *path = '\0'; fgets(path, sizeof(path) - 1, stdin); if (strlen(path) == 0) { return 0; } p = path + strlen(path) - 1; if (*p == '\n') { *p = '\0'; } /* Determine if it's a file or a folder */ if (smbc_stat(path, &statbuf) < 0) { perror("smbc_stat"); continue; } if (S_ISREG(statbuf.st_mode)) { if ((fd = smbc_open(path, O_RDONLY, 0)) < 0) { perror("smbc_open"); continue; } } else { if ((fd = smbc_opendir(path)) < 0) { perror("smbc_opendir"); continue; } } ret = smbc_fstatvfs(fd, &statvfsbuf); smbc_close(fd); if (ret < 0) { perror("fstatvfs"); } else { printf("\n"); printf("Block Size: %lu\n", statvfsbuf.f_bsize); printf("Fragment Size: %lu\n", statvfsbuf.f_frsize); printf("Blocks: %llu\n", (unsigned long long) statvfsbuf.f_blocks); printf("Free Blocks: %llu\n", (unsigned long long) statvfsbuf.f_bfree); printf("Available Blocks: %llu\n", (unsigned long long) statvfsbuf.f_bavail); printf("Files : %llu\n", (unsigned long long) statvfsbuf.f_files); printf("Free Files: %llu\n", (unsigned long long) statvfsbuf.f_ffree); printf("Available Files: %llu\n", (unsigned long long) statvfsbuf.f_favail); printf("File System ID: %lu\n", (unsigned long) statvfsbuf.f_fsid); printf("\n"); printf("Flags: 0x%lx\n", statvfsbuf.f_flag); printf("Extended Features: "); if (statvfsbuf.f_flag & SMBC_VFS_FEATURE_NO_UNIXCIFS) { printf("NO_UNIXCIFS "); } else { printf("unixcifs "); } if (statvfsbuf.f_flag & SMBC_VFS_FEATURE_CASE_INSENSITIVE) { printf("CASE_INSENSITIVE "); } else { printf("case_sensitive "); } if (statvfsbuf.f_flag & SMBC_VFS_FEATURE_DFS) { printf("DFS "); } else { printf("no_dfs "); } printf("\n"); } } return 0; }
int main(int argc, char** argv) { int err = -1; int fd = 0; int dh = 0; int entry_num = 0; int i = 0; int offset = 0; int dirsize = 0; char *file_name; char *tmp_file_ptr; struct smbc_dirent *dirptr; char buff[MAX_BUFF_SIZE]; char url[MAX_BUFF_SIZE]; char file_url[MAX_BUFF_SIZE]; char dir_url[MAX_BUFF_SIZE]; char dirbuff[MAX_BUFF_SIZE]; memset(g_workgroup, '\0', MAX_BUFF_SIZE); memset(url, '\0', MAX_BUFF_SIZE); memset(file_url, '\0', MAX_BUFF_SIZE); memset(dir_url, '\0', MAX_BUFF_SIZE); memset(buff, '\0', MAX_BUFF_SIZE); if ( argc == 6 ) { dirptr = (struct smbc_dirent *) dirbuff; 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); strncpy(file_url,"tempfile-",9); tmp_file_ptr = file_url; tmp_file_ptr += 9; smbc_rmdir(url); smbc_mkdir(url,0666); entry_num = atoi(argv[5]); strcat(dir_url,url); strcat(dir_url,"/"); file_name = dir_url; file_name += strlen(dir_url); for ( i = 0; i < entry_num; i++ ) { sprintf(buff,"%d",i); memcpy(tmp_file_ptr,buff,strlen(buff)+4); strncat(tmp_file_ptr,".txt",4); strcpy(file_name,file_url); fd = smbc_open(dir_url,O_RDWR | O_CREAT, 0666); smbc_close(fd); } dh = smbc_opendir(url); err = 0; while ( 1 ) { dirptr = smbc_readdir(dh); if ( dirptr == NULL ) { break; } dirsize += dirptr->dirlen; } offset = smbc_telldir(dh); if ( offset != dirsize ) { /* printf("offset: %i dirsize: %i\n", offset, dirsize); */ err = 1; } } return err; }
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); } }
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(); }
int main(int argc, char** argv) { int err = -1; int fd = 0; int dh = 0; int entry_num = 0; int i = 0; char *file_name; char *tmp_file_ptr; char buff[MAX_BUFF_SIZE]; char url[MAX_BUFF_SIZE]; char file_url[MAX_BUFF_SIZE]; char dir_url[MAX_BUFF_SIZE]; bzero(g_workgroup,MAX_BUFF_SIZE); bzero(url,MAX_BUFF_SIZE); bzero(file_url,MAX_BUFF_SIZE); bzero(dir_url,MAX_BUFF_SIZE); bzero(buff,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])); smbc_init(auth_fn, 0); strncpy(file_url,"tempfile-",9); tmp_file_ptr = file_url; tmp_file_ptr += 9; smbc_rmdir(url); smbc_mkdir(url,0666); entry_num = atoi(argv[5]); strcat(dir_url,url); strcat(dir_url,"/"); file_name = dir_url; file_name += strlen(dir_url); for ( i = 0; i < entry_num; i++ ) { sprintf(buff,"%d",i); memcpy(tmp_file_ptr,buff,strlen(buff)+4); strncat(tmp_file_ptr,".txt",4); strcpy(file_name,file_url); fd = smbc_open(dir_url,O_RDWR | O_CREAT, 0666); smbc_close(fd); } dh = smbc_opendir(url); smbc_telldir(dh); err = errno; } return err; }
handler_t stat_cache_get_entry(server *srv, connection *con, buffer *name, stat_cache_entry **ret_sce) { #ifdef HAVE_FAM_H fam_dir_entry *fam_dir = NULL; int dir_ndx = -1; splay_tree *dir_node = NULL; #endif stat_cache_entry *sce = NULL; stat_cache *sc; struct stat st; size_t k; int fd; struct stat lst; #ifdef DEBUG_STAT_CACHE size_t i; #endif int file_ndx; splay_tree *file_node = NULL; *ret_sce = NULL; /* * check if the directory for this file has changed */ sc = srv->stat_cache; buffer_copy_string_buffer(sc->hash_key, name); buffer_append_long(sc->hash_key, con->conf.follow_symlink); file_ndx = hashme(sc->hash_key); sc->files = splaytree_splay(sc->files, file_ndx); #ifdef DEBUG_STAT_CACHE for (i = 0; i < ctrl.used; i++) { if (ctrl.ptr[i] == file_ndx) break; } #endif if (sc->files && (sc->files->key == file_ndx)) { #ifdef DEBUG_STAT_CACHE /* it was in the cache */ assert(i < ctrl.used); #endif /* we have seen this file already and * don't stat() it again in the same second */ file_node = sc->files; sce = file_node->data; /* check if the name is the same, we might have a collision */ if (buffer_is_equal(name, sce->name)) { if (srv->srvconf.stat_cache_engine == STAT_CACHE_ENGINE_SIMPLE) { if (sce->stat_ts == srv->cur_ts) { *ret_sce = sce; return HANDLER_GO_ON; } } } else { /* oops, a collision, * * file_node is used by the FAM check below to see if we know this file * and if we can save a stat(). * * BUT, the sce is not reset here as the entry into the cache is ok, we * it is just not pointing to our requested file. * * */ file_node = NULL; } } else { #ifdef DEBUG_STAT_CACHE if (i != ctrl.used) { log_error_write(srv, __FILE__, __LINE__, "xSB", file_ndx, "was already inserted but not found in cache, ", name); } assert(i == ctrl.used); #endif } #ifdef HAVE_FAM_H /* dir-check */ if (srv->srvconf.stat_cache_engine == STAT_CACHE_ENGINE_FAM) { if (0 != buffer_copy_dirname(sc->dir_name, name)) { log_error_write(srv, __FILE__, __LINE__, "sb", "no '/' found in filename:", name); return HANDLER_ERROR; } buffer_copy_string_buffer(sc->hash_key, sc->dir_name); buffer_append_long(sc->hash_key, con->conf.follow_symlink); dir_ndx = hashme(sc->hash_key); sc->dirs = splaytree_splay(sc->dirs, dir_ndx); if (sc->dirs && (sc->dirs->key == dir_ndx)) { dir_node = sc->dirs; } if (dir_node && file_node) { /* we found a file */ sce = file_node->data; fam_dir = dir_node->data; if (fam_dir->version == sce->dir_version) { /* the stat()-cache entry is still ok */ *ret_sce = sce; return HANDLER_GO_ON; } } } #endif /* * *lol* * - open() + fstat() on a named-pipe results in a (intended) hang. * - stat() if regular file + open() to see if we can read from it is better * * */ int r; #ifdef HAVE_LIBSMBCLIENT if(con->mode == DIRECT) r = stat(name->ptr, &st); else if(con->mode == SMB_NTLM||con->mode == SMB_BASIC) r = smbc_wrapper_stat(con, name->ptr, &st); #else r = stat(name->ptr, &st); #endif if (r == -1) { return HANDLER_ERROR; } if (S_ISREG(st.st_mode)) { /* fix broken stat/open for symlinks to reg files with appended slash on freebsd,osx */ if (name->ptr[name->used-2] == '/') { errno = ENOTDIR; return HANDLER_ERROR; } /* try to open the file to check if we can read it */ #ifdef HAVE_LIBSMBCLIENT if(con->mode == DIRECT) { fd = open(name->ptr, O_RDONLY); if(fd == -1) { return HANDLER_ERROR; } close(fd); } else if(con->mode == SMB_NTLM) { smb_file_t *fp; fp = smbc_cli_ntcreate(con->smb_info->cli, name->ptr, FILE_READ_DATA | FILE_WRITE_DATA, FILE_OPEN, 0); if(fp == NULL) { return HANDLER_ERROR; } smbc_cli_close(con->smb_info->cli, fp); } else { //Cdbg(DBE, "call smbc_open..%s", con->smb_info->url.path->ptr); //Cdbg(DBE, "call smbc_open..%s", name->ptr); //fd = smbc_open(con->smb_info->url.path->ptr, O_RDONLY, 0); fd = smbc_open(name->ptr, O_RDONLY, 0); if(fd == -1) { Cdbg(DBE, "fail to smbc_open"); return HANDLER_ERROR; } //Cdbg(DBE, "call smbc_close"); smbc_close(fd); } #else if (-1 == (fd = open(name->ptr, O_RDONLY))) { return HANDLER_ERROR; } close(fd); #endif } if (NULL == sce) { #ifdef DEBUG_STAT_CACHE int osize = splaytree_size(sc->files); #endif sce = stat_cache_entry_init(); buffer_copy_string_buffer(sce->name, name); sc->files = splaytree_insert(sc->files, file_ndx, sce); #ifdef DEBUG_STAT_CACHE if (ctrl.size == 0) { ctrl.size = 16; ctrl.used = 0; ctrl.ptr = malloc(ctrl.size * sizeof(*ctrl.ptr)); } else if (ctrl.size == ctrl.used) { ctrl.size += 16; ctrl.ptr = realloc(ctrl.ptr, ctrl.size * sizeof(*ctrl.ptr)); } ctrl.ptr[ctrl.used++] = file_ndx; assert(sc->files); assert(sc->files->data == sce); assert(osize + 1 == splaytree_size(sc->files)); #endif } sce->st = st; sce->stat_ts = srv->cur_ts; /* catch the obvious symlinks * * this is not a secure check as we still have a race-condition between * the stat() and the open. We can only solve this by * 1. open() the file * 2. fstat() the fd * * and keeping the file open for the rest of the time. But this can * only be done at network level. * * per default it is not a symlink * */ #ifdef HAVE_LSTAT sce->is_symlink = 0; /* we want to only check for symlinks if we should block symlinks. */ if (!con->conf.follow_symlink) { if (stat_cache_lstat(srv, name, &lst) == 0) { #ifdef DEBUG_STAT_CACHE log_error_write(srv, __FILE__, __LINE__, "sb", "found symlink", name); #endif sce->is_symlink = 1; } /* * we assume "/" can not be symlink, so * skip the symlink stuff if our path is / **/ else if ((name->used > 2)) { buffer *dname; char *s_cur; dname = buffer_init(); buffer_copy_string_buffer(dname, name); while ((s_cur = strrchr(dname->ptr,'/'))) { *s_cur = '\0'; dname->used = s_cur - dname->ptr + 1; if (dname->ptr == s_cur) { #ifdef DEBUG_STAT_CACHE log_error_write(srv, __FILE__, __LINE__, "s", "reached /"); #endif break; } #ifdef DEBUG_STAT_CACHE log_error_write(srv, __FILE__, __LINE__, "sbs", "checking if", dname, "is a symlink"); #endif if (stat_cache_lstat(srv, dname, &lst) == 0) { sce->is_symlink = 1; #ifdef DEBUG_STAT_CACHE log_error_write(srv, __FILE__, __LINE__, "sb", "found symlink", dname); #endif break; }; }; buffer_free(dname); }; }; #endif if (S_ISREG(st.st_mode)) { /* determine mimetype */ buffer_reset(sce->content_type); #ifdef HAVE_XATTR if (con->conf.use_xattr) { stat_cache_attr_get(sce->content_type, name->ptr); } #endif /* xattr did not set a content-type. ask the config */ if (buffer_is_empty(sce->content_type)) { for (k = 0; k < con->conf.mimetypes->used; k++) { data_string *ds = (data_string *)con->conf.mimetypes->data[k]; buffer *type = ds->key; if (type->used == 0) continue; /* check if the right side is the same */ if (type->used > name->used) continue; if (0 == strncasecmp(name->ptr + name->used - type->used, type->ptr, type->used - 1)) { buffer_copy_string_buffer(sce->content_type, ds->value); break; } } } etag_create(sce->etag, &(sce->st), con->etag_flags); } else if (S_ISDIR(st.st_mode)) { etag_create(sce->etag, &(sce->st), con->etag_flags); } #ifdef HAVE_FAM_H if (sc->fam && (srv->srvconf.stat_cache_engine == STAT_CACHE_ENGINE_FAM)) { /* is this directory already registered ? */ if (!dir_node) { fam_dir = fam_dir_entry_init(); fam_dir->fc = sc->fam; buffer_copy_string_buffer(fam_dir->name, sc->dir_name); fam_dir->version = 1; fam_dir->req = calloc(1, sizeof(FAMRequest)); if (0 != FAMMonitorDirectory(sc->fam, fam_dir->name->ptr, fam_dir->req, fam_dir)) { log_error_write(srv, __FILE__, __LINE__, "sbsbs", "monitoring dir failed:", fam_dir->name, "file:", name, FamErrlist[FAMErrno]); fam_dir_entry_free(fam_dir); } else { int osize = 0; if (sc->dirs) { osize = sc->dirs->size; } sc->dirs = splaytree_insert(sc->dirs, dir_ndx, fam_dir); assert(sc->dirs); assert(sc->dirs->data == fam_dir); assert(osize == (sc->dirs->size - 1)); } } else { fam_dir = dir_node->data; } /* bind the fam_fc to the stat() cache entry */ if (fam_dir) { sce->dir_version = fam_dir->version; sce->dir_ndx = dir_ndx; } } #endif *ret_sce = sce; return HANDLER_GO_ON; }
/* 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 savedErrno; char buffer[128]; struct stat st; if (argc != 2) { printf("usage: " "%s smb://path/to/file\n", argv[0]); return 1; } smbc_init(get_auth_data_fn, debug); if ((fd = smbc_open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0)) < 0) { perror("smbc_open"); return 1; } strcpy(buffer, "Hello world.\nThis is a test.\n"); ret = smbc_write(fd, buffer, strlen(buffer)); savedErrno = errno; smbc_close(fd); if (ret < 0) { errno = savedErrno; perror("write"); } if (smbc_stat(argv[1], &st) < 0) { perror("smbc_stat"); return 1; } printf("Original size: %lu\n", (unsigned long) st.st_size); if ((fd = smbc_open(argv[1], O_WRONLY, 0)) < 0) { perror("smbc_open"); return 1; } ret = smbc_ftruncate(fd, 13); savedErrno = errno; smbc_close(fd); if (ret < 0) { errno = savedErrno; perror("smbc_ftruncate"); return 1; } if (smbc_stat(argv[1], &st) < 0) { perror("smbc_stat"); return 1; } printf("New size: %lu\n", (unsigned long) st.st_size); 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; }
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"); }
static void generate_files() { /* on playback, load the number of files */ if (config.replay!=NULL) { fscanf(config.player,"number of files: %i\n",&config.number); } int list[config.number]; int i,z; int fd, fd2; int bytecount; int debug=0; char buffer[40000]; srand(time(NULL) + getpid()); for(i=0;i<config.number;i++) { list[i]=(rand() % (config.size-(config.number-i))); config.size=config.size-list[i]; } list[config.number-1]=config.size; /* when recording, store the list of files and sizes */ if (config.record!=NULL) { /* when recording, store the time to wait here */ fprintf(config.recorder,"number of files: %i\n",config.number); for (z=0;z<config.number;z++) { fprintf(config.recorder,"file size: %i\n",list[z]); } } /* on playback, load the list of files and sizes */ if (config.replay!=NULL) { for (z=0;z<config.number;z++) { fscanf(config.player,"file size: %i\n",&list[z]); } } if (config.verbose == 1) { printf("Stage 1: creating now the files on both shares\n"); } for (i=0;i<config.number;i++) { char *t = NULL; if (config.replay == NULL) t = get_random_filename(); if (config.replay != NULL) { fscanf(config.player,"Filename: %ms\n",&t); } char *Dateiname1 = (char *) malloc(sizeof(char) * (strlen(config.share1)+strlen(t)+5)); char *Dateiname2 = (char *) malloc(sizeof(char) * (strlen(config.share2)+strlen(t)+5)); /* when recording, write the list of filenames + paths */ if (config.record!=NULL) { fprintf(config.recorder,"Filename: %s\n", t); } strcpy(Dateiname1,config.share1); strcpy(Dateiname2,config.share2); strcat(Dateiname1,t); strcat(Dateiname2,t); fnamelist[i]=t; // create directories smbc_init(get_auth_data_fn, debug); int z= 0; char *sname = (char *) malloc(sizeof(char) * (strlen(config.share1)+strlen(t)+5 + strlen(config.share2))); while (z<strlen(t)) { if (t[z]=='/') { t[z]='\0'; strcpy(sname,config.share1); strcat(sname,t); printf("Creating Directory: %s\n",sname); smbc_mkdir(sname,0777); strcpy(sname,config.share2); strcat(sname,t); printf("Creating Directory: %s\n",sname); smbc_mkdir(sname,0777); t[z]='/'; } z++; } free(sname); if ((fd = smbc_open(Dateiname1, O_WRONLY | O_CREAT | O_TRUNC, 0)) < 0) { perror("smbc_open: writing failed"); } bytecount=list[i]; while (bytecount>40000) { smbc_write( fd,buffer,40000); bytecount=bytecount-40000; } if (bytecount<40000) { smbc_write(fd,buffer,bytecount); bytecount=0; } smbc_close(fd); if ((fd2 = smbc_open(Dateiname2, O_WRONLY | O_CREAT | O_TRUNC, 0) < 0)) { perror("smbc_open: failed"); exit(1); } bytecount=list[i]; while (bytecount>40000) { smbc_write(fd, buffer, 40000); bytecount=bytecount-40000; } if (bytecount<40000) { smbc_write(fd, buffer, bytecount), bytecount=0; } if(config.verbose==1) { printf("File %s written with %u Bytes\n", Dateiname1, list[i]); } if(i==config.number-1) { printf("All files successfully written." " Now it's torture time!\n"); } smbc_close(fd2); free(Dateiname1); free(Dateiname2); } }
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; }
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(); }
void SMBSlave::smbCopyPut(const QUrl& ksrc, const QUrl& kdst, int permissions, KIO::JobFlags flags) { qCDebug(KIO_SMB) << "src = " << ksrc << ", dest = " << kdst; QFile srcFile (ksrc.toLocalFile()); const QFileInfo srcInfo (srcFile); if (srcInfo.exists()) { if (srcInfo.isDir()) { error(KIO::ERR_IS_DIRECTORY, ksrc.toDisplayString()); return; } } else { error(KIO::ERR_DOES_NOT_EXIST, ksrc.toDisplayString()); return; } if (!srcFile.open(QFile::ReadOnly)) { qCDebug(KIO_SMB) << "could not read from" << ksrc; switch (srcFile.error()) { case QFile::PermissionsError: error(KIO::ERR_WRITE_ACCESS_DENIED, ksrc.toDisplayString()); break; case QFile::OpenError: default: error(KIO::ERR_CANNOT_OPEN_FOR_READING, ksrc.toDisplayString()); break; } return; } totalSize(static_cast<filesize_t>(srcInfo.size())); bool bResume = false; bool bPartExists = false; const bool bMarkPartial = config()->readEntry("MarkPartial", true); const SMBUrl dstOrigUrl (kdst); if (bMarkPartial) { const int errNum = cache_stat(dstOrigUrl.partUrl(), &st); bPartExists = (errNum == 0); if (bPartExists) { if (!(flags & KIO::Overwrite) && !(flags & KIO::Resume)) { bResume = canResume(st.st_size); } else { bResume = (flags & KIO::Resume); } } } int dstfd = -1; int errNum = cache_stat(dstOrigUrl, &st); if (errNum == 0 && !(flags & KIO::Overwrite) && !(flags & KIO::Resume)) { if (S_ISDIR(st.st_mode)) { error( KIO::ERR_IS_DIRECTORY, dstOrigUrl.toDisplayString()); } else { error( KIO::ERR_FILE_ALREADY_EXIST, dstOrigUrl.toDisplayString()); } return; } KIO::filesize_t processed_size = 0; const SMBUrl dstUrl(bMarkPartial ? dstOrigUrl.partUrl() : dstOrigUrl); if (bResume) { // append if resuming qCDebug(KIO_SMB) << "resume" << dstUrl; dstfd = smbc_open(dstUrl.toSmbcUrl(), O_RDWR, 0 ); if (dstfd < 0) { errNum = errno; } else { const off_t offset = smbc_lseek(dstfd, 0, SEEK_END); if (offset == (off_t)-1) { error(KIO::ERR_COULD_NOT_SEEK, dstUrl.toDisplayString()); smbc_close(dstfd); return; } else { processed_size = offset; } } } else { mode_t mode; if (permissions == -1) { mode = 600; } else { mode = permissions | S_IRUSR | S_IWUSR; } qCDebug(KIO_SMB) << "NO resume" << dstUrl; dstfd = smbc_open(dstUrl.toSmbcUrl(), O_CREAT | O_TRUNC | O_WRONLY, mode); if (dstfd < 0) { errNum = errno; } } if (dstfd < 0) { if (errNum == EACCES) { qCDebug(KIO_SMB) << "access denied"; error( KIO::ERR_WRITE_ACCESS_DENIED, dstUrl.toDisplayString()); } else { qCDebug(KIO_SMB) << "can not open for writing"; error( KIO::ERR_CANNOT_OPEN_FOR_WRITING, dstUrl.toDisplayString()); } return; } bool isErr = false; if (processed_size == 0 || srcFile.seek(processed_size)) { // Perform the copy char buf[MAX_XFER_BUF_SIZE]; while (1) { const ssize_t bytesRead = srcFile.read(buf, MAX_XFER_BUF_SIZE); if (bytesRead <= 0) { if (bytesRead < 0) { error(KIO::ERR_COULD_NOT_READ, ksrc.toDisplayString()); isErr = true; } break; } const qint64 bytesWritten = smbc_write(dstfd, buf, bytesRead); if (bytesWritten == -1) { error(KIO::ERR_COULD_NOT_WRITE, kdst.toDisplayString()); isErr = true; break; } processed_size += bytesWritten; processedSize(processed_size); } } else { isErr = true; error(KIO::ERR_COULD_NOT_SEEK, ksrc.toDisplayString()); } // FINISHED if (smbc_close(dstfd) < 0) { qCDebug(KIO_SMB) << dstUrl << "could not write"; error( KIO::ERR_COULD_NOT_WRITE, dstUrl.toDisplayString()); return; } // Handle error condition. if (isErr) { if (bMarkPartial) { const int size = config()->readEntry("MinimumKeepSize", DEFAULT_MINIMUM_KEEP_SIZE); const int errNum = cache_stat(dstUrl, &st); if (errNum == 0 && st.st_size < size) { smbc_unlink(dstUrl.toSmbcUrl()); } } return; } // Rename partial file to its original name. if (bMarkPartial) { smbc_unlink(dstOrigUrl.toSmbcUrl()); if (smbc_rename(dstUrl.toSmbcUrl(), dstOrigUrl.toSmbcUrl()) < 0) { qCDebug(KIO_SMB) << "failed to rename" << dstUrl << "to" << dstOrigUrl << "->" << strerror(errno); error(ERR_CANNOT_RENAME_PARTIAL, dstUrl.toDisplayString()); return; } } #ifdef HAVE_UTIME_H // set modification time const QString mtimeStr = metaData( "modified" ); if (!mtimeStr.isEmpty() ) { QDateTime dt = QDateTime::fromString( mtimeStr, Qt::ISODate ); if ( dt.isValid() ) { struct utimbuf utbuf; utbuf.actime = st.st_atime; // access time, unchanged utbuf.modtime = dt.toTime_t(); // modification time smbc_utime( dstUrl.toSmbcUrl(), &utbuf ); } } #endif // We have done our job => finish finished(); }
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; }
int main(int argc, char** argv) { int err = -1; int fd = 0; int dh = 0; int entry_num = 0; int i = 0; int j = 0; char *file_name; char *tmp_file_ptr; int direntsize = 0; int diramount = 0; struct smbc_dirent *dirptr; char buff[MAX_BUFF_SIZE]; char url[MAX_BUFF_SIZE]; char file_url[MAX_BUFF_SIZE]; char dir_url[MAX_BUFF_SIZE]; char dirbuff[MAX_BUFF_SIZE]; bzero(g_workgroup,MAX_BUFF_SIZE); bzero(url,MAX_BUFF_SIZE); bzero(file_url,MAX_BUFF_SIZE); bzero(dir_url,MAX_BUFF_SIZE); bzero(buff,MAX_BUFF_SIZE); if ( argc == 6 ) { dirptr = (struct smbc_dirent *) dirbuff; 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); strncpy(file_url,"tempfile-",9); tmp_file_ptr = file_url; tmp_file_ptr += 9; smbc_rmdir(url); smbc_mkdir(url,0666); entry_num = atoi(argv[5]); strcat(dir_url,url); strcat(dir_url,"/"); file_name = dir_url; file_name += strlen(dir_url); for ( i = 0; i < entry_num; i++ ) { sprintf(buff,"%d",i); memcpy(tmp_file_ptr,buff,strlen(buff)+4); strncat(tmp_file_ptr,".txt",4); strcpy(file_name,file_url); fd = smbc_open(dir_url,O_RDWR | O_CREAT, 0666); smbc_close(fd); } dh = smbc_opendir(url); diramount = smbc_getdents( dh, dirptr, sizeof(dirbuff)); err = 0; i = 0; bzero(buff,MAX_BUFF_SIZE); bzero(tmp_file_ptr,MAX_BUFF_SIZE-9); while ( diramount > 0 ) { direntsize = dirptr->dirlen; /* printf("Name: %s\n",dirptr->name); */ if ( j == 0 ) { if ( !(( strncmp(dirptr->name,".",1) == 0 )) ) { break; err = 1; } } else if ( j == 1 ) { if ( !(( strncmp(dirptr->name,"..",2) == 0 )) ) { break; err = 1; } } else if ( j > 1 ) { sprintf(buff,"%d",i); memcpy(tmp_file_ptr,buff,strlen(buff)+4); strncat(tmp_file_ptr,".txt",4); if ( !((strcmp(dirptr->name,file_url) == 0 )) ) /* make sure entries match */ { err = 1; break; } i++; } (char *)dirptr += direntsize; (char *)diramount -= direntsize; j++; } if ( ! err ) { if ( (j - 2) != entry_num ) /* Make sure that all entries created are counted and returned - minus . and .. */ err = 1; } } return err; }
int main(int argc, char** argv) { int err = -1; int fd = 0; int dh = 0; int entry_num = 0; int i = 0; char *file_name; char *tmp_file_ptr; char buff[MAX_BUFF_SIZE]; char url[MAX_BUFF_SIZE]; char file_url[MAX_BUFF_SIZE]; char dir_url[MAX_BUFF_SIZE]; memset(g_workgroup, '\0', MAX_BUFF_SIZE); memset(url, '\0', MAX_BUFF_SIZE); memset(file_url, '\0', MAX_BUFF_SIZE); memset(dir_url, '\0', MAX_BUFF_SIZE); memset(buff, '\0', 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])); smbc_init(auth_fn, 0); strncpy(file_url,"tempfile-",9); tmp_file_ptr = file_url; tmp_file_ptr += 9; smbc_rmdir(url); smbc_mkdir(url,0666); entry_num = atoi(argv[5]); strcat(dir_url,url); strcat(dir_url,"/"); file_name = dir_url; file_name += strlen(dir_url); for ( i = 0; i < entry_num; i++ ) { sprintf(buff,"%d",i); memcpy(tmp_file_ptr,buff,strlen(buff)+4); strncat(tmp_file_ptr,".txt",4); strcpy(file_name,file_url); fd = smbc_open(dir_url,O_RDWR | O_CREAT, 0666); smbc_close(fd); } dh = smbc_opendir(url); /* printf("directory handle: %i\n",dh); */ err = smbc_lseekdir(dh,0); /* printf("err: %i\n",err); */ if ( err < 0 ) err = 1; else err = 0; } return err; }
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; }
//=========================================================================== void SMBSlave::put( const KURL& kurl, int permissions, bool overwrite, bool resume ) { void *buf; size_t bufsize; m_current_url = kurl; int filefd; bool exists; mode_t mode; QByteArray filedata; kdDebug(KIO_SMB) << "SMBSlave::put on " << kurl << endl; exists = (cache_stat(m_current_url, &st) != -1 ); if ( exists && !overwrite && !resume) { if (S_ISDIR(st.st_mode)) { kdDebug(KIO_SMB) << "SMBSlave::put on " << kurl <<" already isdir !!"<< endl; error( KIO::ERR_DIR_ALREADY_EXIST, m_current_url.prettyURL()); } else { kdDebug(KIO_SMB) << "SMBSlave::put on " << kurl <<" already exist !!"<< endl; error( KIO::ERR_FILE_ALREADY_EXIST, m_current_url.prettyURL()); } return; } if (exists && !resume && overwrite) { kdDebug(KIO_SMB) << "SMBSlave::put exists try to remove " << m_current_url.toSmbcUrl()<< endl; // remove(m_current_url.url().local8Bit()); } if (resume) { // append if resuming kdDebug(KIO_SMB) << "SMBSlave::put resume " << m_current_url.toSmbcUrl()<< endl; filefd = smbc_open(m_current_url.toSmbcUrl(), O_RDWR, 0 ); smbc_lseek(filefd, 0, SEEK_END); } else { if (permissions != -1) { mode = permissions | S_IWUSR | S_IRUSR; } else { mode = 600;//0666; } kdDebug(KIO_SMB) << "SMBSlave::put NO resume " << m_current_url.toSmbcUrl()<< endl; filefd = smbc_open(m_current_url.toSmbcUrl(), O_CREAT | O_TRUNC | O_WRONLY, mode); } if ( filefd < 0 ) { if ( errno == EACCES ) { kdDebug(KIO_SMB) << "SMBSlave::put error " << kurl <<" access denied !!"<< endl; error( KIO::ERR_WRITE_ACCESS_DENIED, m_current_url.prettyURL()); } else { kdDebug(KIO_SMB) << "SMBSlave::put error " << kurl <<" can not open for writing !!"<< endl; error( KIO::ERR_CANNOT_OPEN_FOR_WRITING, m_current_url.prettyURL()); } finished(); return; } // Loop until we got 0 (end of data) while(1) { kdDebug(KIO_SMB) << "SMBSlave::put request data "<< endl; dataReq(); // Request for data kdDebug(KIO_SMB) << "SMBSlave::put write " << m_current_url.toSmbcUrl()<< endl; if (readData(filedata) <= 0) { kdDebug(KIO_SMB) << "readData <= 0" << endl; break; } kdDebug(KIO_SMB) << "SMBSlave::put write " << m_current_url.toSmbcUrl()<< endl; buf = filedata.data(); bufsize = filedata.size(); int size = smbc_write(filefd, buf, bufsize); if ( size < 0) { kdDebug(KIO_SMB) << "SMBSlave::put error " << kurl <<" could not write !!"<< endl; error( KIO::ERR_COULD_NOT_WRITE, m_current_url.prettyURL()); finished(); return; } kdDebug(KIO_SMB ) << "wrote " << size << endl; } kdDebug(KIO_SMB) << "SMBSlave::put close " << m_current_url.toSmbcUrl()<< endl; if(smbc_close(filefd)) { kdDebug(KIO_SMB) << "SMBSlave::put on " << kurl <<" could not write !!"<< endl; error( KIO::ERR_COULD_NOT_WRITE, m_current_url.prettyURL()); finished(); return; } // set final permissions, if the file was just created if ( permissions != -1 && !exists ) { // TODO: did the smbc_chmod fail? // TODO: put in call to chmod when it is working! // smbc_chmod(url.toSmbcUrl(),permissions); } // We have done our job => finish finished(); }
static void close_f(stream_t *s){ struct priv *p = s->priv; smbc_close(p->fd); }
//=========================================================================== 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 void close_f(stream_t *s){ smbc_close(s->fd); }
int main(int argc, char** argv) { int err = -1; int fd = 0; unsigned int i = 0; int msg_len = 0; char url[MAX_BUFF_SIZE]; char* message; memset(g_workgroup, '\0', MAX_BUFF_SIZE); memset(url, '\0', MAX_BUFF_SIZE); memset(g_print_user, '\0', MAX_BUFF_SIZE); memset(g_print_name, '\0', MAX_BUFF_SIZE); g_print_id = 0; g_print_priority = 0; g_print_size = 0; print_id_count = 0; if ( argc == 7 ) { 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); message[msg_len - 1] = 0; strncpy(message,argv[5],msg_len); /* printf("Message: %s\n",message); */ /* printf("Message len: %i\n",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); free(message); smbc_print_file(url,argv[6]); smbc_print_file(url,argv[6]); smbc_print_file(url,argv[6]); smbc_list_print_jobs(argv[6],print_list_fn); if ( smbc_unlink_print_job(argv[6],g_print_id) == 0 ) { if ( smbc_list_print_jobs(argv[6],print_list_fn_2) == 0 ) { err = 0; for ( i=0; i<print_id_count; i++ ) { if ( g_print_id == print_ids[i] ) { err = 1; break; } } } } else err = 1; } return err; }