跳至主要内容

【转】smb协议栈使用示例

/*
 * * uncdownload.c
 * *
 * * Utility for downloading files from SMB shares using libsmbclient
 * *
 * * Copyright(C) 2006 Sophos Plc, Oxford, England.
 * *
 * * This program is free software; you can redistribute it and/or modify it under the terms of the
 * * GNU General Public License Version 2 as published by the Free Software Foundation.
 * *
 * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
 * * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * * See the GNU General Public License for more details.
 * *
 * * You should have received a copy of the GNU General Public License along with this program; if not,
 * * write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 * *
 * */


#include <sys/types.h>
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <strings.h>

#include <libsmbclient.h>

/*
 * *
 * */

static const char *def_workgroup = "WORKGROUP";

/*
 * * Global variables holding parsed command line options
 * */

static char *opt_workgroup;
static char *opt_username;
static char *opt_password;
static int opt_stdinpwd;
static int opt_stdoutdata = 1;
static char *opt_outfile;
static int opt_outfd;
static char *opt_downloadurl;

/*
 * * Parse command line options
 * */

static int parseopts(int argc, char *argv[])
{
    int arg;
    char *nonoption = NULL;
    char option = 0;
    int param = 0;

    for ( arg = 1; arg < argc; arg++ ) {
        if ( param ) {
            /* Previous arg was an option */
            param = 0;
            switch ( option ) {
                case 'w':
                    opt_workgroup = argv[arg];
                    break;
                case 'u':
                    opt_username = argv[arg];
                    break;
                case 'p':
                    opt_password = argv[arg];
                    if ( !strcmp(opt_password, "-") )
                        opt_stdinpwd = 1;
                    break;
                case 'o':
                    opt_outfile = argv[arg];
                    opt_stdoutdata = 0;
                    break;
                case 'd':
                    opt_outfd = atoi(argv[arg]);
                    opt_stdoutdata = 0;
                    break;
            }
        } else {
            /* Look for an option */
            if ( argv[arg][0] == '-' ) {
                option = argv[arg][1];
                switch ( option ) {
                    case 'w':
                    case 'u':
                    case 'p':
                    case 'o':
                    case 'd':
                        param = 1;
                        break;
                    default:
                        fprintf(stderr, "Unknown option: %c\n", option);
                }
            /* If not an option, store as a non-option argument */
            } else {
                if ( nonoption )
                    fprintf(stderr, "Only first non-option argument considered as download URL!");
                else
                    nonoption = argv[arg];
            }
        }
    }

    if ( param ) {
        fprintf(stderr, "No argument for -%c!\n", option);
        return -1;
    }

    if ( !nonoption ) {
        fprintf(stderr, "No UNC path given!\n");
        return -1;
    }

    opt_downloadurl = nonoption;

    return 0;
}

/*
 * * libsmbclient callback function
 * */

static void get_auth_data_fn(const char *pServer, const char *pShare, char *pWorkgroup, int maxLenWorkgroup, char *pUsername, int maxLenUsername, char *pPassword, int maxLenPassword )
{
    (void)pServer;
    (void)pShare;


    if ( opt_workgroup && opt_workgroup[0] != '\0' )
        strncpy(pWorkgroup, opt_workgroup, maxLenWorkgroup - 1);

    if ( opt_username && opt_username[0] != '\0' )
        strncpy(pUsername, opt_username, maxLenUsername - 1);

    if ( opt_password && opt_password[0] != '\0' )
        strncpy(pPassword, opt_password, maxLenPassword - 1);
}

/*
 * * Convert backslashes to slashes
 * */

static char *bstos(char *str)
{
    char *p = str;

    while ( *p ) {
        if ( *p == '\\' )
            *p = '/';
        p++;
    }

    return str;
}

/*
 * * Creates a nice file URL which libsmbclient understands
 * */

static char *mkurl(char *uncpath)
{
    unsigned int len = strlen(uncpath) + 1;
    char *url;
    int prepend = 0;

    if ( strncasecmp(uncpath, "smb:", 4) ) {
        len += 4;
        prepend = 1;
    }

    if ( !(url = malloc(len)) )
        return NULL;
    else
        *url = 0; /* So that strcat below is safe if not prepending */

    if ( prepend )
        strcpy(url, "smb:");

    strcat(url, uncpath);

    return bstos(url);
}

/*
 * * Null-terminate string on first newline
 * */

static char *ntonl(char *str)
{
    char *p = str;

    while ( *p ) {
        if ( *p == '\n' ) {
            *p = 0;
            break;
        }
        p++;
    }

    return str;
}

