r16298: On request of jiri sasek - Sun Microsystems - Prague Czech Republic <Jiri...
[nivanova/samba-autobuild/.git] / source3 / utils / net_usershare.c
1 /* 
2    Samba Unix/Linux SMB client library 
3    Distributed SMB/CIFS Server Management Utility 
4
5    Copyright (C) Jeremy Allison (jra@samba.org) 2005
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
20
21 #include "includes.h"
22 #include "utils/net.h"
23
24 struct {
25         const char *us_errstr;
26         enum usershare_err us_err;
27 } us_errs [] = {
28         {"",USERSHARE_OK},
29         {"Malformed usershare file", USERSHARE_MALFORMED_FILE},
30         {"Bad version number", USERSHARE_BAD_VERSION},
31         {"Malformed path entry", USERSHARE_MALFORMED_PATH},
32         {"Malformed comment entryfile", USERSHARE_MALFORMED_COMMENT_DEF},
33         {"Malformed acl definition", USERSHARE_MALFORMED_ACL_DEF},
34         {"Acl parse error", USERSHARE_ACL_ERR},
35         {"Path not absolute", USERSHARE_PATH_NOT_ABSOLUTE},
36         {"Path is denied", USERSHARE_PATH_IS_DENIED},
37         {"Path not allowed", USERSHARE_PATH_NOT_ALLOWED},
38         {"Path is not a directory", USERSHARE_PATH_NOT_DIRECTORY},
39         {"System error", USERSHARE_POSIX_ERR},
40         {NULL,(enum usershare_err)-1}
41 };
42
43 static const char *get_us_error_code(enum usershare_err us_err)
44 {
45         static pstring out;
46         int idx = 0;
47
48         while (us_errs[idx].us_errstr != NULL) {
49                 if (us_errs[idx].us_err == us_err) {
50                         return us_errs[idx].us_errstr;
51                 }
52                 idx++;
53         }
54
55         slprintf(out, sizeof(out), "Usershare error code (0x%x)", (unsigned int)us_err);
56         return out;
57 }
58
59 /* The help subsystem for the USERSHARE subcommand */
60
61 static int net_usershare_add_usage(int argc, const char **argv)
62 {
63         char c = *lp_winbind_separator();
64         d_printf(
65                 "net usershare add [-l|--long] <sharename> <path> [<comment>] [<acl>] [<guest_ok=[y|n]>]\n"
66                 "\tAdds the specified share name for this user.\n"
67                 "\t<sharename> is the new share name.\n"
68                 "\t<path> is the path on the filesystem to export.\n"
69                 "\t<comment> is the optional comment for the new share.\n"
70                 "\t<acl> is an optional share acl in the format \"DOMAIN%cname:X,DOMAIN%cname:X,....\"\n"
71                 "\t<guest_ok=y> if present sets \"guest ok = yes\" on this usershare.\n"
72                 "\t\t\"X\" represents a permission and can be any one of the characters f, r or d\n"
73                 "\t\twhere \"f\" means full control, \"r\" means read-only, \"d\" means deny access.\n"
74                 "\t\tname may be a domain user or group. For local users use the local server name "
75                 "instead of \"DOMAIN\"\n"
76                 "\t\tThe default acl is \"Everyone:r\" which allows everyone read-only access.\n"
77                 "\tAdd -l or --long to print the info on the newly added share.\n",
78                 c, c );
79         return -1;
80 }
81
82 static int net_usershare_delete_usage(int argc, const char **argv)
83 {
84         d_printf(
85                 "net usershare delete <sharename>\n"\
86                 "\tdeletes the specified share name for this user.\n");
87         return -1;
88 }
89
90 static int net_usershare_info_usage(int argc, const char **argv)
91 {
92         d_printf(
93                 "net usershare info [-l|--long] [wildcard sharename]\n"\
94                 "\tPrints out the path, comment and acl elements of shares that match the wildcard.\n"
95                 "\tBy default only gives info on shares owned by the current user\n"
96                 "\tAdd -l or --long to apply this to all shares\n"
97                 "\tOmit the sharename or use a wildcard of '*' to see all shares\n");
98         return -1;
99 }
100
101 static int net_usershare_list_usage(int argc, const char **argv)
102 {
103         d_printf(
104                 "net usershare list [-l|--long] [wildcard sharename]\n"\
105                 "\tLists the names of all shares that match the wildcard.\n"
106                 "\tBy default only lists shares owned by the current user\n"
107                 "\tAdd -l or --long to apply this to all shares\n"
108                 "\tOmit the sharename or use a wildcard of '*' to see all shares\n");
109         return -1;
110 }
111
112 int net_usershare_usage(int argc, const char **argv)
113 {
114         d_printf("net usershare add <sharename> <path> [<comment>] [<acl>] [<guest_ok=[y|n]>] to "
115                                 "add or change a user defined share.\n"
116                 "net usershare delete <sharename> to delete a user defined share.\n"
117                 "net usershare info [-l|--long] [wildcard sharename] to print info about a user defined share.\n"
118                 "net usershare list [-l|--long] [wildcard sharename] to list user defined shares.\n"
119                 "net usershare help\n"\
120                 "\nType \"net usershare help <option>\" to get more information on that option\n\n");
121
122         net_common_flags_usage(argc, argv);
123         return -1;
124 }
125
126 /***************************************************************************
127 ***************************************************************************/
128
129 static void get_basepath(pstring basepath)
130 {
131         pstrcpy(basepath, lp_usershare_path());
132         if ((basepath[0] != '\0') && (basepath[strlen(basepath)-1] == '/')) {
133                 basepath[strlen(basepath)-1] = '\0';
134         }
135 }
136
137 /***************************************************************************
138  Delete a single userlevel share.
139 ***************************************************************************/
140
141 static int net_usershare_delete(int argc, const char **argv)
142 {
143         pstring us_path;
144         char *sharename;
145
146         if (argc != 1) {
147                 return net_usershare_delete_usage(argc, argv);
148         }
149
150         sharename = strdup_lower(argv[0]);
151
152         if (!validate_net_name(sharename, INVALID_SHARENAME_CHARS, strlen(sharename))) {
153                 d_fprintf(stderr, "net usershare delete: share name %s contains "
154                         "invalid characters (any of %s)\n",
155                         sharename, INVALID_SHARENAME_CHARS);
156                 SAFE_FREE(sharename);
157                 return -1;
158         }
159
160         pstrcpy(us_path, lp_usershare_path());
161         pstrcat(us_path, "/");
162         pstrcat(us_path, sharename);
163
164         if (unlink(us_path) != 0) {
165                 d_fprintf(stderr, "net usershare delete: unable to remove usershare %s. "
166                         "Error was %s\n",
167                         us_path, strerror(errno));
168                 SAFE_FREE(sharename);
169                 return -1;
170         }
171         SAFE_FREE(sharename);
172         return 0;
173 }
174
175 /***************************************************************************
176  Data structures to handle a list of usershare files.
177 ***************************************************************************/
178
179 struct file_list {
180         struct file_list *next, *prev;
181         const char *pathname;
182 };
183
184 static struct file_list *flist;
185
186 /***************************************************************************
187 ***************************************************************************/
188
189 static int get_share_list(TALLOC_CTX *ctx, const char *wcard, BOOL only_ours)
190 {
191         SMB_STRUCT_DIR *dp;
192         SMB_STRUCT_DIRENT *de;
193         uid_t myuid = geteuid();
194         struct file_list *fl = NULL;
195         pstring basepath;
196
197         get_basepath(basepath);
198         dp = sys_opendir(basepath);
199         if (!dp) {
200                 d_fprintf(stderr, "get_share_list: cannot open usershare directory %s. Error %s\n",
201                         basepath, strerror(errno) );
202                 return -1;
203         }
204
205         while((de = sys_readdir(dp)) != 0) {
206                 SMB_STRUCT_STAT sbuf;
207                 pstring path;
208                 const char *n = de->d_name;
209
210                 /* Ignore . and .. */
211                 if (*n == '.') {
212                         if ((n[1] == '\0') || (n[1] == '.' && n[2] == '\0')) {
213                                 continue;
214                         }
215                 }
216
217                 if (!validate_net_name(n, INVALID_SHARENAME_CHARS, strlen(n))) {
218                         d_fprintf(stderr, "get_share_list: ignoring bad share name %s\n",n);
219                         continue;
220                 }
221                 pstrcpy(path, basepath);
222                 pstrcat(path, "/");
223                 pstrcat(path, n);
224
225                 if (sys_lstat(path, &sbuf) != 0) {
226                         d_fprintf(stderr, "get_share_list: can't lstat file %s. Error was %s\n",
227                                 path, strerror(errno) );
228                         continue;
229                 }
230
231                 if (!S_ISREG(sbuf.st_mode)) {
232                         d_fprintf(stderr, "get_share_list: file %s is not a regular file. Ignoring.\n",
233                                 path );
234                         continue;
235                 }
236
237                 if (only_ours && sbuf.st_uid != myuid) {
238                         continue;
239                 }
240
241                 if (!unix_wild_match(wcard, n)) {
242                         continue;
243                 }
244
245                 /* (Finally) - add to list. */ 
246                 fl = TALLOC_P(ctx, struct file_list);
247                 if (!fl) {
248                         return -1;
249                 }
250                 fl->pathname = talloc_strdup(ctx, n);
251                 if (!fl->pathname) {
252                         return -1;
253                 }
254
255                 DLIST_ADD(flist, fl);
256         }
257
258         sys_closedir(dp);
259         return 0;
260 }
261
262 enum us_priv_op { US_LIST_OP, US_INFO_OP};
263
264 struct us_priv_info {
265         TALLOC_CTX *ctx;
266         enum us_priv_op op;
267 };
268
269 /***************************************************************************
270  Call a function for every share on the list.
271 ***************************************************************************/
272
273 static int process_share_list(int (*fn)(struct file_list *, void *), void *priv)
274 {
275         struct file_list *fl;
276         int ret = 0;
277
278         for (fl = flist; fl; fl = fl->next) {
279                 ret = (*fn)(fl, priv);
280         }
281
282         return ret;
283 }
284
285 /***************************************************************************
286  Info function.
287 ***************************************************************************/
288
289 static int info_fn(struct file_list *fl, void *priv)
290 {
291         SMB_STRUCT_STAT sbuf;
292         char **lines = NULL;
293         struct us_priv_info *pi = (struct us_priv_info *)priv;
294         TALLOC_CTX *ctx = pi->ctx;
295         int fd = -1;
296         int numlines = 0;
297         SEC_DESC *psd = NULL;
298         pstring basepath;
299         pstring sharepath;
300         pstring comment;
301         pstring acl_str;
302         int num_aces;
303         char sep_str[2];
304         enum usershare_err us_err;
305         BOOL guest_ok = False;
306
307         sep_str[0] = *lp_winbind_separator();
308         sep_str[1] = '\0';
309
310         get_basepath(basepath);
311         pstrcat(basepath, "/");
312         pstrcat(basepath, fl->pathname);
313
314 #ifdef O_NOFOLLOW
315         fd = sys_open(basepath, O_RDONLY|O_NOFOLLOW, 0);
316 #else
317         fd = sys_open(basepath, O_RDONLY, 0);
318 #endif
319
320         if (fd == -1) {
321                 d_fprintf(stderr, "info_fn: unable to open %s. %s\n",
322                         basepath, strerror(errno) );
323                 return -1;
324         }
325
326         /* Paranoia... */
327         if (sys_fstat(fd, &sbuf) != 0) {
328                 d_fprintf(stderr, "info_fn: can't fstat file %s. Error was %s\n",
329                         basepath, strerror(errno) );
330                 close(fd);
331                 return -1;
332         }
333
334         if (!S_ISREG(sbuf.st_mode)) {
335                 d_fprintf(stderr, "info_fn: file %s is not a regular file. Ignoring.\n",
336                         basepath );
337                 close(fd);
338                 return -1;
339         }
340
341         lines = fd_lines_load(fd, &numlines, 10240);
342         close(fd);
343
344         if (lines == NULL) {
345                 return -1;
346         }
347
348         /* Ensure it's well formed. */
349         us_err = parse_usershare_file(ctx, &sbuf, fl->pathname, -1, lines, numlines,
350                                 sharepath,
351                                 comment,
352                                 &psd,
353                                 &guest_ok);
354
355         file_lines_free(lines);
356
357         if (us_err != USERSHARE_OK) {
358                 d_fprintf(stderr, "info_fn: file %s is not a well formed usershare file.\n",
359                         basepath );
360                 d_fprintf(stderr, "info_fn: Error was %s.\n",
361                         get_us_error_code(us_err) );
362                 return -1;
363         }
364
365         pstrcpy(acl_str, "usershare_acl=");
366
367         for (num_aces = 0; num_aces < psd->dacl->num_aces; num_aces++) {
368                 char access_str[2];
369                 const char *domain;
370                 const char *name;
371                 NTSTATUS ntstatus;
372
373                 access_str[1] = '\0';
374
375                 ntstatus = net_lookup_name_from_sid(ctx, &psd->dacl->ace[num_aces].trustee, &domain, &name);
376
377                 if (NT_STATUS_IS_OK(ntstatus)) {
378                         if (domain && *domain) {
379                                 pstrcat(acl_str, domain);
380                                 pstrcat(acl_str, sep_str);
381                         }
382                         pstrcat(acl_str,name);
383                 } else {
384                         fstring sidstr;
385                         sid_to_string(sidstr, &psd->dacl->ace[num_aces].trustee);
386                         pstrcat(acl_str,sidstr);
387                 }
388                 pstrcat(acl_str, ":");
389
390                 if (psd->dacl->ace[num_aces].type == SEC_ACE_TYPE_ACCESS_DENIED) {
391                         pstrcat(acl_str, "D,");
392                 } else {
393                         if (psd->dacl->ace[num_aces].info.mask & GENERIC_ALL_ACCESS) {
394                                 pstrcat(acl_str, "F,");
395                         } else {
396                                 pstrcat(acl_str, "R,");
397                         }
398                 }
399         }
400
401         acl_str[strlen(acl_str)-1] = '\0';
402
403         if (pi->op == US_INFO_OP) {
404                 d_printf("[%s]\n", fl->pathname );
405                 d_printf("path=%s\n", sharepath );
406                 d_printf("comment=%s\n", comment);
407                 d_printf("%s\n", acl_str);
408                 d_printf("guest_ok=%c\n\n", guest_ok ? 'y' : 'n');
409         } else if (pi->op == US_LIST_OP) {
410                 d_printf("%s\n", fl->pathname);
411         }
412
413         return 0;
414 }
415
416 /***************************************************************************
417  Print out info (internal detail) on userlevel shares.
418 ***************************************************************************/
419
420 static int net_usershare_info(int argc, const char **argv)
421 {
422         fstring wcard;
423         BOOL only_ours = True;
424         int ret = -1;
425         struct us_priv_info pi;
426         TALLOC_CTX *ctx;
427
428         fstrcpy(wcard, "*");
429
430         if (opt_long_list_entries) {
431                 only_ours = False;
432         }
433
434         switch (argc) {
435                 case 0:
436                         break;
437                 case 1:
438                         fstrcpy(wcard, argv[0]);
439                         break;
440                 default:
441                         return net_usershare_info_usage(argc, argv);
442         }
443
444         strlower_m(wcard);
445
446         ctx = talloc_init("share_info");
447         ret = get_share_list(ctx, wcard, only_ours);
448         if (ret) {
449                 return ret;
450         }
451
452         pi.ctx = ctx;
453         pi.op = US_INFO_OP;
454
455         ret = process_share_list(info_fn, &pi);
456         talloc_destroy(ctx);
457         return ret;
458 }
459
460 /***************************************************************************
461  Add a single userlevel share.
462 ***************************************************************************/
463
464 static int net_usershare_add(int argc, const char **argv)
465 {
466         TALLOC_CTX *ctx = NULL;
467         SMB_STRUCT_STAT sbuf;
468         SMB_STRUCT_STAT lsbuf;
469         char *sharename;
470         pstring full_path;
471         pstring full_path_tmp;
472         const char *us_path;
473         const char *us_comment;
474         const char *arg_acl;
475         char *us_acl;
476         char *file_img;
477         int num_aces = 0;
478         int i;
479         int tmpfd;
480         const char *pacl;
481         size_t to_write;
482         uid_t myeuid = geteuid();
483         BOOL guest_ok = False;
484
485         us_comment = "";
486         arg_acl = "S-1-1-0:R";
487
488         switch (argc) {
489                 case 0:
490                 case 1:
491                 default:
492                         return net_usershare_add_usage(argc, argv);
493                 case 2:
494                         sharename = strdup_lower(argv[0]);
495                         us_path = argv[1];
496                         break;
497                 case 3:
498                         sharename = strdup_lower(argv[0]);
499                         us_path = argv[1];
500                         us_comment = argv[2];
501                         break;
502                 case 4:
503                         sharename = strdup_lower(argv[0]);
504                         us_path = argv[1];
505                         us_comment = argv[2];
506                         arg_acl = argv[3];
507                         break;
508                 case 5:
509                         sharename = strdup_lower(argv[0]);
510                         us_path = argv[1];
511                         us_comment = argv[2];
512                         arg_acl = argv[3];
513                         if (!strnequal(argv[4], "guest_ok=", 9)) {
514                                 return net_usershare_add_usage(argc, argv);
515                         }
516                         switch (argv[4][9]) {
517                                 case 'y':
518                                 case 'Y':
519                                         guest_ok = True;
520                                         break;
521                                 case 'n':
522                                 case 'N':
523                                         guest_ok = False;
524                                         break;
525                                 default: 
526                                         return net_usershare_add_usage(argc, argv);
527                         }
528                         break;
529         }
530
531         if (!validate_net_name(sharename, INVALID_SHARENAME_CHARS, strlen(sharename))) {
532                 d_fprintf(stderr, "net usershare add: share name %s contains "
533                         "invalid characters (any of %s)\n",
534                         sharename, INVALID_SHARENAME_CHARS);
535                 SAFE_FREE(sharename);
536                 return -1;
537         }
538
539         /* Disallow shares the same as users. */
540         if (getpwnam(sharename)) {
541                 d_fprintf(stderr, "net usershare add: share name %s is already a valid system user name\n",
542                         sharename );
543                 SAFE_FREE(sharename);
544                 return -1;
545         }
546
547         /* Construct the full path for the usershare file. */
548         get_basepath(full_path);
549         pstrcat(full_path, "/");
550         pstrcpy(full_path_tmp, full_path);
551         pstrcat(full_path, sharename);
552         pstrcat(full_path_tmp, ":tmpXXXXXX");
553
554         /* The path *must* be absolute. */
555         if (us_path[0] != '/') {
556                 d_fprintf(stderr,"net usershare add: path %s is not an absolute path.\n",
557                         us_path);
558                 SAFE_FREE(sharename);
559                 return -1;
560         }
561
562         /* Check the directory to be shared exists. */
563         if (sys_stat(us_path, &sbuf) != 0) {
564                 d_fprintf(stderr, "net usershare add: cannot stat path %s to ensure "
565                         "this is a directory. Error was %s\n",
566                         us_path, strerror(errno) );
567                 SAFE_FREE(sharename);
568                 return -1;
569         }
570
571         if (!S_ISDIR(sbuf.st_mode)) {
572                 d_fprintf(stderr, "net usershare add: path %s is not a directory.\n",
573                         us_path );
574                 SAFE_FREE(sharename);
575                 return -1;
576         }
577
578         /* If we're not root, check if we're restricted to sharing out directories
579            that we own only. */
580
581         if ((myeuid != 0) && lp_usershare_owner_only() && (myeuid != sbuf.st_uid)) {
582                 d_fprintf(stderr, "net usershare add: cannot share path %s as "
583                         "we are restricted to only sharing directories we own.\n"
584                         "\tAsk the administrator to add the line \"usershare owner only = False\" \n"
585                         "\tto the [global] section of the smb.conf to allow this.\n",
586                         us_path );
587                 SAFE_FREE(sharename);
588                 return -1;
589         }
590
591         /* No validation needed on comment. Now go through and validate the
592            acl string. Convert names to SID's as needed. Then run it through
593            parse_usershare_acl to ensure it's valid. */
594
595         ctx = talloc_init("share_info");
596
597         /* Start off the string we'll append to. */
598         us_acl = talloc_strdup(ctx, "");
599
600         pacl = arg_acl;
601         num_aces = 1;
602
603         /* Add the number of ',' characters to get the number of aces. */
604         num_aces += count_chars(pacl,',');
605
606         for (i = 0; i < num_aces; i++) {
607                 DOM_SID sid;
608                 const char *pcolon = strchr_m(pacl, ':');
609                 const char *name;
610
611                 if (pcolon == NULL) {
612                         d_fprintf(stderr, "net usershare add: malformed acl %s (missing ':').\n",
613                                 pacl );
614                         talloc_destroy(ctx);
615                         SAFE_FREE(sharename);
616                         return -1;
617                 }
618
619                 switch(pcolon[1]) {
620                         case 'f':
621                         case 'F':
622                         case 'd':
623                         case 'r':
624                         case 'R':
625                                 break;
626                         default:
627                                 d_fprintf(stderr, "net usershare add: malformed acl %s "
628                                         "(access control must be 'r', 'f', or 'd')\n",
629                                         pacl );
630                                 talloc_destroy(ctx);
631                                 SAFE_FREE(sharename);
632                                 return -1;
633                 }
634
635                 if (pcolon[2] != ',' && pcolon[2] != '\0') {
636                         d_fprintf(stderr, "net usershare add: malformed terminating character for acl %s\n",
637                                 pacl );
638                         talloc_destroy(ctx);
639                         SAFE_FREE(sharename);
640                         return -1;
641                 }
642
643                 /* Get the name */
644                 name = talloc_strndup(ctx, pacl, pcolon - pacl);
645                 if (!string_to_sid(&sid, name)) {
646                         /* Convert to a SID */
647                         NTSTATUS ntstatus = net_lookup_sid_from_name(ctx, name, &sid);
648                         if (!NT_STATUS_IS_OK(ntstatus)) {
649                                 d_fprintf(stderr, "net usershare add: cannot convert name \"%s\" to a SID. %s.",
650                                         name, get_friendly_nt_error_msg(ntstatus) );
651                                 if (NT_STATUS_EQUAL(ntstatus, NT_STATUS_CONNECTION_REFUSED)) {
652                                         d_fprintf(stderr,  " Maybe smbd is not running.\n");
653                                 } else {
654                                         d_fprintf(stderr, "\n");
655                                 }
656                                 talloc_destroy(ctx);
657                                 SAFE_FREE(sharename);
658                                 return -1;
659                         }
660                 }
661                 us_acl = talloc_asprintf_append(us_acl, "%s:%c,", sid_string_static(&sid), pcolon[1]);
662
663                 /* Move to the next ACL entry. */
664                 if (pcolon[2] == ',') {
665                         pacl = &pcolon[3];
666                 }
667         }
668
669         /* Remove the last ',' */
670         us_acl[strlen(us_acl)-1] = '\0';
671
672         if (guest_ok && !lp_usershare_allow_guests()) {
673                 d_fprintf(stderr, "net usershare add: guest_ok=y requested "
674                         "but the \"usershare allow guests\" parameter is not enabled "
675                         "by this server.\n");
676                 talloc_destroy(ctx);
677                 SAFE_FREE(sharename);
678                 return -1;
679         }
680
681         /* Create a temporary filename for this share. */
682         tmpfd = smb_mkstemp(full_path_tmp);
683
684         if (tmpfd == -1) {
685                 d_fprintf(stderr, "net usershare add: cannot create tmp file %s\n",
686                                 full_path_tmp );
687                 talloc_destroy(ctx);
688                 SAFE_FREE(sharename);
689                 return -1;
690         }
691
692         /* Ensure we opened the file we thought we did. */
693         if (sys_lstat(full_path_tmp, &lsbuf) != 0) {
694                 d_fprintf(stderr, "net usershare add: cannot lstat tmp file %s\n",
695                                 full_path_tmp );
696                 talloc_destroy(ctx);
697                 SAFE_FREE(sharename);
698                 return -1;
699         }
700
701         /* Check this is the same as the file we opened. */
702         if (sys_fstat(tmpfd, &sbuf) != 0) {
703                 d_fprintf(stderr, "net usershare add: cannot fstat tmp file %s\n",
704                                 full_path_tmp );
705                 talloc_destroy(ctx);
706                 SAFE_FREE(sharename);
707                 return -1;
708         }
709
710         if (!S_ISREG(sbuf.st_mode) || sbuf.st_dev != lsbuf.st_dev || sbuf.st_ino != lsbuf.st_ino) {
711                 d_fprintf(stderr, "net usershare add: tmp file %s is not a regular file ?\n",
712                                 full_path_tmp );
713                 talloc_destroy(ctx);
714                 SAFE_FREE(sharename);
715                 return -1;
716         }
717         
718         if (fchmod(tmpfd, 0644) == -1) {
719                 d_fprintf(stderr, "net usershare add: failed to fchmod tmp file %s to 0644n",
720                                 full_path_tmp );
721                 talloc_destroy(ctx);
722                 SAFE_FREE(sharename);
723                 return -1;
724         }
725
726         /* Create the in-memory image of the file. */
727         file_img = talloc_strdup(ctx, "#VERSION 2\npath=");
728         file_img = talloc_asprintf_append(file_img, "%s\ncomment=%s\nusershare_acl=%s\nguest_ok=%c\n",
729                         us_path, us_comment, us_acl, guest_ok ? 'y' : 'n');
730
731         to_write = strlen(file_img);
732
733         if (write(tmpfd, file_img, to_write) != to_write) {
734                 d_fprintf(stderr, "net usershare add: failed to write %u bytes to file %s. Error was %s\n",
735                         (unsigned int)to_write, full_path_tmp, strerror(errno));
736                 unlink(full_path_tmp);
737                 talloc_destroy(ctx);
738                 SAFE_FREE(sharename);
739                 return -1;
740         }
741
742         /* Attempt to replace any existing share by this name. */
743         if (rename(full_path_tmp, full_path) != 0) {
744                 unlink(full_path_tmp);
745                 d_fprintf(stderr, "net usershare add: failed to add share %s. Error was %s\n",
746                         sharename, strerror(errno));
747                 talloc_destroy(ctx);
748                 close(tmpfd);
749                 SAFE_FREE(sharename);
750                 return -1;
751         }
752
753         close(tmpfd);
754         talloc_destroy(ctx);
755
756         if (opt_long_list_entries) {
757                 const char *my_argv[2];
758                 my_argv[0] = sharename;
759                 my_argv[1] = NULL;
760                 net_usershare_info(1, argv);
761         }
762
763         SAFE_FREE(sharename);
764         return 0;
765 }
766
767 #if 0
768 /***************************************************************************
769  List function.
770 ***************************************************************************/
771
772 static int list_fn(struct file_list *fl, void *priv)
773 {
774         d_printf("%s\n", fl->pathname);
775         return 0;
776 }
777 #endif
778
779 /***************************************************************************
780  List userlevel shares.
781 ***************************************************************************/
782
783 static int net_usershare_list(int argc, const char **argv)
784 {
785         fstring wcard;
786         BOOL only_ours = True;
787         int ret = -1;
788         struct us_priv_info pi;
789         TALLOC_CTX *ctx;
790
791         fstrcpy(wcard, "*");
792
793         if (opt_long_list_entries) {
794                 only_ours = False;
795         }
796
797         switch (argc) {
798                 case 0:
799                         break;
800                 case 1:
801                         fstrcpy(wcard, argv[0]);
802                         break;
803                 default:
804                         return net_usershare_list_usage(argc, argv);
805         }
806
807         strlower_m(wcard);
808
809         ctx = talloc_init("share_list");
810         ret = get_share_list(ctx, wcard, only_ours);
811         if (ret) {
812                 return ret;
813         }
814
815         pi.ctx = ctx;
816         pi.op = US_LIST_OP;
817
818         ret = process_share_list(info_fn, &pi);
819         talloc_destroy(ctx);
820         return ret;
821 }
822
823 /***************************************************************************
824  Handle "net usershare help *" subcommands.
825 ***************************************************************************/
826
827 int net_usershare_help(int argc, const char **argv)
828 {
829         struct functable func[] = {
830                 {"ADD", net_usershare_add_usage},
831                 {"DELETE", net_usershare_delete_usage},
832                 {"INFO", net_usershare_info_usage},
833                 {"LIST", net_usershare_list_usage},
834                 {NULL, NULL}};
835
836         return net_run_function(argc, argv, func, net_usershare_usage);
837 }
838
839 /***************************************************************************
840  Entry-point for all the USERSHARE functions.
841 ***************************************************************************/
842
843 int net_usershare(int argc, const char **argv)
844 {
845         SMB_STRUCT_DIR *dp;
846
847         struct functable func[] = {
848                 {"ADD", net_usershare_add},
849                 {"DELETE", net_usershare_delete},
850                 {"INFO", net_usershare_info},
851                 {"LIST", net_usershare_list},
852                 {"HELP", net_usershare_help},
853                 {NULL, NULL}
854         };
855         
856         if (lp_usershare_max_shares() == 0) {
857                 d_fprintf(stderr, "net usershare: usershares are currently disabled\n");
858                 return -1;
859         }
860
861         dp = sys_opendir(lp_usershare_path());
862         if (!dp) {
863                 int err = errno;
864                 d_fprintf(stderr, "net usershare: cannot open usershare directory %s. Error %s\n",
865                         lp_usershare_path(), strerror(err) );
866                 if (err == EACCES) {
867                         d_fprintf(stderr, "You do not have permission to create a usershare. Ask your "
868                                 "administrator to grant you permissions to create a share.\n");
869                 } else if (err == ENOENT) {
870                         d_fprintf(stderr, "Please ask your system administrator to "
871                                 "enable user sharing.\n");
872                 }
873                 return -1;
874         }
875         sys_closedir(dp);
876
877         return net_run_function(argc, argv, func, net_usershare_usage);
878 }