Ensure all callers to the rpc_client/cli_pipe functions correctly
[kamenim/samba.git] / source3 / utils / smbtree.c
index 26db71766874682b2112707571b10ca339d481eb..717ce650068d0e1737e302432a35da8d6df1afb3 100644 (file)
@@ -1,13 +1,13 @@
 /* 
-   Unix SMB/Netbios implementation.
+   Unix SMB/CIFS implementation.
    Network neighbourhood browser.
-   Version 3.0
    
    Copyright (C) Tim Potter      2000
+   Copyright (C) Jelmer Vernooij 2003
    
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
-   the Free Software Foundation; either version 2 of the License, or
+   the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    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., 675 Mass Ave, Cambridge, MA 02139, USA.
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
 
 #include "includes.h"
 
-struct user_auth_info {
-       pstring username;
-       pstring password;
-       pstring workgroup;
-};
+static int use_bcast;
 
 /* How low can we go? */
 
 enum tree_level {LEV_WORKGROUP, LEV_SERVER, LEV_SHARE};
-enum tree_level level = LEV_SHARE;
-
-static void usage(void)
-{
-       printf(
-"Usage: smbtree [options]\n\
-\n\
-\t-d debuglevel           set debug output level\n\
-\t-U username             user to autheticate as\n\
-\t-W workgroup            workgroup of user to authenticate as\n\
-\t-D                      list only domains (workgroups) of tree\n\
-\t-S                      list domains and servers of tree\n\
-\n\
-The username can be of the form username%%password or\n\
-workgroup\\username%%password.\n\n\
-");
-}
+static enum tree_level level = LEV_SHARE;
 
 /* Holds a list of workgroups or servers */
 