/*
 * @return codes:
 * 0 success
 * 1 failed to parse arguments
 * 2 failed mkurl
 * 3 failed to read password
 * 4 failed to open output file
 * 5 failed to open remote file (not permission or existence)
 * 6 failed reading or writing
 * 7 bad authentication
 * 8 no such file
 * 9 invalid argument from smbc_open - may mean missing directory component
 * */

int main(int argc, char * argv[])
{
    char *smbpath;
    char pwdbuf[128];
    int outfd;
    int smbdebug = 0;
    int smbfd;
    int ret;
    char buffer[2048];

    if ( parseopts(argc, argv) ) {
        fprintf(stderr,
"Usage:\n\
\t%s [OPTIONS] DOWNLOAD-URL\n\
Options:\n\
\t-w\tworkgroup (default: %s)\n\
\t-u\tusername\n\
\t-p\tpassword (if - then read from stdin)\n\
\t-o\toutput (if omitted then written to stdout)\n\
\t-d\tdescriptor (if omitted then written to stdout, overrides output file)\n"
,
             argv[0], def_workgroup);
        return 1;
    }

    if ( !(smbpath = mkurl(opt_downloadurl)) ) {
        fprintf(stderr, "Failed to create SMB URL!\n");
        return 2;
    }

    if ( opt_stdinpwd ) {
        if ( !fgets(pwdbuf, sizeof(pwdbuf), stdin) ) {
            fprintf(stderr, "Failed to read password from stdin!\n");
            return 3;
        }
        opt_password = ntonl(pwdbuf);
    }

    if ( opt_outfd ) {
        outfd = opt_outfd;
    } else if ( !opt_stdoutdata ) {
        if ( (outfd = open(opt_outfile, O_WRONLY | O_CREAT | O_TRUNC)) <= 0 ) {
            fprintf(stderr, "Failed to open output file! - %s\n", strerror(errno));
            return 4;
        }
    } else {
        outfd = STDOUT_FILENO;
    }

    smbc_init(get_auth_data_fn, smbdebug);

    if ( (smbfd = smbc_open(smbpath, O_RDONLY, 0)) < 0 ) {
        fprintf(stderr, "Failed to open remote location! - %s(%d)\n", strerror(errno),errno);
        switch(errno)
        {
            case EACCES:
                return 7; /* Bad permissions */
            case ENOENT: /* No such file or directory */
            case EISDIR: /* Is a directory */
            case ENODEV: /* No such share */
            case ENOTDIR: /* Perhaps a directory in the path is in fact a file? */
                return 8; /* Implies: No such file */
            case EINVAL: /* May mean a directory in the path doesn't exist */
                return 9; /* Implies: No such file */
        }
        /* default */
        return 5;
    }

    /* Main loop */
    do {
        ret = smbc_read(smbfd, buffer, sizeof(buffer));
        if ( ret > 0 ) {
            ret = write(outfd, buffer, ret);
            if ( ret < 0 )
                break;
        }
    } while ( ret > 0 );

    if ( ret < 0 ) {
        fprintf(stderr, "Error reading or writting! - %s\n", strerror(errno));
        return 6;
    }

    smbc_close(smbfd);
    free(smbpath); /* Allocated with mkurl */

    return 0;
}


评论

此博客中的热门博文

【转】AMBA、AHB、APB总线简介

AMBA 简介 随着深亚微米工艺技术日益成熟,集成电路芯片的规模越来越大。数字IC从基于时序驱动的设计方法,发展到基于IP复用的设计方法,并在SOC设计中得到了广泛应用。在基于IP复用的SoC设计中,片上总线设计是最关键的问题。为此,业界出现了很多片上总线标准。其中,由ARM公司推出的AMBA片上总线受到了广大IP开发商和SoC系统集成者的青睐,已成为一种流行的工业标准片上结构。AMBA规范主要包括了AHB(Advanced High performance Bus)系统总线和APB(Advanced Peripheral Bus)外围总线。   AMBA 片上总线        AMBA 2.0 规范包括四个部分:AHB、ASB、APB和Test Methodology。AHB的相互连接采用了传统的带有主模块和从模块的共享总线,接口与互连功能分离,这对芯片上模块之间的互连具有重要意义。AMBA已不仅是一种总线,更是一种带有接口模块的互连体系。下面将简要介绍比较重要的AHB和APB总线。 基于 AMBA 的片上系统        一个典型的基于AMBA总线的系统框图如图3所示。        大多数挂在总线上的模块(包括处理器)只是单一属性的功能模块:主模块或者从模块。主模块是向从模块发出读写操作的模块,如CPU,DSP等;从模块是接受命令并做出反应的模块,如片上的RAM,AHB/APB 桥等。另外,还有一些模块同时具有两种属性,例如直接存储器存取(DMA)在被编程时是从模块,但在系统读传输数据时必须是主模块。如果总线上存在多个主模块,就需要仲裁器来决定如何控制各种主模块对总线的访问。虽然仲裁规范是AMBA总线规范中的一部分,但具体使用的算法由RTL设计工程师决定,其中两个最常用的算法是固定优先级算法和循环制算法。AHB总线上最多可以有16个主模块和任意多个从模块,如果主模块数目大于16,则需再加一层结构(具体参阅ARM公司推出的Multi-layer AHB规范)。APB 桥既是APB总线上唯一的主模块,也是AHB系统总线上的从模块。其主要功能是锁存来自AHB系统总...

【转】VxWorks套接口

int m_socket;   // Open a socket        m_socket = socket(AF_INET, SOCK_STREAM, 0);   第一个参数 domain 说明我们网络程序所在的主机采用的通讯协族 (AF_UNIX 和 AF_INET 等 ). AF_UNIX 只能够用于单一的 Unix 系统进程间通信 , 而 AF_INET 是针对 Internet 的 , 因而可以允许在远程主机之间通信 . VxWorks 套接字仅支持 Internet 域地址族 , 不支持 UNIX 域地址族 . 因此在需要 domain 参数的函数中 , 使用 AF_INET 作为函数参数值 . 第二个参数 type 说明我们网络程序所采用的通讯协议 ( SOCK_STREAM , SOCK_DGRAM 等 ). SOCK_STREAM 表明我们用的是 TCP 协议 , 这样会提供按顺序的 , 可靠 , 双向 , 面向连接的比特流 . SOCK_DGRAM  表明我们用的是 UDP 协议 , 这样只会提供定长的 , 不可靠 , 无连接的通信 . 此外,还有 SOCK_RAW 代表是原始协议套接字 . 第三个参数 protocol, 由于我们指定了 type, 所以这个地方我们一般只要用 0 来代替就可以了 . socket 为网络通讯做基本的准备 , 成功打开则返回一个套接字描述符 , 如果失败则返回 ERROR. 套接字描述符是一个标准的 I/O 系统文件描述符 (fd, file descriptor), 可以被 close(), read(), write() 和 ioctl() 函数使用 .   // Make the socket sending alive messages when connected int flag = 1; setsockopt(m_socket, SOL_SOCKET, SO_KEEPALIVE, (char*)&flag, sizeof(flag));   // increase receive buffer siz...

【转】C++/CLI程序进程之间的通讯

 现在,把大型软件项目分解为一些相交互的小程序似乎变得越来越普遍,程序各部分之间的通讯可使用某种类型的通讯协议,这些程序可能运行在不同的机器上、不同的操作系统中、以不同的语言编写,但也有可能只在同一台机器上,实际上,这些程序可看成是同一程序中的不同线程。而本文主要讨论C++/CLI程序间的通讯,当然,在此是讨论进程间通讯,而不是网络通讯。    简介   试想一个包含数据库查询功能的应用,通常有一个被称为服务端的程序,等待另一个被称为客户端程序发送请求,当接收到请求时,服务端执行相应功能,并把结果(或者错误信息)返回给客户端。在许多情况中,有着多个客户端,所有的请求都会在同一时间发送到同一服务端,这就要求服务端程序要更加高级、完善。   在某些针对此任务的环境中,服务端程序可能只是众多程序中的一个程序,其他可能也是服务端或者客户端程序,实际上,如果我们的数据库服务端需要访问不存在于本机的文件,那么它就可能成为其他某个文件服务器的一个客户端。一个程序中可能会有一个服务线程及一个或多个客户线程,因此,我们需小心使用客户端及服务端这个术语,虽然它们表达了近似的抽象含义,但在具体实现上却大不相同。从一般的观点来看,客户端即为服务端所提供服务的"消费者",而服务端也能成为其他某些服务的客户端。    服务端套接字   让我们从一个具体有代表性的服务端程序开始(请看例1),此程序等待客户端发送一对整数,把它们相加之后返回结果给客户端。   例1: using namespace System; using namespace System::IO; using namespace System::Net; using namespace System::Net::Sockets; int main(array<String^>^ argv) { if (argv->Length != 1) { Console::WriteLine("Usage: Server port"); Environment::Exit(1); } int port = 0; try { port = Int32::Parse(argv[0]); } catch (FormatException^ e) { Console::Wri...