-struct name_list {
-        struct name_list *prev, *next;
-        pstring name, comment;
+struct smb_name_list {
+        struct smb_name_list *prev, *next;
+        char *name, *comment;
         uint32 server_type;
 };
 
-static struct name_list *workgroups, *servers, *shares;
+static struct smb_name_list *workgroups, *servers, *shares;
 
-static void free_name_list(struct name_list *list)
+static void free_name_list(struct smb_name_list *list)
 {
         while(list)
                 DLIST_REMOVE(list, list);
@@ -68,163 +47,69 @@ static void free_name_list(struct name_list *list)
 static void add_name(const char *machine_name, uint32 server_type,
                      const char *comment, void *state)
 {
-        struct name_list **name_list = (struct name_list **)state;
-        struct name_list *new_name;
+        struct smb_name_list **name_list = (struct smb_name_list **)state;
+        struct smb_name_list *new_name;
 
-        new_name = (struct name_list *)malloc(sizeof(struct name_list));
+        new_name = SMB_MALLOC_P(struct smb_name_list);
 
         if (!new_name)
                 return;
 
         ZERO_STRUCTP(new_name);
 
-        pstrcpy(new_name->name, machine_name);
-        pstrcpy(new_name->comment, comment);
+       new_name->name = SMB_STRDUP(machine_name);
+       new_name->comment = SMB_STRDUP(comment);
         new_name->server_type = server_type;
 
-        DLIST_ADD(*name_list, new_name);
-}
-
-/* Return a cli_state pointing at the IPC$ share for the given workgroup */
-
-static struct cli_state *get_ipc_connect(char *server,
-                                         struct user_auth_info *user_info)
-{
-        struct nmb_name calling, called;
-        extern struct in_addr ipzero;
-        struct in_addr server_ip = ipzero;
-        struct cli_state *cli;
-        pstring myname;
-
-        get_myname(myname);
-
-        make_nmb_name(&called, myname, 0x0);
-        make_nmb_name(&calling, server, 0x20);
-
-        if (is_ipaddress(server))
-                if (!resolve_name(server, &server_ip, 0x20))
-                        return False;
-                
- again:
-       if (!(cli = cli_initialise(NULL))) {
-                DEBUG(4, ("Unable to initialise cli structure\n"));
-                goto error;
-        }
-
-        if (!cli_connect(cli, server, &server_ip)) {
-                DEBUG(4, ("Unable to connect to %s\n", server));
-                goto error;
-        }
-
-        if (!cli_session_request(cli, &calling, &called)) {
-                cli_shutdown(cli);
-                if (!strequal(called.name, "*SMBSERVER")) {
-                        make_nmb_name(&called , "*SMBSERVER", 0x20);
-                        goto again;
-                }
-                DEBUG(4, ("Session request failed to %s\n", called.name));
-                goto error;
-       }
-
-        if (!cli_negprot(cli)) {
-                DEBUG(4, ("Negprot failed\n"));
-                goto error;
-       }
-
-       if (!cli_session_setup(cli, user_info->username, user_info->password, 
-                               strlen(user_info->password),
-                              user_info->password, 
-                               strlen(user_info->password), server) &&
-           /* try an anonymous login if it failed */
-           !cli_session_setup(cli, "", "", 1,"", 0, server)) {
-                DEBUG(4, ("Session setup failed\n"));
-                goto error;
-       }
-
-       DEBUG(4,(" session setup ok\n"));
-
-       if (!cli_send_tconX(cli, "IPC$", "?????",
-                           user_info->password, 
-                            strlen(user_info->password)+1)) {
-                DEBUG(4, ("Tconx failed\n"));
-                goto error;
+       if (!new_name->name || !new_name->comment) {
+               SAFE_FREE(new_name->name);
+               SAFE_FREE(new_name->comment);
+               SAFE_FREE(new_name);
+               return;
        }
 
-        return cli;
-
-        /* Clean up after error */
-
- error:
-        if (cli && cli->initialised)
-                cli_shutdown(cli);
-
-        free(cli);
-        return NULL;
-}
-
-/* Return the IP address and workgroup of a master browser on the 
-   network. */
-
-static BOOL find_master_ip_bcast(pstring workgroup, struct in_addr *server_ip)
-{
-       struct in_addr *ip_list;
-       int i, count;
-
-        /* Go looking for workgroups by broadcasting on the local network */ 
-
-        if (!name_resolve_bcast(MSBROWSE, 1, &ip_list, &count)) {
-                return False;
-        }
-
-       for (i = 0; i < count; i++) {
-               static fstring name;
-
-               if (!name_status_find(0x1d, ip_list[i], name))
-                        return False;
-
-                if (!find_master_ip(name, server_ip))
-                        return False;
-
-                pstrcpy(workgroup, name);
-
-                DEBUG(4, ("found master browser %s, %s\n", 
-                          name, inet_ntoa(ip_list[i])));
-
-                return True;
-       }
-
-       return False;
+        DLIST_ADD(*name_list, new_name);
 }
 
 /****************************************************************************
   display tree of smb workgroups, servers and shares
 ****************************************************************************/
-static BOOL get_workgroups(struct user_auth_info *user_info)
+static bool get_workgroups(struct user_auth_info *user_info)
 {
         struct cli_state *cli;
-        struct in_addr server_ip;
-       pstring master_workgroup;
+        struct sockaddr_storage server_ss;
+       TALLOC_CTX *ctx = talloc_tos();
+       char *master_workgroup = NULL;
 
         /* Try to connect to a #1d name of our current workgroup.  If that
            doesn't work broadcast for a master browser and then jump off
            that workgroup. */
 
-       pstrcpy(master_workgroup, lp_workgroup());
+       master_workgroup = talloc_strdup(ctx, lp_workgroup());
+       if (!master_workgroup) {
+               return false;
+       }
 
-        if (!find_master_ip(lp_workgroup(), &server_ip)) {
-                DEBUG(4, ("Unable to find master browser for workgroup %s\n", 
+        if (!use_bcast && !find_master_ip(lp_workgroup(), &server_ss)) {
+                DEBUG(4, ("Unable to find master browser for workgroup %s, falling back to broadcast\n", 
                          master_workgroup));
-               if (!find_master_ip_bcast(master_workgroup, &server_ip)) {
+                               use_bcast = True;
+               } else if(!use_bcast) {
+                       char addr[INET6_ADDRSTRLEN];
+                       print_sockaddr(addr, sizeof(addr), &server_ss);
+                       if (!(cli = get_ipc_connect(addr, &server_ss, user_info)))
+                               return False;
+               }
+
+               if (!(cli = get_ipc_connect_master_ip_bcast(talloc_tos(),
+                                                       user_info,
+                                                       &master_workgroup))) {
                        DEBUG(4, ("Unable to find master browser by "
                                  "broadcast\n"));
                        return False;
-               }
         }
 
-        if (!(cli = get_ipc_connect(inet_ntoa(server_ip), user_info)))
-                return False;
-
-        if (!cli_NetServerEnum(cli, master_workgroup, 
+        if (!cli_NetServerEnum(cli, master_workgroup,
                                SV_TYPE_DOMAIN_ENUM, add_name, &workgroups))
                 return False;
 
@@ -233,45 +118,111 @@ static BOOL get_workgroups(struct user_auth_info *user_info)
 
 /* Retrieve the list of servers for a given workgroup */
 
-static BOOL get_servers(char *workgroup, struct user_auth_info *user_info)
+static bool get_servers(char *workgroup, struct user_auth_info *user_info)
 {
         struct cli_state *cli;
-        struct in_addr server_ip;
+        struct sockaddr_storage server_ss;
+       char addr[INET6_ADDRSTRLEN];
 
         /* Open an IPC$ connection to the master browser for the workgroup */
 
-        if (!find_master_ip(workgroup, &server_ip)) {
+        if (!find_master_ip(workgroup, &server_ss)) {
                 DEBUG(4, ("Cannot find master browser for workgroup %s\n",
                           workgroup));
                 return False;
         }
 
-        if (!(cli = get_ipc_connect(inet_ntoa(server_ip), user_info)))
+       print_sockaddr(addr, sizeof(addr), &server_ss);
+        if (!(cli = get_ipc_connect(addr, &server_ss, user_info)))
                 return False;
 
-        if (!cli_NetServerEnum(cli, workgroup, SV_TYPE_ALL, add_name, 
+        if (!cli_NetServerEnum(cli, workgroup, SV_TYPE_ALL, add_name,
                                &servers))
                 return False;
 
         return True;
 }
 
-static BOOL get_shares(char *server_name, struct user_auth_info *user_info)
+static bool get_rpc_shares(struct cli_state *cli,
+                          void (*fn)(const char *, uint32, const char *, void *),
+                          void *state)
+{
+       NTSTATUS status;
+       struct rpc_pipe_client *pipe_hnd = NULL;
+       TALLOC_CTX *mem_ctx;
+       WERROR werr;
+       struct srvsvc_NetShareInfoCtr info_ctr;
+       struct srvsvc_NetShareCtr1 ctr1;
+       int i;
+       uint32_t resume_handle = 0;
+       uint32_t total_entries = 0;
+
+       mem_ctx = talloc_new(NULL);
+       if (mem_ctx == NULL) {
+               DEBUG(0, ("talloc_new failed\n"));
+               return False;
+       }
+
+       status = cli_rpc_pipe_open_noauth(cli, &ndr_table_srvsvc.syntax_id,
+                                         &pipe_hnd);
+
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(10, ("Could not connect to srvsvc pipe: %s\n",
+                          nt_errstr(status)));
+               TALLOC_FREE(mem_ctx);
+               return False;
+       }
+
+       ZERO_STRUCT(info_ctr);
+       ZERO_STRUCT(ctr1);
+
+       info_ctr.level = 1;
+       info_ctr.ctr.ctr1 = &ctr1;
+
+       status = rpccli_srvsvc_NetShareEnumAll(pipe_hnd, mem_ctx,
+                                              pipe_hnd->desthost,
+                                              &info_ctr,
+                                              0xffffffff,
+                                              &total_entries,
+                                              &resume_handle,
+                                              &werr);
+
+       if (!NT_STATUS_IS_OK(status) || !W_ERROR_IS_OK(werr)) {
+               TALLOC_FREE(mem_ctx);
+               TALLOC_FREE(pipe_hnd);
+               return False;
+       }
+
+       for (i=0; i<total_entries; i++) {
+               struct srvsvc_NetShareInfo1 info = info_ctr.ctr.ctr1->array[i];
+               fn(info.name, info.type, info.comment, state);
+       }
+
+       TALLOC_FREE(mem_ctx);
+       TALLOC_FREE(pipe_hnd);
+       return True;
+}
+
+
+static bool get_shares(char *server_name, struct user_auth_info *user_info)
 {
         struct cli_state *cli;
 
-        if (!(cli = get_ipc_connect(server_name, user_info)))
+        if (!(cli = get_ipc_connect(server_name, NULL, user_info)))
                 return False;
 
+       if (get_rpc_shares(cli, add_name, &shares))
+               return True;
+
         if (!cli_RNetShareEnum(cli, add_name, &shares))
                 return False;
 
         return True;
 }
 
-static BOOL print_tree(struct user_auth_info *user_info)
+static bool print_tree(struct user_auth_info *user_info)
 {
-        struct name_list *wg, *sv, *sh;
+        struct smb_name_list *wg, *sv, *sh;
 
         /* List workgroups */
 
@@ -293,7 +244,8 @@ static BOOL print_tree(struct user_auth_info *user_info)
 
                 for (sv = servers; sv; sv = sv->next) {
 
-                        printf("\t%s\n", sv->name);
+                        printf("\t\\\\%-15s\t\t%s\n", 
+                              sv->name, sv->comment);
 
                         /* List shares */
 
@@ -305,7 +257,8 @@ static BOOL print_tree(struct user_auth_info *user_info)
                                 continue;
 
                         for (sh = shares; sh; sh = sh->next) {
-                                printf("\t\t%s\n", sh->name);
+                                printf("\t\t\\\\%s\\%-15s\t%s\n", 
+                                      sv->name, sh->name, sh->comment);
                         }
                 }
         }
@@ -318,102 +271,59 @@ static BOOL print_tree(struct user_auth_info *user_info)
 ****************************************************************************/
  int main(int argc,char *argv[])
 {
-       extern char *optarg;
-       extern int optind;
-       extern FILE *dbf;
-       int opt;
-       char *p;
-       pstring servicesf = CONFIGFILE;
-       struct user_auth_info user_info;
-       BOOL got_pass = False;
+       TALLOC_CTX *frame = talloc_stackframe();
+       struct user_auth_info *auth_info;
+       struct poptOption long_options[] = {
+               POPT_AUTOHELP
+               { "broadcast", 'b', POPT_ARG_VAL, &use_bcast, True, "Use broadcast instead of using the master browser" },
+               { "domains", 'D', POPT_ARG_VAL, &level, LEV_WORKGROUP, "List only domains (workgroups) of tree" },
+               { "servers", 'S', POPT_ARG_VAL, &level, LEV_SERVER, "List domains(workgroups) and servers of tree" },
+               POPT_COMMON_SAMBA
+               POPT_COMMON_CREDENTIALS
+               POPT_TABLEEND
+       };
+       poptContext pc;
 
        /* Initialise samba stuff */
+       load_case_tables();
 
        setlinebuf(stdout);
 
-       dbf = stderr;
+       dbf = x_stderr;
 
        setup_logging(argv[0],True);
 
-       TimeInit();
-
-       lp_load(servicesf,True,False,False);
-       load_interfaces();
-
-       if (getenv("USER")) {
-               pstrcpy(user_info.username, getenv("USER"));
-
-               if ((p=strchr(user_info.username, '%'))) {
-                       *p = 0;
-                       pstrcpy(user_info.password, p+1);
-                       got_pass = True;
-                       memset(strchr(getenv("USER"), '%') + 1, 'X',
-                              strlen(user_info.password));
-               }
+       auth_info = user_auth_info_init(frame);
+       if (auth_info == NULL) {
+               exit(1);
        }
+       popt_common_set_auth_info(auth_info);
 
-        pstrcpy(user_info.workgroup, lp_workgroup());
+       pc = poptGetContext("smbtree", argc, (const char **)argv, long_options,
+                                               POPT_CONTEXT_KEEP_FIRST);
+       while(poptGetNextOpt(pc) != -1);
+       poptFreeContext(pc);
 
-       /* Parse command line args */
+       lp_load(get_dyn_CONFIGFILE(),True,False,False,True);
+       load_interfaces();
 
-       while ((opt = getopt(argc, argv, "U:hd:W:DS")) != EOF) {
-               switch (opt) {
-               case 'U':
-                       pstrcpy(user_info.username,optarg);
-                       p = strchr(user_info.username,'%');
-                       if (p) {
-                               *p = 0;
-                               pstrcpy(user_info.password, p+1);
-                               got_pass = 1;
-                       }
-                       break;
-
-               case 'h':
-                       usage();
-                       exit(1);
-
-               case 'd':
-                       DEBUGLEVEL = atoi(optarg);
-                       break;
-
-               case 'W':
-                       pstrcpy(user_info.workgroup, optarg);
-                       break;
-
-                case 'D':
-                        level = LEV_WORKGROUP;
-                        break;
-
-                case 'S':
-                        level = LEV_SERVER;
-                        break;
-
-               default:
-                       printf("Unknown option %c (%d)\n", (char)opt, opt);
-                       exit(1);
-               }
-       }
+       /* Parse command line args */
 
-       argc -= optind;
-       argv += optind;
-       
-       if (argc > 0) {
-               usage();
-               exit(1);
+       if (get_cmdline_auth_info_use_machine_account(auth_info) &&
+           !set_cmdline_auth_info_machine_account_creds(auth_info)) {
+               TALLOC_FREE(frame);
+               return 1;
        }
 
-       if (!got_pass) {
-               char *pass = getpass("Password: ");
-               if (pass) {
-                       pstrcpy(user_info.password, pass);
-               }
-                got_pass = True;
-       }
+       set_cmdline_auth_info_getpass(auth_info);
 
        /* Now do our stuff */
 
-        if (!print_tree(&user_info))
+        if (!print_tree(auth_info)) {
+               TALLOC_FREE(frame);
                 return 1;
+       }
 
+       TALLOC_FREE(frame);
        return 0;
 }