summaryrefslogtreecommitdiffstats
path: root/utils/gssd/krb5_util.c
blob: dccbeb63ad6478b26d8b6a2151625af1a86ca87a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
/*
 *  Adapted in part from MIT Kerberos 5-1.2.1 slave/kprop.c and from
 *  http://docs.sun.com/?p=/doc/816-1331/6m7oo9sms&a=view
 *
 *  Copyright (c) 2002-2004 The Regents of the University of Michigan.
 *  All rights reserved.
 *
 *  Andy Adamson <andros@umich.edu>
 *  J. Bruce Fields <bfields@umich.edu>
 *  Marius Aamodt Eriksen <marius@umich.edu>
 *  Kevin Coffman <kwc@umich.edu>
 */

/*
 * slave/kprop.c
 *
 * Copyright 1990,1991 by the Massachusetts Institute of Technology.
 * All Rights Reserved.
 *
 * Export of this software from the United States of America may
 *   require a specific license from the United States Government.
 *   It is the responsibility of any person or organization contemplating
 *   export to obtain such a license before exporting.
 *
 * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
 * distribute this software and its documentation for any purpose and
 * without fee is hereby granted, provided that the above copyright
 * notice appear in all copies and that both that copyright notice and
 * this permission notice appear in supporting documentation, and that
 * the name of M.I.T. not be used in advertising or publicity pertaining
 * to distribution of the software without specific, written prior
 * permission.  Furthermore if you modify this software you must label
 * your software as modified software and not distribute it in such a
 * fashion that it might be confused with the original M.I.T. software.
 * M.I.T. makes no representations about the suitability of
 * this software for any purpose.  It is provided "as is" without express
 * or implied warranty.
 */

/*
 * Copyright 1994 by OpenVision Technologies, Inc.
 *
 * Permission to use, copy, modify, distribute, and sell this software
 * and its documentation for any purpose is hereby granted without fee,
 * provided that the above copyright notice appears in all copies and
 * that both that copyright notice and this permission notice appear in
 * supporting documentation, and that the name of OpenVision not be used
 * in advertising or publicity pertaining to distribution of the software
 * without specific, written prior permission. OpenVision makes no
 * representations about the suitability of this software for any
 * purpose.  It is provided "as is" without express or implied warranty.
 *
 * OPENVISION DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
 * EVENT SHALL OPENVISION BE LIABLE FOR ANY SPECIAL, INDIRECT OR
 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
 * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
 * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 */
/*
  krb5_util.c

  Copyright (c) 2004 The Regents of the University of Michigan.
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions
  are met:

  1. Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.
  3. Neither the name of the University nor the names of its
     contributors may be used to endorse or promote products derived
     from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
  BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif	/* HAVE_CONFIG_H */

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif

#include <sys/param.h>
#include <rpc/rpc.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <dirent.h>
#include <netdb.h>
#include <ctype.h>
#include <errno.h>
#include <time.h>
#include <gssapi/gssapi.h>
#ifdef USE_PRIVATE_KRB5_FUNCTIONS
#include <gssapi/gssapi_krb5.h>
#endif
#include <krb5.h>
#include <rpc/auth_gss.h>

#include "gssd.h"
#include "err_util.h"
#include "gss_util.h"
#include "krb5_util.h"

/* Global list of principals/cache file names for machine credentials */
struct gssd_k5_kt_princ *gssd_k5_kt_princ_list = NULL;

/*==========================*/
/*===  Internal routines ===*/
/*==========================*/

static int select_krb5_ccache(const struct dirent *d);
static int gssd_find_existing_krb5_ccache(uid_t uid, char *dirname,
		struct dirent **d);
static int gssd_get_single_krb5_cred(krb5_context context,
		krb5_keytab kt, struct gssd_k5_kt_princ *ple, int nocache);
static int query_krb5_ccache(const char* cred_cache, char **ret_princname,
		char **ret_realm);

/*
 * Called from the scandir function to weed out potential krb5
 * credentials cache files
 *
 * Returns:
 *	0 => don't select this one
 *	1 => select this one
 */
static int
select_krb5_ccache(const struct dirent *d)
{
	/*
	 * Note: We used to check d->d_type for DT_REG here,
	 * but apparenlty reiser4 always has DT_UNKNOWN.
	 * Check for IS_REG after stat() call instead.
	 */
	if (strstr(d->d_name, GSSD_DEFAULT_CRED_PREFIX))
		return 1;
	else
		return 0;
}

/*
 * Look in directory "dirname" for files that look like they
 * are Kerberos Credential Cache files for a given UID.  Return
 * non-zero and the dirent pointer for the entry most likely to be
 * what we want. Otherwise, return zero and no dirent pointer.
 * The caller is responsible for freeing the dirent if one is returned.
 *
 * Returns 0 if a valid-looking entry was found and a non-zero error
 * code otherwise.
 */
static int
gssd_find_existing_krb5_ccache(uid_t uid, char *dirname, struct dirent **d)
{
	struct dirent **namelist;
	int n;
	int i;
	int found = 0;
	struct dirent *best_match_dir = NULL;
	struct stat best_match_stat, tmp_stat;
	char buf[1030];
	char *princname = NULL;
	char *realm = NULL;
	int score, best_match_score = 0, err = -EACCES;

	memset(&best_match_stat, 0, sizeof(best_match_stat));
	*d = NULL;
	n = scandir(dirname, &namelist, select_krb5_ccache, 0);
	if (n < 0) {
		printerr(1, "Error doing scandir on directory '%s': %s\n",
			dirname, strerror(errno));
	}
	else if (n > 0) {
		char statname[1024];
		for (i = 0; i < n; i++) {
			snprintf(statname, sizeof(statname),
				 "%s/%s", dirname, namelist[i]->d_name);
			printerr(3, "CC file '%s' being considered, "
				 "with preferred realm '%s'\n",
				 statname, preferred_realm ?
					preferred_realm : "<none selected>");
			snprintf(buf, sizeof(buf), "FILE:%s/%s", dirname, 
					namelist[i]->d_name);
			if (lstat(statname, &tmp_stat)) {
				printerr(0, "Error doing stat on file '%s'\n",
					 statname);
				free(namelist[i]);
				continue;
			}
			/* Only pick caches owned by the user (uid) */
			if (tmp_stat.st_uid != uid) {
				printerr(3, "CC file '%s' owned by %u, not %u\n",
					 statname, tmp_stat.st_uid, uid);
				free(namelist[i]);
				continue;
			}
			if (!S_ISREG(tmp_stat.st_mode)) {
				printerr(3, "CC file '%s' is not a regular file\n",
					 statname);
				free(namelist[i]);
				continue;
			}
			if (!query_krb5_ccache(buf, &princname, &realm)) {
				printerr(3, "CC file '%s' is expired or corrupt\n",
					 statname);
				free(namelist[i]);
				err = -EKEYEXPIRED;
				continue;
			}

			score = 0;
			if (preferred_realm &&
					strcmp(realm, preferred_realm) == 0) 
				score++;

			printerr(3, "CC file '%s'(%s@%s) passed all checks and"
				    " has mtime of %u\n",
				 statname, princname, realm, 
				 tmp_stat.st_mtime);
			/*
			 * if more than one match is found, return the most
			 * recent (the one with the latest mtime), and
			 * don't free the dirent
			 */
			if (!found) {
				best_match_dir = namelist[i];
				best_match_stat = tmp_stat;
				best_match_score = score;
				found++;
			}
			else {
				/*
				 * If current score is higher than best match 
				 * score, we use the current match. Otherwise,
				 * if the current match has an mtime later
				 * than the one we are looking at, then use
				 * the current match.  Otherwise, we still
				 * have the best match.
				 */
				if (best_match_score < score ||
				    (best_match_score == score && 
				       tmp_stat.st_mtime >
					    best_match_stat.st_mtime)) {
					free(best_match_dir);
					best_match_dir = namelist[i];
					best_match_stat = tmp_stat;
					best_match_score = score;
				}
				else {
					free(namelist[i]);
				}
				printerr(3, "CC file '%s/%s' is our "
					    "current best match "
					    "with mtime of %u\n",
					 dirname, best_match_dir->d_name,
					 best_match_stat.st_mtime);
			}
			free(princname);
			free(realm);
		}
		free(namelist);
	}
	if (found) {
		*d = best_match_dir;
		return 0;
	}

	return err;
}

/*
 * Obtain credentials via a key in the keytab given
 * a keytab handle and a gssd_k5_kt_princ structure.
 * Checks to see if current credentials are expired,
 * if not, uses the keytab to obtain new credentials.
 *
 * Returns:
 *	0 => success (or credentials have not expired)
 *	nonzero => error
 */
static int
gssd_get_single_krb5_cred(krb5_context context,
			  krb5_keytab kt,
			  struct gssd_k5_kt_princ *ple,
			  int nocache)
{
#if HAVE_KRB5_GET_INIT_CREDS_OPT_SET_ADDRESSLESS
	krb5_get_init_creds_opt *init_opts = NULL;
#else
	krb5_get_init_creds_opt options;
#endif
	krb5_get_init_creds_opt *opts;
	krb5_creds my_creds;
	krb5_ccache ccache = NULL;
	char kt_name[BUFSIZ];
	char cc_name[BUFSIZ];
	int code;
	time_t now = time(0);
	char *cache_type;
	char *pname = NULL;
	char *k5err = NULL;

	memset(&my_creds, 0, sizeof(my_creds));

	if (ple->ccname && ple->endtime > now && !nocache) {
		printerr(2, "INFO: Credentials in CC '%s' are good until %d\n",
			 ple->ccname, ple->endtime);
		code = 0;
		goto out;
	}

	if ((code = krb5_kt_get_name(context, kt, kt_name, BUFSIZ))) {
		printerr(0, "ERROR: Unable to get keytab name in "
			    "gssd_get_single_krb5_cred\n");
		goto out;
	}

	if ((krb5_unparse_name(context, ple->princ, &pname)))
		pname = NULL;

#if HAVE_KRB5_GET_INIT_CREDS_OPT_SET_ADDRESSLESS
	code = krb5_get_init_creds_opt_alloc(context, &init_opts);
	if (code) {
		k5err = gssd_k5_err_msg(context, code);
		printerr(0, "ERROR: %s allocating gic options\n", k5err);
		goto out;
	}
	if (krb5_get_init_creds_opt_set_addressless(context, init_opts, 1))
		printerr(1, "WARNING: Unable to set option for addressless "
			 "tickets.  May have problems behind a NAT.\n");
#ifdef TEST_SHORT_LIFETIME
	/* set a short lifetime (for debugging only!) */
	printerr(0, "WARNING: Using (debug) short machine cred lifetime!\n");
	krb5_get_init_creds_opt_set_tkt_life(init_opts, 5*60);
#endif
	opts = init_opts;

#else	/* HAVE_KRB5_GET_INIT_CREDS_OPT_SET_ADDRESSLESS */

	krb5_get_init_creds_opt_init(&options);
	krb5_get_init_creds_opt_set_address_list(&options, NULL);
#ifdef TEST_SHORT_LIFETIME
	/* set a short lifetime (for debugging only!) */
	printerr(0, "WARNING: Using (debug) short machine cred lifetime!\n");
	krb5_get_init_creds_opt_set_tkt_life(&options, 5*60);
#endif
	opts = &options;
#endif

	if ((code = krb5_get_init_creds_keytab(context, &my_creds, ple->princ,
					       kt, 0, NULL, opts))) {
		k5err = gssd_k5_err_msg(context, code);
		printerr(1, "WARNING: %s while getting initial ticket for "
			 "principal '%s' using keytab '%s'\n", k5err,
			 pname ? pname : "<unparsable>", kt_name);
		goto out;
	}

	/*
	 * Initialize cache file which we're going to be using
	 */

	if (use_memcache)
	    cache_type = "MEMORY";
	else
	    cache_type = "FILE";
	snprintf(cc_name, sizeof(cc_name), "%s:%s/%s%s_%s",
		cache_type,
		ccachesearch[0], GSSD_DEFAULT_CRED_PREFIX,
		GSSD_DEFAULT_MACHINE_CRED_SUFFIX, ple->realm);
	ple->endtime = my_creds.times.endtime;
	if (ple->ccname != NULL)
		free(ple->ccname);
	ple->ccname = strdup(cc_name);
	if (ple->ccname == NULL) {
		printerr(0, "ERROR: no storage to duplicate credentials "
			    "cache name '%s'\n", cc_name);
		code = ENOMEM;
		goto out;
	}
	if ((code = krb5_cc_resolve(context, cc_name, &ccache))) {
		k5err = gssd_k5_err_msg(context, code);
		printerr(0, "ERROR: %s while opening credential cache '%s'\n",
			 k5err, cc_name);
		goto out;
	}
	if ((code = krb5_cc_initialize(context, ccache, ple->princ))) {
		k5err = gssd_k5_err_msg(context, code);
		printerr(0, "ERROR: %s while initializing credential "
			 "cache '%s'\n", k5err, cc_name);
		goto out;
	}
	if ((code = krb5_cc_store_cred(context, ccache, &my_creds))) {
		k5err = gssd_k5_err_msg(context, code);
		printerr(0, "ERROR: %s while storing credentials in '%s'\n",
			 k5err, cc_name);
		goto out;
	}

	code = 0;
	printerr(2, "Successfully obtained machine credentials for "
		 "principal '%s' stored in ccache '%s'\n", pname, cc_name);
  out:
#if HAVE_KRB5_GET_INIT_CREDS_OPT_SET_ADDRESSLESS
	if (init_opts)
		krb5_get_init_creds_opt_free(context, init_opts);
#endif
	if (pname)
		k5_free_unparsed_name(context, pname);
	if (ccache)
		krb5_cc_close(context, ccache);
	krb5_free_cred_contents(context, &my_creds);
	free(k5err);
	return (code);
}

/*
 * Depending on the version of Kerberos, we either need to use
 * a private function, or simply set the environment variable.
 */
static void
gssd_set_krb5_ccache_name(char *ccname)
{
#ifdef USE_GSS_KRB5_CCACHE_NAME
	u_int	maj_stat, min_stat;

	printerr(2, "using gss_krb5_ccache_name to select krb5 ccache %s\n",
		 ccname);
	maj_stat = gss_krb5_ccache_name(&min_stat, ccname, NULL);
	if (maj_stat != GSS_S_COMPLETE) {
		printerr(0, "WARNING: gss_krb5_ccache_name with "
			"name '%s' failed (%s)\n",
			ccname, error_message(min_stat));
	}
#else
	/*
	 * Set the KRB5CCNAME environment variable to tell the krb5 code
	 * which credentials cache to use.  (Instead of using the private
	 * function above for which there is no generic gssapi
	 * equivalent.)
	 */
	printerr(2, "using environment variable to select krb5 ccache %s\n",
		 ccname);
	setenv("KRB5CCNAME", ccname, 1);
#endif
}

/*
 * Given a principal, find a matching ple structure
 */
static struct gssd_k5_kt_princ *
find_ple_by_princ(krb5_context context, krb5_principal princ)
{
	struct gssd_k5_kt_princ *ple;

	for (ple = gssd_k5_kt_princ_list; ple != NULL; ple = ple->next) {
		if (krb5_principal_compare(context, ple->princ, princ))
			return ple;
	}
	/* no match found */
	return NULL;
}

/*
 * Create, initialize, and add a new ple structure to the global list
 */
static struct gssd_k5_kt_princ *
new_ple(krb5_context context, krb5_principal princ)
{
	struct gssd_k5_kt_princ *ple = NULL, *p;
	krb5_error_code code;
	char *default_realm;
	int is_default_realm = 0;

	ple = malloc(sizeof(struct gssd_k5_kt_princ));
	if (ple == NULL)
		goto outerr;
	memset(ple, 0, sizeof(*ple));

#ifdef HAVE_KRB5
	ple->realm = strndup(princ->realm.data,
			     princ->realm.length);
#else
	ple->realm = strdup(princ->realm);
#endif
	if (ple->realm == NULL)
		goto outerr;
	code = krb5_copy_principal(context, princ, &ple->princ);
	if (code)
		goto outerr;

	/*
	 * Add new entry onto the list (if this is the default
	 * realm, always add to the front of the list)
	 */

	code = krb5_get_default_realm(context, &default_realm);
	if (code == 0) {
		if (strcmp(ple->realm, default_realm) == 0)
			is_default_realm = 1;
		k5_free_default_realm(context, default_realm);
	}

	if (is_default_realm) {
		ple->next = gssd_k5_kt_princ_list;
		gssd_k5_kt_princ_list = ple;
	} else {
		p = gssd_k5_kt_princ_list;
		while (p != NULL && p->next != NULL)
			p = p->next;
		if (p == NULL)
			gssd_k5_kt_princ_list = ple;
		else
			p->next = ple;
	}

	return ple;
outerr:
	if (ple) {
		if (ple->realm)
			free(ple->realm);
		free(ple);
	}
	return NULL;
}

/*
 * Given a principal, find an existing ple structure, or create one
 */
static struct gssd_k5_kt_princ *
get_ple_by_princ(krb5_context context, krb5_principal princ)
{
	struct gssd_k5_kt_princ *ple;

	/* Need to serialize list if we ever become multi-threaded! */

	ple = find_ple_by_princ(context, princ);
	if (ple == NULL) {
		ple = new_ple(context, princ);
	}

	return ple;
}

/*
 * Given a (possibly unqualified) hostname,
 * return the fully qualified (lower-case!) hostname
 */
static int
get_full_hostname(const char *inhost, char *outhost, int outhostlen)
{
	struct addrinfo *addrs = NULL;
	struct addrinfo hints;
	int retval;
	char *c;

	memset(&hints, 0, sizeof(hints));
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_family = PF_UNSPEC;
	hints.ai_flags = AI_CANONNAME;

	/* Get full target hostname */
	retval = getaddrinfo(inhost, NULL, &hints, &addrs);
	if (retval) {
		printerr(1, "%s while getting full hostname for '%s'\n",
			 gai_strerror(retval), inhost);
		goto out;
	}
	strncpy(outhost, addrs->ai_canonname, outhostlen);
	freeaddrinfo(addrs);
	for (c = outhost; *c != '\0'; c++)
	    *c = tolower(*c);

	printerr(3, "Full hostname for '%s' is '%s'\n", inhost, outhost);
	retval = 0;
out:
	return retval;
}

/* 
 * If principal matches the given realm and service name,
 * and has *any* instance (hostname), return 1.
 * Otherwise return 0, indicating no match.
 */
static int
realm_and_service_match(krb5_context context, krb5_principal p,
			const char *realm, const char *service)
{
#ifdef HAVE_KRB5
	/* Must have two components */
	if (p->length != 2)
		return 0;
	if ((strlen(realm) == p->realm.length)
	    && (strncmp(realm, p->realm.data, p->realm.length) == 0)
	    && (strlen(service) == p->data[0].length)
	    && (strncmp(service, p->data[0].data, p->data[0].length) == 0))
		return 1;
#else
	const char *name, *inst;

	if (p->name.name_string.len != 2)
		return 0;
	name = krb5_principal_get_comp_string(context, p, 0);
	inst = krb5_principal_get_comp_string(context, p, 1);
	if (name == NULL || inst == NULL)
		return 0;
	if ((strcmp(realm, p->realm) == 0)
	    && (strcmp(service, name) == 0))
		return 1;
#endif
	return 0;
}

/*
 * Search the given keytab file looking for an entry with the given
 * service name and realm, ignoring hostname (instance).
 *
 * Returns:
 *	0 => No error
 *	non-zero => An error occurred
 *
 * If a keytab entry is found, "found" is set to one, and the keytab
 * entry is returned in "kte".  Otherwise, "found" is zero, and the
 * value of "kte" is unpredictable.
 */
static int
gssd_search_krb5_keytab(krb5_context context, krb5_keytab kt,
			const char *realm, const char *service,
			int *found, krb5_keytab_entry *kte)
{
	krb5_kt_cursor cursor;
	krb5_error_code code;
	struct gssd_k5_kt_princ *ple;
	int retval = -1;
	char kt_name[BUFSIZ];
	char *pname;
	char *k5err = NULL;

	if (found == NULL) {
		retval = EINVAL;
		goto out;
	}
	*found = 0;

	/*
	 * Look through each entry in the keytab file and determine
	 * if we might want to use it as machine credentials.  If so,
	 * save info in the global principal list (gssd_k5_kt_princ_list).
	 */
	if ((code = krb5_kt_get_name(context, kt, kt_name, BUFSIZ))) {
		k5err = gssd_k5_err_msg(context, code);
		printerr(0, "ERROR: %s attempting to get keytab name\n", k5err);
		retval = code;
		goto out;
	}
	if ((code = krb5_kt_start_seq_get(context, kt, &cursor))) {
		k5err = gssd_k5_err_msg(context, code);
		printerr(0, "ERROR: %s while beginning keytab scan "
			    "for keytab '%s'\n", k5err, kt_name);
		retval = code;
		goto out;
	}

	while ((code = krb5_kt_next_entry(context, kt, kte, &cursor)) == 0) {
		if ((code = krb5_unparse_name(context, kte->principal,
					      &pname))) {
			k5err = gssd_k5_err_msg(context, code);
			printerr(0, "WARNING: Skipping keytab entry because "
				 "we failed to unparse principal name: %s\n",
				 k5err);
			k5_free_kt_entry(context, kte);
			continue;
		}
		printerr(4, "Processing keytab entry for principal '%s'\n",
			 pname);
		/* Use the first matching keytab entry found */
	        if ((realm_and_service_match(context, kte->principal, realm,
					     service))) {
			printerr(4, "We WILL use this entry (%s)\n", pname);
			ple = get_ple_by_princ(context, kte->principal);
			/*
			 * Return, don't free, keytab entry if
			 * we were successful!
			 */
			if (ple == NULL) {
				retval = ENOMEM;
				k5_free_kt_entry(context, kte);
			} else {
				retval = 0;
				*found = 1;
			}
			k5_free_unparsed_name(context, pname);
			break;
		}
		else {
			printerr(4, "We will NOT use this entry (%s)\n",
				pname);
		}
		k5_free_unparsed_name(context, pname);
		k5_free_kt_entry(context, kte);
	}

	if ((code = krb5_kt_end_seq_get(context, kt, &cursor))) {
		k5err = gssd_k5_err_msg(context, code);
		printerr(0, "WARNING: %s while ending keytab scan for "
			    "keytab '%s'\n", k5err, kt_name);
	}

	retval = 0;
  out:
	free(k5err);
	return retval;
}

/*
 * Find a keytab entry to use for a given target hostname.
 * Tries to find the most appropriate keytab to use given the
 * name of the host we are trying to connect with.
 */
static int
find_keytab_entry(krb5_context context, krb5_keytab kt, const char *hostname,
		  krb5_keytab_entry *kte, const char **svcnames)
{
	krb5_error_code code;
	char **realmnames = NULL;
	char myhostname[NI_MAXHOST], targethostname[NI_MAXHOST];
	int i, j, retval;
	char *default_realm = NULL;
	char *realm;
	char *k5err = NULL;
	int tried_all = 0, tried_default = 0;
	krb5_principal princ;


	/* Get full target hostname */
	retval = get_full_hostname(hostname, targethostname,
				   sizeof(targethostname));
	if (retval)
		goto out;

	/* Get full local hostname */
	retval = gethostname(myhostname, sizeof(myhostname));
	if (retval) {
		k5err = gssd_k5_err_msg(context, retval);
		printerr(1, "%s while getting local hostname\n", k5err);
		goto out;
	}
	retval = get_full_hostname(myhostname, myhostname, sizeof(myhostname));
	if (retval)
		goto out;

	code = krb5_get_default_realm(context, &default_realm);
	if (code) {
		retval = code;
		k5err = gssd_k5_err_msg(context, code);
		printerr(1, "%s while getting default realm name\n", k5err);
		goto out;
	}

	/*
	 * Get the realm name(s) for the target hostname.
	 * In reality, this function currently only returns a
	 * single realm, but we code with the assumption that
	 * someday it may actually return a list.
	 */
	code = krb5_get_host_realm(context, targethostname, &realmnames);
	if (code) {
		k5err = gssd_k5_err_msg(context, code);
		printerr(0, "ERROR: %s while getting realm(s) for host '%s'\n",
			 k5err, targethostname);
		retval = code;
		goto out;
	}

	/*
	 * Try the "appropriate" realm first, and if nothing found for that
	 * realm, try the default realm (if it hasn't already been tried).
	 */
	i = 0;
	realm = realmnames[i];
	while (1) {
		if (realm == NULL) {
			tried_all = 1;
			if (!tried_default)
				realm = default_realm;
		}
		if (tried_all && tried_default)
			break;
		if (strcmp(realm, default_realm) == 0)
			tried_default = 1;
		for (j = 0; svcnames[j] != NULL; j++) {
			code = krb5_build_principal_ext(context, &princ,
							strlen(realm),
							realm,
							strlen(svcnames[j]),
							svcnames[j],
							strlen(myhostname),
							myhostname,
							NULL);
			if (code) {
				k5err = gssd_k5_err_msg(context, code);
				printerr(1, "%s while building principal for "
					 "'%s/%s@%s'\n", k5err, svcnames[j],
					 myhostname, realm);
				continue;
			}
			code = krb5_kt_get_entry(context, kt, princ, 0, 0, kte);
			krb5_free_principal(context, princ);
			if (code) {
				k5err = gssd_k5_err_msg(context, code);
				printerr(3, "%s while getting keytab entry for "
					 "'%s/%s@%s'\n", k5err, svcnames[j],
					 myhostname, realm);
			} else {
				printerr(3, "Success getting keytab entry for "
					 "'%s/%s@%s'\n",
					 svcnames[j], myhostname, realm);
				retval = 0;
				goto out;
			}
			retval = code;
		}
		/*
		 * Nothing found with our hostname instance, now look for
		 * names with any instance (they must have an instance)
		 */
		for (j = 0; svcnames[j] != NULL; j++) {
			int found = 0;
			code = gssd_search_krb5_keytab(context, kt, realm,
						       svcnames[j], &found, kte);
			if (!code && found) {
				printerr(3, "Success getting keytab entry for "
					 "%s/*@%s\n", svcnames[j], realm);
				retval = 0;
				goto out;
			}
		}
		if (!tried_all) {
			i++;
			realm = realmnames[i];
		}
	}
out:
	if (default_realm)
		k5_free_default_realm(context, default_realm);
	if (realmnames)
		krb5_free_host_realm(context, realmnames);
	free(k5err);
	return retval;
}


static inline int data_is_equal(krb5_data d1, krb5_data d2)
{
	return (d1.length == d2.length
		&& memcmp(d1.data, d2.data, d1.length) == 0);
}

static int
check_for_tgt(krb5_context context, krb5_ccache ccache,
	      krb5_principal principal)
{
	krb5_error_code ret;
	krb5_creds creds;
	krb5_cc_cursor cur;
	int found = 0;

	ret = krb5_cc_start_seq_get(context, ccache, &cur);
	if (ret) 
		return 0;

	while (!found &&
		(ret = krb5_cc_next_cred(context, ccache, &cur, &creds)) == 0) {
		if (creds.server->length == 2 &&
				data_is_equal(creds.server->realm,
					      principal->realm) &&
				creds.server->data[0].length == 6 &&
				memcmp(creds.server->data[0].data,
						"krbtgt", 6) == 0 &&
				data_is_equal(creds.server->data[1],
					      principal->realm) &&
				creds.times.endtime > time(NULL))
			found = 1;
		krb5_free_cred_contents(context, &creds);
	}
	krb5_cc_end_seq_get(context, ccache, &cur);

	return found;
}

static int
query_krb5_ccache(const char* cred_cache, char **ret_princname,
		  char **ret_realm)
{
	krb5_error_code ret;
	krb5_context context;
	krb5_ccache ccache;
	krb5_principal principal;
	int found = 0;
	char *str = NULL;
	char *princstring;

	ret = krb5_init_context(&context);
	if (ret) 
		return 0;

	if(!cred_cache || krb5_cc_resolve(context, cred_cache, &ccache))
		goto err_cache;

	if (krb5_cc_set_flags(context, ccache, 0))
		goto err_princ;

	ret = krb5_cc_get_principal(context, ccache, &principal);
	if (ret) 
		goto err_princ;

	found = check_for_tgt(context, ccache, principal);
	if (found) {
		ret = krb5_unparse_name(context, principal, &princstring);
		if (ret == 0) {
		    if ((str = strchr(princstring, '@')) != NULL) {
			    *str = '\0';
			    *ret_princname = strdup(princstring);
			    *ret_realm = strdup(str+1);
		    }
		    k5_free_unparsed_name(context, princstring);
		} else {
			found = 0;
		}
	}
	krb5_free_principal(context, principal);
err_princ:
	krb5_cc_set_flags(context, ccache,  KRB5_TC_OPENCLOSE);
	krb5_cc_close(context, ccache);
err_cache:
	krb5_free_context(context);
	return found;
}

/*==========================*/
/*===  External routines ===*/
/*==========================*/

/*
 * Attempt to find the best match for a credentials cache file
 * given only a UID.  We really need more information, but we
 * do the best we can.
 *
 * Returns 0 if a ccache was found, and a non-zero error code otherwise.
 */
int
gssd_setup_krb5_user_gss_ccache(uid_t uid, char *servername, char *dirname)
{
	char			buf[MAX_NETOBJ_SZ];
	struct dirent		*d;
	int			err;

	printerr(2, "getting credentials for client with uid %u for "
		    "server %s\n", uid, servername);
	memset(buf, 0, sizeof(buf));
	err = gssd_find_existing_krb5_ccache(uid, dirname, &d);
	if (err)
		return err;

	snprintf(buf, sizeof(buf), "FILE:%s/%s", dirname, d->d_name);
	free(d);

	printerr(2, "using %s as credentials cache for client with "
		    "uid %u for server %s\n", buf, uid, servername);
	gssd_set_krb5_ccache_name(buf);
	return err;
}

/*
 * Let the gss code know where to find the machine credentials ccache.
 *
 * Returns:
 *	void
 */
void
gssd_setup_krb5_machine_gss_ccache(char *ccname)
{
	printerr(2, "using %s as credentials cache for machine creds\n",
		 ccname);
	gssd_set_krb5_ccache_name(ccname);
}

/*
 * Return an array of pointers to names of credential cache files
 * which can be used to try to create gss contexts with a server.
 *
 * Returns:
 *	0 => list is attached
 *	nonzero => error
 */
int
gssd_get_krb5_machine_cred_list(char ***list)
{
	char **l;
	int listinc = 10;
	int listsize = listinc;
	int i = 0;
	int retval;
	struct gssd_k5_kt_princ *ple;

	/* Assume failure */
	retval = -1;
	*list = (char **) NULL;

	if ((l = (char **) malloc(listsize * sizeof(char *))) == NULL) {
		retval = ENOMEM;
		goto out;
	}

	/* Need to serialize list if we ever become multi-threaded! */

	for (ple = gssd_k5_kt_princ_list; ple; ple = ple->next) {
		if (ple->ccname) {
			/* Make sure cred is up-to-date before returning it */
			retval = gssd_refresh_krb5_machine_credential(NULL, ple,
				NULL);
			if (retval)
				continue;
			if (i + 1 > listsize) {
				listsize += listinc;
				l = (char **)
					realloc(l, listsize * sizeof(char *));
				if (l == NULL) {
					retval = ENOMEM;
					goto out;
				}
			}
			if ((l[i++] = strdup(ple->ccname)) == NULL) {
				retval = ENOMEM;
				goto out;
			}
		}
	}
	if (i > 0) {
		l[i] = NULL;
		*list = l;
		retval = 0;
		goto out;
	}
  out:
	return retval;
}

/*
 * Frees the list of names returned in get_krb5_machine_cred_list()
 */
void
gssd_free_krb5_machine_cred_list(char **list)
{
	char **n;

	if (list == NULL)
		return;
	for (n = list; n && *n; n++) {
		free(*n);
	}
	free(list);
}

/*
 * Called upon exit.  Destroys machine credentials.
 */
void
gssd_destroy_krb5_machine_creds(void)
{
	krb5_context context;
	krb5_error_code code = 0;
	krb5_ccache ccache;
	struct gssd_k5_kt_princ *ple;
	char *k5err = NULL;

	code = krb5_init_context(&context);
	if (code) {
		k5err = gssd_k5_err_msg(NULL, code);
		printerr(0, "ERROR: %s while initializing krb5\n", k5err);
		goto out;
	}

	for (ple = gssd_k5_kt_princ_list; ple; ple = ple->next) {
		if (!ple->ccname)
			continue;
		if ((code = krb5_cc_resolve(context, ple->ccname, &ccache))) {
			k5err = gssd_k5_err_msg(context, code);
			printerr(0, "WARNING: %s while resolving credential "
				    "cache '%s' for destruction\n", k5err,
				    ple->ccname);
			continue;
		}

		if ((code = krb5_cc_destroy(context, ccache))) {
			k5err = gssd_k5_err_msg(context, code);
			printerr(0, "WARNING: %s while destroying credential "
				    "cache '%s'\n", k5err, ple->ccname);
		}
	}
  out:
	free(k5err);
	krb5_free_context(context);
}

/*
 * Obtain (or refresh if necessary) Kerberos machine credentials
 */
int
gssd_refresh_krb5_machine_credential(char *hostname,
				     struct gssd_k5_kt_princ *ple, 
					 char *service)
{
	krb5_error_code code = 0;
	krb5_context context;
	krb5_keytab kt = NULL;;
	int retval = 0;
	char *k5err = NULL;
	const char *svcnames[4] = { "root", "nfs", "host", NULL };

	/*
	 * If a specific service name was specified, use it.
	 * Otherwise, use the default list.
	 */
	if (service != NULL && strcmp(service, "*") != 0) {
		svcnames[0] = service;
		svcnames[1] = NULL;
	}
	if (hostname == NULL && ple == NULL)
		return EINVAL;

	code = krb5_init_context(&context);
	if (code) {
		k5err = gssd_k5_err_msg(NULL, code);
		printerr(0, "ERROR: %s: %s while initializing krb5 context\n",
			 __func__, k5err);
		retval = code;
		goto out;
	}

	if ((code = krb5_kt_resolve(context, keytabfile, &kt))) {
		k5err = gssd_k5_err_msg(context, code);
		printerr(0, "ERROR: %s: %s while resolving keytab '%s'\n",
			 __func__, k5err, keytabfile);
		goto out;
	}

	if (ple == NULL) {
		krb5_keytab_entry kte;

		code = find_keytab_entry(context, kt, hostname, &kte, svcnames);
		if (code) {
			printerr(0, "ERROR: %s: no usable keytab entry found "
				 "in keytab %s for connection with host %s\n",
				 __FUNCTION__, keytabfile, hostname);
			retval = code;
			goto out;
		}

		ple = get_ple_by_princ(context, kte.principal);
		k5_free_kt_entry(context, &kte);
		if (ple == NULL) {
			char *pname;
			if ((krb5_unparse_name(context, kte.principal, &pname))) {
				pname = NULL;
			}
			printerr(0, "ERROR: %s: Could not locate or create "
				 "ple struct for principal %s for connection "
				 "with host %s\n",
				 __FUNCTION__, pname ? pname : "<unparsable>",
				 hostname);
			if (pname) k5_free_unparsed_name(context, pname);
			goto out;
		}
	}
	retval = gssd_get_single_krb5_cred(context, kt, ple, 0);
out:
	if (kt)
		krb5_kt_close(context, kt);
	krb5_free_context(context);
	free(k5err);
	return retval;
}

/*
 * A common routine for getting the Kerberos error message
 */
char *
gssd_k5_err_msg(krb5_context context, krb5_error_code code)
{
	const char *origmsg;
	char *msg = NULL;

#if HAVE_KRB5_GET_ERROR_MESSAGE
	if (context != NULL) {
		origmsg = krb5_get_error_message(context, code);
		msg = strdup(origmsg);
		krb5_free_error_message(context, origmsg);
	}
#endif
	if (msg != NULL)
		return msg;
#if HAVE_KRB5
	return strdup(error_message(code));
#else
	if (context != NULL)
		return strdup(krb5_get_err_text(context, code));
	else
		return strdup(error_message(code));
#endif
}

/*
 * Return default Kerberos realm
 */
void
gssd_k5_get_default_realm(char **def_realm)
{
	krb5_context context;

	if (krb5_init_context(&context))
		return;

	krb5_get_default_realm(context, def_realm);

	krb5_free_context(context);
}

#ifdef HAVE_SET_ALLOWABLE_ENCTYPES
/*
 * this routine obtains a credentials handle via gss_acquire_cred()
 * then calls gss_krb5_set_allowable_enctypes() to limit the encryption
 * types negotiated.
 *
 * XXX Should call some function to determine the enctypes supported
 * by the kernel. (Only need to do that once!)
 *
 * Returns:
 *	0 => all went well
 *     -1 => there was an error
 */

int
limit_krb5_enctypes(struct rpc_gss_sec *sec, uid_t uid)
{
	u_int maj_stat, min_stat;
	gss_cred_id_t credh;
	gss_OID_set_desc  desired_mechs;
	krb5_enctype enctypes[] = { ENCTYPE_DES_CBC_CRC,
				    ENCTYPE_DES_CBC_MD5,
				    ENCTYPE_DES_CBC_MD4 };
	int num_enctypes = sizeof(enctypes) / sizeof(enctypes[0]);
	extern int num_krb5_enctypes;
	extern krb5_enctype *krb5_enctypes;

	/* We only care about getting a krb5 cred */
	desired_mechs.count = 1;
	desired_mechs.elements = &krb5oid;

	maj_stat = gss_acquire_cred(&min_stat, NULL, 0,
				    &desired_mechs, GSS_C_INITIATE,
				    &credh, NULL, NULL);

	if (maj_stat != GSS_S_COMPLETE) {
		if (get_verbosity() > 0)
			pgsserr("gss_acquire_cred",
				maj_stat, min_stat, &krb5oid);
		return -1;
	}

	/*
	 * If we failed for any reason to produce global
	 * list of supported enctypes, use local default here.
	 */
	if (krb5_enctypes == NULL)
		maj_stat = gss_set_allowable_enctypes(&min_stat, credh,
					&krb5oid, num_enctypes, enctypes);
	else
		maj_stat = gss_set_allowable_enctypes(&min_stat, credh,
					&krb5oid, num_krb5_enctypes, krb5_enctypes);

	if (maj_stat != GSS_S_COMPLETE) {
		pgsserr("gss_set_allowable_enctypes",
			maj_stat, min_stat, &krb5oid);
		gss_release_cred(&min_stat, &credh);
		return -1;
	}
	sec->cred = credh;

	return 0;
}
#endif	/* HAVE_SET_ALLOWABLE_ENCTYPES */
5 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526 7527 7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545 7546 7547 7548 7549 7550 7551 7552 7553 7554 7555 7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817
/*
   Unix SMB/CIFS implementation.
   Main SMB reply routines
   Copyright (C) Andrew Tridgell 1992-1998
   Copyright (C) Andrew Bartlett      2001
   Copyright (C) Jeremy Allison 1992-2007.
   Copyright (C) Volker Lendecke 2007

   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 3 of the License, or
   (at your option) any later version.

   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, see <http://www.gnu.org/licenses/>.
*/
/*
   This file handles most of the reply_ calls that the server
   makes to handle specific protocols
*/

#include "includes.h"
#include "smbd/globals.h"

/****************************************************************************
 Ensure we check the path in *exactly* the same way as W2K for a findfirst/findnext
 path or anything including wildcards.
 We're assuming here that '/' is not the second byte in any multibyte char
 set (a safe assumption). '\\' *may* be the second byte in a multibyte char
 set.
****************************************************************************/

/* Custom version for processing POSIX paths. */
#define IS_PATH_SEP(c,posix_only) ((c) == '/' || (!(posix_only) && (c) == '\\'))

static NTSTATUS check_path_syntax_internal(char *path,
					   bool posix_path,
					   bool *p_last_component_contains_wcard)
{
	char *d = path;
	const char *s = path;
	NTSTATUS ret = NT_STATUS_OK;
	bool start_of_name_component = True;
	bool stream_started = false;

	*p_last_component_contains_wcard = False;

	while (*s) {
		if (stream_started) {
			switch (*s) {
			case '/':
			case '\\':
				return NT_STATUS_OBJECT_NAME_INVALID;
			case ':':
				if (s[1] == '\0') {
					return NT_STATUS_OBJECT_NAME_INVALID;
				}
				if (strchr_m(&s[1], ':')) {
					return NT_STATUS_OBJECT_NAME_INVALID;
				}
				break;
			}
		}

		if (!posix_path && !stream_started && *s == ':') {
			if (*p_last_component_contains_wcard) {
				return NT_STATUS_OBJECT_NAME_INVALID;
			}
			/* Stream names allow more characters than file names.
			   We're overloading posix_path here to allow a wider
			   range of characters. If stream_started is true this
			   is still a Windows path even if posix_path is true.
			   JRA.
			*/
			stream_started = true;
			start_of_name_component = false;
			posix_path = true;

			if (s[1] == '\0') {
				return NT_STATUS_OBJECT_NAME_INVALID;
			}
		}

		if (!stream_started && IS_PATH_SEP(*s,posix_path)) {
			/*
			 * Safe to assume is not the second part of a mb char
			 * as this is handled below.
			 */
			/* Eat multiple '/' or '\\' */
			while (IS_PATH_SEP(*s,posix_path)) {
				s++;
			}
			if ((d != path) && (*s != '\0')) {
				/* We only care about non-leading or trailing '/' or '\\' */
				*d++ = '/';
			}

			start_of_name_component = True;
			/* New component. */
			*p_last_component_contains_wcard = False;
			continue;
		}

		if (start_of_name_component) {
			if ((s[0] == '.') && (s[1] == '.') && (IS_PATH_SEP(s[2],posix_path) || s[2] == '\0')) {
				/* Uh oh - "/../" or "\\..\\"  or "/..\0" or "\\..\0" ! */

				/*
				 * No mb char starts with '.' so we're safe checking the directory separator here.
				 */

				/* If  we just added a '/' - delete it */
				if ((d > path) && (*(d-1) == '/')) {
					*(d-1) = '\0';
					d--;
				}

				/* Are we at the start ? Can't go back further if so. */
				if (d <= path) {
					ret = NT_STATUS_OBJECT_PATH_SYNTAX_BAD;
					break;
				}
				/* Go back one level... */
				/* We know this is safe as '/' cannot be part of a mb sequence. */
				/* NOTE - if this assumption is invalid we are not in good shape... */
				/* Decrement d first as d points to the *next* char to write into. */
				for (d--; d > path; d--) {
					if (*d == '/')
						break;
				}
				s += 2; /* Else go past the .. */
				/* We're still at the start of a name component, just the previous one. */
				continue;

			} else if ((s[0] == '.') && ((s[1] == '\0') || IS_PATH_SEP(s[1],posix_path))) {
				if (posix_path) {
					/* Eat the '.' */
					s++;
					continue;
				}
			}

		}

		if (!(*s & 0x80)) {
			if (!posix_path) {
				if (*s <= 0x1f || *s == '|') {
					return NT_STATUS_OBJECT_NAME_INVALID;
				}
				switch (*s) {
					case '*':
					case '?':
					case '<':
					case '>':
					case '"':
						*p_last_component_contains_wcard = True;
						break;
					default:
						break;
				}
			}
			*d++ = *s++;
		} else {
			size_t siz;
			/* Get the size of the next MB character. */
			next_codepoint(s,&siz);
			switch(siz) {
				case 5:
					*d++ = *s++;
					/*fall through*/
				case 4:
					*d++ = *s++;
					/*fall through*/
				case 3:
					*d++ = *s++;
					/*fall through*/
				case 2:
					*d++ = *s++;
					/*fall through*/
				case 1:
					*d++ = *s++;
					break;
				default:
					DEBUG(0,("check_path_syntax_internal: character length assumptions invalid !\n"));
					*d = '\0';
					return NT_STATUS_INVALID_PARAMETER;
			}
		}
		start_of_name_component = False;
	}

	*d = '\0';

	return ret;
}

/****************************************************************************
 Ensure we check the path in *exactly* the same way as W2K for regular pathnames.
 No wildcards allowed.
****************************************************************************/

NTSTATUS check_path_syntax(char *path)
{
	bool ignore;
	return check_path_syntax_internal(path, False, &ignore);
}

/****************************************************************************
 Ensure we check the path in *exactly* the same way as W2K for regular pathnames.
 Wildcards allowed - p_contains_wcard returns true if the last component contained
 a wildcard.
****************************************************************************/

NTSTATUS check_path_syntax_wcard(char *path, bool *p_contains_wcard)
{
	return check_path_syntax_internal(path, False, p_contains_wcard);
}

/****************************************************************************
 Check the path for a POSIX client.
 We're assuming here that '/' is not the second byte in any multibyte char
 set (a safe assumption).
****************************************************************************/

NTSTATUS check_path_syntax_posix(char *path)
{
	bool ignore;
	return check_path_syntax_internal(path, True, &ignore);
}

/****************************************************************************
 Pull a string and check the path allowing a wilcard - provide for error return.
****************************************************************************/

size_t srvstr_get_path_wcard(TALLOC_CTX *ctx,
			const char *base_ptr,
			uint16 smb_flags2,
			char **pp_dest,
			const char *src,
			size_t src_len,
			int flags,
			NTSTATUS *err,
			bool *contains_wcard)
{
	size_t ret;

	*pp_dest = NULL;

	ret = srvstr_pull_talloc(ctx, base_ptr, smb_flags2, pp_dest, src,
				 src_len, flags);

	if (!*pp_dest) {
		*err = NT_STATUS_INVALID_PARAMETER;
		return ret;
	}

	*contains_wcard = False;

	if (smb_flags2 & FLAGS2_DFS_PATHNAMES) {
		/*
		 * For a DFS path the function parse_dfs_path()
		 * will do the path processing, just make a copy.
		 */
		*err = NT_STATUS_OK;
		return ret;
	}

	if (lp_posix_pathnames()) {
		*err = check_path_syntax_posix(*pp_dest);
	} else {
		*err = check_path_syntax_wcard(*pp_dest, contains_wcard);
	}

	return ret;
}

/****************************************************************************
 Pull a string and check the path - provide for error return.
****************************************************************************/

size_t srvstr_get_path(TALLOC_CTX *ctx,
			const char *base_ptr,
			uint16 smb_flags2,
			char **pp_dest,
			const char *src,
			size_t src_len,
			int flags,
			NTSTATUS *err)
{
	bool ignore;
	return srvstr_get_path_wcard(ctx, base_ptr, smb_flags2, pp_dest, src,
				     src_len, flags, err, &ignore);
}

size_t srvstr_get_path_req_wcard(TALLOC_CTX *mem_ctx, struct smb_request *req,
				 char **pp_dest, const char *src, int flags,
				 NTSTATUS *err, bool *contains_wcard)
{
	return srvstr_get_path_wcard(mem_ctx, (char *)req->inbuf, req->flags2,
				     pp_dest, src, smbreq_bufrem(req, src),
				     flags, err, contains_wcard);
}

size_t srvstr_get_path_req(TALLOC_CTX *mem_ctx, struct smb_request *req,
			   char **pp_dest, const char *src, int flags,
			   NTSTATUS *err)
{
	bool ignore;
	return srvstr_get_path_req_wcard(mem_ctx, req, pp_dest, src,
					 flags, err, &ignore);
}

/****************************************************************************
 Check if we have a correct fsp pointing to a file. Basic check for open fsp.
****************************************************************************/

bool check_fsp_open(connection_struct *conn, struct smb_request *req,
		    files_struct *fsp)
{
	if (!(fsp) || !(conn)) {
		reply_nterror(req, NT_STATUS_INVALID_HANDLE);
		return False;
	}
	if (((conn) != (fsp)->conn) || req->vuid != (fsp)->vuid) {
		reply_nterror(req, NT_STATUS_INVALID_HANDLE);
		return False;
	}
	return True;
}

/****************************************************************************
 Check if we have a correct fsp pointing to a file.
****************************************************************************/

bool check_fsp(connection_struct *conn, struct smb_request *req,
	       files_struct *fsp)
{
	if (!check_fsp_open(conn, req, fsp)) {
		return False;
	}
	if ((fsp)->is_directory) {
		reply_nterror(req, NT_STATUS_INVALID_DEVICE_REQUEST);
		return False;
	}
	if ((fsp)->fh->fd == -1) {
		reply_nterror(req, NT_STATUS_ACCESS_DENIED);
		return False;
	}
	(fsp)->num_smb_operations++;
	return True;
}

/****************************************************************************
 Check if we have a correct fsp pointing to a quota fake file. Replacement for
 the CHECK_NTQUOTA_HANDLE_OK macro.
****************************************************************************/

bool check_fsp_ntquota_handle(connection_struct *conn, struct smb_request *req,
			      files_struct *fsp)
{
	if (!check_fsp_open(conn, req, fsp)) {
		return false;
	}

	if (fsp->is_directory) {
		return false;
	}

	if (fsp->fake_file_handle == NULL) {
		return false;
	}

	if (fsp->fake_file_handle->type != FAKE_FILE_TYPE_QUOTA) {
		return false;
	}

	if (fsp->fake_file_handle->private_data == NULL) {
		return false;
	}

	return true;
}

/****************************************************************************
 Check if we have a correct fsp. Replacement for the FSP_BELONGS_CONN macro
****************************************************************************/

bool fsp_belongs_conn(connection_struct *conn, struct smb_request *req,
		      files_struct *fsp)
{
	if ((fsp) && (conn) && ((conn)==(fsp)->conn)
	    && (req->vuid == (fsp)->vuid)) {
		return True;
	}

	reply_nterror(req, NT_STATUS_INVALID_HANDLE);
	return False;
}

static bool netbios_session_retarget(const char *name, int name_type)
{
	char *trim_name;
	char *trim_name_type;
	const char *retarget_parm;
	char *retarget;
	char *p;
	int retarget_type = 0x20;
	int retarget_port = 139;
	struct sockaddr_storage retarget_addr;
	struct sockaddr_in *in_addr;
	bool ret = false;
	uint8_t outbuf[10];

	if (get_socket_port(smbd_server_fd()) != 139) {
		return false;
	}

	trim_name = talloc_strdup(talloc_tos(), name);
	if (trim_name == NULL) {
		goto fail;
	}
	trim_char(trim_name, ' ', ' ');

	trim_name_type = talloc_asprintf(trim_name, "%s#%2.2x", trim_name,
					 name_type);
	if (trim_name_type == NULL) {
		goto fail;
	}

	retarget_parm = lp_parm_const_string(-1, "netbios retarget",
					     trim_name_type, NULL);
	if (retarget_parm == NULL) {
		retarget_parm = lp_parm_const_string(-1, "netbios retarget",
						     trim_name, NULL);
	}
	if (retarget_parm == NULL) {
		goto fail;
	}

	retarget = talloc_strdup(trim_name, retarget_parm);
	if (retarget == NULL) {
		goto fail;
	}

	DEBUG(10, ("retargeting %s to %s\n", trim_name_type, retarget));

	p = strchr(retarget, ':');
	if (p != NULL) {
		*p++ = '\0';
		retarget_port = atoi(p);
	}

	p = strchr_m(retarget, '#');
	if (p != NULL) {
		*p++ = '\0';
		sscanf(p, "%x", &retarget_type);
	}

	ret = resolve_name(retarget, &retarget_addr, retarget_type, false);
	if (!ret) {
		DEBUG(10, ("could not resolve %s\n", retarget));
		goto fail;
	}

	if (retarget_addr.ss_family != AF_INET) {
		DEBUG(10, ("Retarget target not an IPv4 addr\n"));
		goto fail;
	}

	in_addr = (struct sockaddr_in *)(void *)&retarget_addr;

	_smb_setlen(outbuf, 6);
	SCVAL(outbuf, 0, 0x84);
	*(uint32_t *)(outbuf+4) = in_addr->sin_addr.s_addr;
	*(uint16_t *)(outbuf+8) = htons(retarget_port);

	if (!srv_send_smb(smbd_server_fd(), (char *)outbuf, false, 0, false,
			  NULL)) {
		exit_server_cleanly("netbios_session_regarget: srv_send_smb "
				    "failed.");
	}

	ret = true;
 fail:
	TALLOC_FREE(trim_name);
	return ret;
}

/****************************************************************************
 Reply to a (netbios-level) special message.
****************************************************************************/

void reply_special(char *inbuf)
{
	int msg_type = CVAL(inbuf,0);
	int msg_flags = CVAL(inbuf,1);
	fstring name1,name2;
	char name_type1, name_type2;
	struct smbd_server_connection *sconn = smbd_server_conn;

	/*
	 * We only really use 4 bytes of the outbuf, but for the smb_setlen
	 * calculation & friends (srv_send_smb uses that) we need the full smb
	 * header.
	 */
	char outbuf[smb_size];

	*name1 = *name2 = 0;

	memset(outbuf, '\0', sizeof(outbuf));

	smb_setlen(outbuf,0);

	switch (msg_type) {
	case 0x81: /* session request */

		if (sconn->nbt.got_session) {
			exit_server_cleanly("multiple session request not permitted");
		}

		SCVAL(outbuf,0,0x82);
		SCVAL(outbuf,3,0);
		if (name_len(inbuf+4) > 50 || 
		    name_len(inbuf+4 + name_len(inbuf + 4)) > 50) {
			DEBUG(0,("Invalid name length in session request\n"));
			return;
		}
		name_type1 = name_extract(inbuf,4,name1);
		name_type2 = name_extract(inbuf,4 + name_len(inbuf + 4),name2);
		DEBUG(2,("netbios connect: name1=%s0x%x name2=%s0x%x\n",
			 name1, name_type1, name2, name_type2));

		if (netbios_session_retarget(name1, name_type1)) {
			exit_server_cleanly("retargeted client");
		}

		set_local_machine_name(name1, True);
		set_remote_machine_name(name2, True);

		DEBUG(2,("netbios connect: local=%s remote=%s, name type = %x\n",
			 get_local_machine_name(), get_remote_machine_name(),
			 name_type2));

		if (name_type2 == 'R') {
			/* We are being asked for a pathworks session --- 
			   no thanks! */
			SCVAL(outbuf, 0,0x83);
			break;
		}

		/* only add the client's machine name to the list
		   of possibly valid usernames if we are operating
		   in share mode security */
		if (lp_security() == SEC_SHARE) {
			add_session_user(sconn, get_remote_machine_name());
		}

		reload_services(True);
		reopen_logs();

		sconn->nbt.got_session = true;
		break;

	case 0x89: /* session keepalive request 
		      (some old clients produce this?) */
		SCVAL(outbuf,0,SMBkeepalive);
		SCVAL(outbuf,3,0);
		break;

	case 0x82: /* positive session response */
	case 0x83: /* negative session response */
	case 0x84: /* retarget session response */
		DEBUG(0,("Unexpected session response\n"));
		break;

	case SMBkeepalive: /* session keepalive */
	default:
		return;
	}

	DEBUG(5,("init msg_type=0x%x msg_flags=0x%x\n",
		    msg_type, msg_flags));

	srv_send_smb(smbd_server_fd(), outbuf, false, 0, false, NULL);
	return;
}

/****************************************************************************
 Reply to a tcon.
 conn POINTER CAN BE NULL HERE !
****************************************************************************/

void reply_tcon(struct smb_request *req)
{
	connection_struct *conn = req->conn;
	const char *service;
	char *service_buf = NULL;
	char *password = NULL;
	char *dev = NULL;
	int pwlen=0;
	NTSTATUS nt_status;
	const char *p;
	DATA_BLOB password_blob;
	TALLOC_CTX *ctx = talloc_tos();
	struct smbd_server_connection *sconn = smbd_server_conn;

	START_PROFILE(SMBtcon);

	if (req->buflen < 4) {
		reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
		END_PROFILE(SMBtcon);
		return;
	}

	p = (const char *)req->buf + 1;
	p += srvstr_pull_req_talloc(ctx, req, &service_buf, p, STR_TERMINATE);
	p += 1;
	pwlen = srvstr_pull_req_talloc(ctx, req, &password, p, STR_TERMINATE);
	p += pwlen+1;
	p += srvstr_pull_req_talloc(ctx, req, &dev, p, STR_TERMINATE);
	p += 1;

	if (service_buf == NULL || password == NULL || dev == NULL) {
		reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
		END_PROFILE(SMBtcon);
		return;
	}
	p = strrchr_m(service_buf,'\\');
	if (p) {
		service = p+1;
	} else {
		service = service_buf;
	}

	password_blob = data_blob(password, pwlen+1);

	conn = make_connection(sconn,service,password_blob,dev,
			       req->vuid,&nt_status);
	req->conn = conn;

	data_blob_clear_free(&password_blob);

	if (!conn) {
		reply_nterror(req, nt_status);
		END_PROFILE(SMBtcon);
		return;
	}

	reply_outbuf(req, 2, 0);
	SSVAL(req->outbuf,smb_vwv0,sconn->smb1.negprot.max_recv);
	SSVAL(req->outbuf,smb_vwv1,conn->cnum);
	SSVAL(req->outbuf,smb_tid,conn->cnum);

	DEBUG(3,("tcon service=%s cnum=%d\n",
		 service, conn->cnum));

	END_PROFILE(SMBtcon);
	return;
}

/****************************************************************************
 Reply to a tcon and X.
 conn POINTER CAN BE NULL HERE !
****************************************************************************/

void reply_tcon_and_X(struct smb_request *req)
{
	connection_struct *conn = req->conn;
	const char *service = NULL;
	DATA_BLOB password;
	TALLOC_CTX *ctx = talloc_tos();
	/* what the cleint thinks the device is */
	char *client_devicetype = NULL;
	/* what the server tells the client the share represents */
	const char *server_devicetype;
	NTSTATUS nt_status;
	int passlen;
	char *path = NULL;
	const char *p, *q;
	uint16 tcon_flags;
	struct smbd_server_connection *sconn = smbd_server_conn;

	START_PROFILE(SMBtconX);

	if (req->wct < 4) {
		reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
		END_PROFILE(SMBtconX);
		return;
	}

	passlen = SVAL(req->vwv+3, 0);
	tcon_flags = SVAL(req->vwv+2, 0);

	/* we might have to close an old one */
	if ((tcon_flags & 0x1) && conn) {
		close_cnum(conn,req->vuid);
		req->conn = NULL;
		conn = NULL;
	}

	if ((passlen > MAX_PASS_LEN) || (passlen >= req->buflen)) {
		reply_doserror(req, ERRDOS, ERRbuftoosmall);
		END_PROFILE(SMBtconX);
		return;
	}

	if (sconn->smb1.negprot.encrypted_passwords) {
		password = data_blob_talloc(talloc_tos(), req->buf, passlen);
		if (lp_security() == SEC_SHARE) {
			/*
			 * Security = share always has a pad byte
			 * after the password.
			 */
			p = (const char *)req->buf + passlen + 1;
		} else {
			p = (const char *)req->buf + passlen;
		}
	} else {
		password = data_blob_talloc(talloc_tos(), req->buf, passlen+1);
		/* Ensure correct termination */
		password.data[passlen]=0;
		p = (const char *)req->buf + passlen + 1;
	}

	p += srvstr_pull_req_talloc(ctx, req, &path, p, STR_TERMINATE);

	if (path == NULL) {
		data_blob_clear_free(&password);
		reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
		END_PROFILE(SMBtconX);
		return;
	}

	/*
	 * the service name can be either: \\server\share
	 * or share directly like on the DELL PowerVault 705
	 */
	if (*path=='\\') {
		q = strchr_m(path+2,'\\');
		if (!q) {
			data_blob_clear_free(&password);
			reply_doserror(req, ERRDOS, ERRnosuchshare);
			END_PROFILE(SMBtconX);
			return;
		}
		service = q+1;
	} else {
		service = path;
	}

	p += srvstr_pull_talloc(ctx, req->inbuf, req->flags2,
				&client_devicetype, p,
				MIN(6, smbreq_bufrem(req, p)), STR_ASCII);

	if (client_devicetype == NULL) {
		data_blob_clear_free(&password);
		reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
		END_PROFILE(SMBtconX);
		return;
	}

	DEBUG(4,("Client requested device type [%s] for share [%s]\n", client_devicetype, service));

	conn = make_connection(sconn, service, password, client_devicetype,
			       req->vuid, &nt_status);
	req->conn =conn;

	data_blob_clear_free(&password);

	if (!conn) {
		reply_nterror(req, nt_status);
		END_PROFILE(SMBtconX);
		return;
	}

	if ( IS_IPC(conn) )
		server_devicetype = "IPC";
	else if ( IS_PRINT(conn) )
		server_devicetype = "LPT1:";
	else
		server_devicetype = "A:";

	if (get_Protocol() < PROTOCOL_NT1) {
		reply_outbuf(req, 2, 0);
		if (message_push_string(&req->outbuf, server_devicetype,
					STR_TERMINATE|STR_ASCII) == -1) {
			reply_nterror(req, NT_STATUS_NO_MEMORY);
			END_PROFILE(SMBtconX);
			return;
		}
	} else {
		/* NT sets the fstype of IPC$ to the null string */
		const char *fstype = IS_IPC(conn) ? "" : lp_fstype(SNUM(conn));

		if (tcon_flags & TCONX_FLAG_EXTENDED_RESPONSE) {
			/* Return permissions. */
			uint32 perm1 = 0;
			uint32 perm2 = 0;

			reply_outbuf(req, 7, 0);

			if (IS_IPC(conn)) {
				perm1 = FILE_ALL_ACCESS;
				perm2 = FILE_ALL_ACCESS;
			} else {
				perm1 = CAN_WRITE(conn) ?
						SHARE_ALL_ACCESS :
						SHARE_READ_ONLY;
			}

			SIVAL(req->outbuf, smb_vwv3, perm1);
			SIVAL(req->outbuf, smb_vwv5, perm2);
		} else {
			reply_outbuf(req, 3, 0);
		}

		if ((message_push_string(&req->outbuf, server_devicetype,
					 STR_TERMINATE|STR_ASCII) == -1)
		    || (message_push_string(&req->outbuf, fstype,
					    STR_TERMINATE) == -1)) {
			reply_nterror(req, NT_STATUS_NO_MEMORY);
			END_PROFILE(SMBtconX);
			return;
		}

		/* what does setting this bit do? It is set by NT4 and
		   may affect the ability to autorun mounted cdroms */
		SSVAL(req->outbuf, smb_vwv2, SMB_SUPPORT_SEARCH_BITS|
		      (lp_csc_policy(SNUM(conn)) << 2));

		if (lp_msdfs_root(SNUM(conn)) && lp_host_msdfs()) {
			DEBUG(2,("Serving %s as a Dfs root\n",
				 lp_servicename(SNUM(conn)) ));
			SSVAL(req->outbuf, smb_vwv2,
			      SMB_SHARE_IN_DFS | SVAL(req->outbuf, smb_vwv2));
		}
	}


	DEBUG(3,("tconX service=%s \n",
		 service));

	/* set the incoming and outgoing tid to the just created one */
	SSVAL(req->inbuf,smb_tid,conn->cnum);
	SSVAL(req->outbuf,smb_tid,conn->cnum);

	END_PROFILE(SMBtconX);

	req->tid = conn->cnum;
	chain_reply(req);
	return;
}

/****************************************************************************
 Reply to an unknown type.
****************************************************************************/

void reply_unknown_new(struct smb_request *req, uint8 type)
{
	DEBUG(0, ("unknown command type (%s): type=%d (0x%X)\n",
		  smb_fn_name(type), type, type));
	reply_doserror(req, ERRSRV, ERRunknownsmb);
	return;
}

/****************************************************************************
 Reply to an ioctl.
 conn POINTER CAN BE NULL HERE !
****************************************************************************/

void reply_ioctl(struct smb_request *req)
{
	connection_struct *conn = req->conn;
	uint16 device;
	uint16 function;
	uint32 ioctl_code;
	int replysize;
	char *p;

	START_PROFILE(SMBioctl);

	if (req->wct < 3) {
		reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
		END_PROFILE(SMBioctl);
		return;
	}

	device     = SVAL(req->vwv+1, 0);
	function   = SVAL(req->vwv+2, 0);
	ioctl_code = (device << 16) + function;

	DEBUG(4, ("Received IOCTL (code 0x%x)\n", ioctl_code));

	switch (ioctl_code) {
	    case IOCTL_QUERY_JOB_INFO:
		    replysize = 32;
		    break;
	    default:
		    reply_doserror(req, ERRSRV, ERRnosupport);
		    END_PROFILE(SMBioctl);
		    return;
	}

	reply_outbuf(req, 8, replysize+1);
	SSVAL(req->outbuf,smb_vwv1,replysize); /* Total data bytes returned */
	SSVAL(req->outbuf,smb_vwv5,replysize); /* Data bytes this buffer */
	SSVAL(req->outbuf,smb_vwv6,52);        /* Offset to data */
	p = smb_buf(req->outbuf);
	memset(p, '\0', replysize+1); /* valgrind-safe. */
	p += 1;          /* Allow for alignment */

	switch (ioctl_code) {
		case IOCTL_QUERY_JOB_INFO:		    
		{
			files_struct *fsp = file_fsp(
				req, SVAL(req->vwv+0, 0));
			if (!fsp) {
				reply_doserror(req, ERRDOS, ERRbadfid);
				END_PROFILE(SMBioctl);
				return;
			}
			SSVAL(p,0,fsp->rap_print_jobid);             /* Job number */
			srvstr_push((char *)req->outbuf, req->flags2, p+2,
				    global_myname(), 15,
				    STR_TERMINATE|STR_ASCII);
			if (conn) {
				srvstr_push((char *)req->outbuf, req->flags2,
					    p+18, lp_servicename(SNUM(conn)),
					    13, STR_TERMINATE|STR_ASCII);
			} else {
				memset(p+18, 0, 13);
			}
			break;
		}
	}

	END_PROFILE(SMBioctl);
	return;
}

/****************************************************************************
 Strange checkpath NTSTATUS mapping.
****************************************************************************/

static NTSTATUS map_checkpath_error(uint16_t flags2, NTSTATUS status)
{
	/* Strange DOS error code semantics only for checkpath... */
	if (!(flags2 & FLAGS2_32_BIT_ERROR_CODES)) {
		if (NT_STATUS_EQUAL(NT_STATUS_OBJECT_NAME_INVALID,status)) {
			/* We need to map to ERRbadpath */
			return NT_STATUS_OBJECT_PATH_NOT_FOUND;
		}
	}
	return status;
}

/****************************************************************************
 Reply to a checkpath.
****************************************************************************/

void reply_checkpath(struct smb_request *req)
{
	connection_struct *conn = req->conn;
	struct smb_filename *smb_fname = NULL;
	char *name = NULL;
	NTSTATUS status;
	TALLOC_CTX *ctx = talloc_tos();

	START_PROFILE(SMBcheckpath);

	srvstr_get_path_req(ctx, req, &name, (const char *)req->buf + 1,
			    STR_TERMINATE, &status);

	if (!NT_STATUS_IS_OK(status)) {
		status = map_checkpath_error(req->flags2, status);
		reply_nterror(req, status);
		END_PROFILE(SMBcheckpath);
		return;
	}

	DEBUG(3,("reply_checkpath %s mode=%d\n", name, (int)SVAL(req->vwv+0, 0)));

	status = filename_convert(ctx,
				conn,
				req->flags2 & FLAGS2_DFS_PATHNAMES,
				name,
				0,
				NULL,
				&smb_fname);

	if (!NT_STATUS_IS_OK(status)) {
		if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
			reply_botherror(req, NT_STATUS_PATH_NOT_COVERED,
					ERRSRV, ERRbadpath);
			END_PROFILE(SMBcheckpath);
			return;
		}
		goto path_err;
	}

	if (!VALID_STAT(smb_fname->st) &&
	    (SMB_VFS_STAT(conn, smb_fname) != 0)) {
		DEBUG(3,("reply_checkpath: stat of %s failed (%s)\n",
			smb_fname_str_dbg(smb_fname), strerror(errno)));
		status = map_nt_error_from_unix(errno);
		goto path_err;
	}

	if (!S_ISDIR(smb_fname->st.st_ex_mode)) {
		reply_botherror(req, NT_STATUS_NOT_A_DIRECTORY,
				ERRDOS, ERRbadpath);
		goto out;
	}

	reply_outbuf(req, 0, 0);

 path_err:
	/* We special case this - as when a Windows machine
		is parsing a path is steps through the components
		one at a time - if a component fails it expects
		ERRbadpath, not ERRbadfile.
	*/
	status = map_checkpath_error(req->flags2, status);
	if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
		/*
		 * Windows returns different error codes if
		 * the parent directory is valid but not the
		 * last component - it returns NT_STATUS_OBJECT_NAME_NOT_FOUND
		 * for that case and NT_STATUS_OBJECT_PATH_NOT_FOUND
		 * if the path is invalid.
		 */
		reply_botherror(req, NT_STATUS_OBJECT_NAME_NOT_FOUND,
				ERRDOS, ERRbadpath);
		goto out;
	}

	reply_nterror(req, status);

 out:
	TALLOC_FREE(smb_fname);
	END_PROFILE(SMBcheckpath);
	return;
}

/****************************************************************************
 Reply to a getatr.
****************************************************************************/

void reply_getatr(struct smb_request *req)
{
	connection_struct *conn = req->conn;
	struct smb_filename *smb_fname = NULL;
	char *fname = NULL;
	int mode=0;
	SMB_OFF_T size=0;
	time_t mtime=0;
	const char *p;
	NTSTATUS status;
	TALLOC_CTX *ctx = talloc_tos();
	bool ask_sharemode = lp_parm_bool(SNUM(conn), "smbd", "search ask sharemode", true);

	START_PROFILE(SMBgetatr);

	p = (const char *)req->buf + 1;
	p += srvstr_get_path_req(ctx, req, &fname, p, STR_TERMINATE, &status);
	if (!NT_STATUS_IS_OK(status)) {
		reply_nterror(req, status);
		goto out;
	}

	/* dos smetimes asks for a stat of "" - it returns a "hidden directory"
		under WfWg - weird! */
	if (*fname == '\0') {
		mode = aHIDDEN | aDIR;
		if (!CAN_WRITE(conn)) {
			mode |= aRONLY;
		}
		size = 0;
		mtime = 0;
	} else {
		status = filename_convert(ctx,
				conn,
				req->flags2 & FLAGS2_DFS_PATHNAMES,
				fname,
				0,
				NULL,
				&smb_fname);
		if (!NT_STATUS_IS_OK(status)) {
			if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
				reply_botherror(req, NT_STATUS_PATH_NOT_COVERED,
						ERRSRV, ERRbadpath);
				goto out;
			}
			reply_nterror(req, status);
			goto out;
		}
		if (!VALID_STAT(smb_fname->st) &&
		    (SMB_VFS_STAT(conn, smb_fname) != 0)) {
			DEBUG(3,("reply_getatr: stat of %s failed (%s)\n",
				 smb_fname_str_dbg(smb_fname),
				 strerror(errno)));
			reply_nterror(req,  map_nt_error_from_unix(errno));
			goto out;
		}

		mode = dos_mode(conn, smb_fname);
		size = smb_fname->st.st_ex_size;

		if (ask_sharemode) {
			struct timespec write_time_ts;
			struct file_id fileid;

			ZERO_STRUCT(write_time_ts);
			fileid = vfs_file_id_from_sbuf(conn, &smb_fname->st);
			get_file_infos(fileid, NULL, &write_time_ts);
			if (!null_timespec(write_time_ts)) {
				update_stat_ex_mtime(&smb_fname->st, write_time_ts);
			}
		}

		mtime = convert_timespec_to_time_t(smb_fname->st.st_ex_mtime);
		if (mode & aDIR) {
			size = 0;
		}
	}

	reply_outbuf(req, 10, 0);

	SSVAL(req->outbuf,smb_vwv0,mode);
	if(lp_dos_filetime_resolution(SNUM(conn)) ) {
		srv_put_dos_date3((char *)req->outbuf,smb_vwv1,mtime & ~1);
	} else {
		srv_put_dos_date3((char *)req->outbuf,smb_vwv1,mtime);
	}
	SIVAL(req->outbuf,smb_vwv3,(uint32)size);

	if (get_Protocol() >= PROTOCOL_NT1) {
		SSVAL(req->outbuf, smb_flg2,
		      SVAL(req->outbuf, smb_flg2) | FLAGS2_IS_LONG_NAME);
	}

	DEBUG(3,("reply_getatr: name=%s mode=%d size=%u\n",
		 smb_fname_str_dbg(smb_fname), mode, (unsigned int)size));

 out:
	TALLOC_FREE(smb_fname);
	TALLOC_FREE(fname);
	END_PROFILE(SMBgetatr);
	return;
}

/****************************************************************************
 Reply to a setatr.
****************************************************************************/

void reply_setatr(struct smb_request *req)
{
	struct smb_file_time ft;
	connection_struct *conn = req->conn;
	struct smb_filename *smb_fname = NULL;
	char *fname = NULL;
	int mode;
	time_t mtime;
	const char *p;
	NTSTATUS status;
	TALLOC_CTX *ctx = talloc_tos();

	START_PROFILE(SMBsetatr);

	ZERO_STRUCT(ft);

	if (req->wct < 2) {
		reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
		goto out;
	}

	p = (const char *)req->buf + 1;
	p += srvstr_get_path_req(ctx, req, &fname, p, STR_TERMINATE, &status);
	if (!NT_STATUS_IS_OK(status)) {
		reply_nterror(req, status);
		goto out;
	}

	status = filename_convert(ctx,
				conn,
				req->flags2 & FLAGS2_DFS_PATHNAMES,
				fname,
				0,
				NULL,
				&smb_fname);
	if (!NT_STATUS_IS_OK(status)) {
		if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
			reply_botherror(req, NT_STATUS_PATH_NOT_COVERED,
					ERRSRV, ERRbadpath);
			goto out;
		}
		reply_nterror(req, status);
		goto out;
	}

	if (smb_fname->base_name[0] == '.' &&
	    smb_fname->base_name[1] == '\0') {
		/*
		 * Not sure here is the right place to catch this
		 * condition. Might be moved to somewhere else later -- vl
		 */
		reply_nterror(req, NT_STATUS_ACCESS_DENIED);
		goto out;
	}

	mode = SVAL(req->vwv+0, 0);
	mtime = srv_make_unix_date3(req->vwv+1);

	ft.mtime = convert_time_t_to_timespec(mtime);
	status = smb_set_file_time(conn, NULL, smb_fname, &ft, true);
	if (!NT_STATUS_IS_OK(status)) {
		reply_nterror(req, status);
		goto out;
	}

	if (mode != FILE_ATTRIBUTE_NORMAL) {
		if (VALID_STAT_OF_DIR(smb_fname->st))
			mode |= aDIR;
		else
			mode &= ~aDIR;

		if (file_set_dosmode(conn, smb_fname, mode, NULL,
				     false) != 0) {
			reply_nterror(req, map_nt_error_from_unix(errno));
			goto out;
		}
	}

	reply_outbuf(req, 0, 0);

	DEBUG(3, ("setatr name=%s mode=%d\n", smb_fname_str_dbg(smb_fname),
		 mode));
 out:
	TALLOC_FREE(smb_fname);
	END_PROFILE(SMBsetatr);
	return;
}

/****************************************************************************
 Reply to a dskattr.
****************************************************************************/

void reply_dskattr(struct smb_request *req)
{
	connection_struct *conn = req->conn;
	uint64_t dfree,dsize,bsize;
	START_PROFILE(SMBdskattr);

	if (get_dfree_info(conn,".",True,&bsize,&dfree,&dsize) == (uint64_t)-1) {
		reply_nterror(req, map_nt_error_from_unix(errno));
		END_PROFILE(SMBdskattr);
		return;
	}

	reply_outbuf(req, 5, 0);

	if (get_Protocol() <= PROTOCOL_LANMAN2) {
		double total_space, free_space;
		/* we need to scale this to a number that DOS6 can handle. We
		   use floating point so we can handle large drives on systems
		   that don't have 64 bit integers 

		   we end up displaying a maximum of 2G to DOS systems
		*/
		total_space = dsize * (double)bsize;
		free_space = dfree * (double)bsize;

		dsize = (uint64_t)((total_space+63*512) / (64*512));
		dfree = (uint64_t)((free_space+63*512) / (64*512));

		if (dsize > 0xFFFF) dsize = 0xFFFF;
		if (dfree > 0xFFFF) dfree = 0xFFFF;

		SSVAL(req->outbuf,smb_vwv0,dsize);
		SSVAL(req->outbuf,smb_vwv1,64); /* this must be 64 for dos systems */
		SSVAL(req->outbuf,smb_vwv2,512); /* and this must be 512 */
		SSVAL(req->outbuf,smb_vwv3,dfree);
	} else {
		SSVAL(req->outbuf,smb_vwv0,dsize);
		SSVAL(req->outbuf,smb_vwv1,bsize/512);
		SSVAL(req->outbuf,smb_vwv2,512);
		SSVAL(req->outbuf,smb_vwv3,dfree);
	}

	DEBUG(3,("dskattr dfree=%d\n", (unsigned int)dfree));

	END_PROFILE(SMBdskattr);
	return;
}

/*
 * Utility function to split the filename from the directory.
 */
static NTSTATUS split_fname_dir_mask(TALLOC_CTX *ctx, const char *fname_in,
				     char **fname_dir_out,
				     char **fname_mask_out)
{
	const char *p = NULL;
	char *fname_dir = NULL;
	char *fname_mask = NULL;

	p = strrchr_m(fname_in, '/');
	if (!p) {
		fname_dir = talloc_strdup(ctx, ".");
		fname_mask = talloc_strdup(ctx, fname_in);
	} else {
		fname_dir = talloc_strndup(ctx, fname_in,
		    PTR_DIFF(p, fname_in));
		fname_mask = talloc_strdup(ctx, p+1);
	}

	if (!fname_dir || !fname_mask) {
		TALLOC_FREE(fname_dir);
		TALLOC_FREE(fname_mask);
		return NT_STATUS_NO_MEMORY;
	}

	*fname_dir_out = fname_dir;
	*fname_mask_out = fname_mask;
	return NT_STATUS_OK;
}

/****************************************************************************
 Reply to a search.
 Can be called from SMBsearch, SMBffirst or SMBfunique.
****************************************************************************/

void reply_search(struct smb_request *req)
{
	connection_struct *conn = req->conn;
	char *path = NULL;
	const char *mask = NULL;
	char *directory = NULL;
	struct smb_filename *smb_fname = NULL;
	char *fname = NULL;
	SMB_OFF_T size;
	uint32 mode;
	struct timespec date;
	uint32 dirtype;
	unsigned int numentries = 0;
	unsigned int maxentries = 0;
	bool finished = False;
	const char *p;
	int status_len;
	char status[21];
	int dptr_num= -1;
	bool check_descend = False;
	bool expect_close = False;
	NTSTATUS nt_status;
	bool mask_contains_wcard = False;
	bool allow_long_path_components = (req->flags2 & FLAGS2_LONG_PATH_COMPONENTS) ? True : False;
	TALLOC_CTX *ctx = talloc_tos();
	bool ask_sharemode = lp_parm_bool(SNUM(conn), "smbd", "search ask sharemode", true);
	struct dptr_struct *dirptr = NULL;
	struct smbd_server_connection *sconn = smbd_server_conn;

	START_PROFILE(SMBsearch);

	if (req->wct < 2) {
		reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
		goto out;
	}

	if (lp_posix_pathnames()) {
		reply_unknown_new(req, req->cmd);
		goto out;
	}

	/* If we were called as SMBffirst then we must expect close. */
	if(req->cmd == SMBffirst) {
		expect_close = True;
	}

	reply_outbuf(req, 1, 3);
	maxentries = SVAL(req->vwv+0, 0);
	dirtype = SVAL(req->vwv+1, 0);
	p = (const char *)req->buf + 1;
	p += srvstr_get_path_req_wcard(ctx, req, &path, p, STR_TERMINATE,
				       &nt_status, &mask_contains_wcard);
	if (!NT_STATUS_IS_OK(nt_status)) {
		reply_nterror(req, nt_status);
		goto out;
	}

	p++;
	status_len = SVAL(p, 0);
	p += 2;

	/* dirtype &= ~aDIR; */

	if (status_len == 0) {
		nt_status = filename_convert(ctx, conn,
					     req->flags2 & FLAGS2_DFS_PATHNAMES,
					     path,
					     UCF_ALWAYS_ALLOW_WCARD_LCOMP,
					     &mask_contains_wcard,
					     &smb_fname);
		if (!NT_STATUS_IS_OK(nt_status)) {
			if (NT_STATUS_EQUAL(nt_status,NT_STATUS_PATH_NOT_COVERED)) {
				reply_botherror(req, NT_STATUS_PATH_NOT_COVERED,
						ERRSRV, ERRbadpath);
				goto out;
			}
			reply_nterror(req, nt_status);
			goto out;
		}

		directory = smb_fname->base_name;

		p = strrchr_m(directory,'/');
		if ((p != NULL) && (*directory != '/')) {
			mask = p + 1;
			directory = talloc_strndup(ctx, directory,
						   PTR_DIFF(p, directory));
		} else {
			mask = directory;
			directory = talloc_strdup(ctx,".");
		}

		if (!directory) {
			reply_nterror(req, NT_STATUS_NO_MEMORY);
			goto out;
		}

		memset((char *)status,'\0',21);
		SCVAL(status,0,(dirtype & 0x1F));

		nt_status = dptr_create(conn,
					directory,
					True,
					expect_close,
					req->smbpid,
					mask,
					mask_contains_wcard,
					dirtype,
					&dirptr);
		if (!NT_STATUS_IS_OK(nt_status)) {
			reply_nterror(req, nt_status);
			goto out;
		}
		dptr_num = dptr_dnum(dirptr);
	} else {
		int status_dirtype;
		const char *dirpath;

		memcpy(status,p,21);
		status_dirtype = CVAL(status,0) & 0x1F;
		if (status_dirtype != (dirtype & 0x1F)) {
			dirtype = status_dirtype;
		}

		dirptr = dptr_fetch(sconn, status+12,&dptr_num);
		if (!dirptr) {
			goto SearchEmpty;
		}
		dirpath = dptr_path(sconn, dptr_num);
		directory = talloc_strdup(ctx, dirpath);
		if (!directory) {
			reply_nterror(req, NT_STATUS_NO_MEMORY);
			goto out;
		}

		mask = dptr_wcard(sconn, dptr_num);
		if (!mask) {
			goto SearchEmpty;
		}
		/*
		 * For a 'continue' search we have no string. So
		 * check from the initial saved string.
		 */
		mask_contains_wcard = ms_has_wild(mask);
		dirtype = dptr_attr(sconn, dptr_num);
	}

	DEBUG(4,("dptr_num is %d\n",dptr_num));

	/* Initialize per SMBsearch/SMBffirst/SMBfunique operation data */
	dptr_init_search_op(dirptr);

	if ((dirtype&0x1F) == aVOLID) {
		char buf[DIR_STRUCT_SIZE];
		memcpy(buf,status,21);
		if (!make_dir_struct(ctx,buf,"???????????",volume_label(SNUM(conn)),
				0,aVOLID,0,!allow_long_path_components)) {
			reply_nterror(req, NT_STATUS_NO_MEMORY);
			goto out;
		}
		dptr_fill(sconn, buf+12,dptr_num);
		if (dptr_zero(buf+12) && (status_len==0)) {
			numentries = 1;
		} else {
			numentries = 0;
		}
		if (message_push_blob(&req->outbuf,
				      data_blob_const(buf, sizeof(buf)))
		    == -1) {
			reply_nterror(req, NT_STATUS_NO_MEMORY);
			goto out;
		}
	} else {
		unsigned int i;
		maxentries = MIN(
			maxentries,
			((BUFFER_SIZE -
			  ((uint8 *)smb_buf(req->outbuf) + 3 - req->outbuf))
			 /DIR_STRUCT_SIZE));

		DEBUG(8,("dirpath=<%s> dontdescend=<%s>\n",
			directory,lp_dontdescend(SNUM(conn))));
		if (in_list(directory, lp_dontdescend(SNUM(conn)),True)) {
			check_descend = True;
		}

		for (i=numentries;(i<maxentries) && !finished;i++) {
			finished = !get_dir_entry(ctx,
						  dirptr,
						  mask,
						  dirtype,
						  &fname,
						  &size,
						  &mode,
						  &date,
						  check_descend,
						  ask_sharemode);
			if (!finished) {
				char buf[DIR_STRUCT_SIZE];
				memcpy(buf,status,21);
				if (!make_dir_struct(ctx,
						buf,
						mask,
						fname,
						size,
						mode,
						convert_timespec_to_time_t(date),
						!allow_long_path_components)) {
					reply_nterror(req, NT_STATUS_NO_MEMORY);
					goto out;
				}
				if (!dptr_fill(sconn, buf+12,dptr_num)) {
					break;
				}
				if (message_push_blob(&req->outbuf,
						      data_blob_const(buf, sizeof(buf)))
				    == -1) {
					reply_nterror(req, NT_STATUS_NO_MEMORY);
					goto out;
				}
				numentries++;
			}
		}
	}

  SearchEmpty:

	/* If we were called as SMBffirst with smb_search_id == NULL
		and no entries were found then return error and close dirptr 
		(X/Open spec) */

	if (numentries == 0) {
		dptr_close(sconn, &dptr_num);
	} else if(expect_close && status_len == 0) {
		/* Close the dptr - we know it's gone */
		dptr_close(sconn, &dptr_num);
	}

	/* If we were called as SMBfunique, then we can close the dirptr now ! */
	if(dptr_num >= 0 && req->cmd == SMBfunique) {
		dptr_close(sconn, &dptr_num);
	}

	if ((numentries == 0) && !mask_contains_wcard) {
		reply_botherror(req, STATUS_NO_MORE_FILES, ERRDOS, ERRnofiles);
		goto out;
	}

	SSVAL(req->outbuf,smb_vwv0,numentries);
	SSVAL(req->outbuf,smb_vwv1,3 + numentries * DIR_STRUCT_SIZE);
	SCVAL(smb_buf(req->outbuf),0,5);
	SSVAL(smb_buf(req->outbuf),1,numentries*DIR_STRUCT_SIZE);

	/* The replies here are never long name. */
	SSVAL(req->outbuf, smb_flg2,
	      SVAL(req->outbuf, smb_flg2) & (~FLAGS2_IS_LONG_NAME));
	if (!allow_long_path_components) {
		SSVAL(req->outbuf, smb_flg2,
		      SVAL(req->outbuf, smb_flg2)
		      & (~FLAGS2_LONG_PATH_COMPONENTS));
	}

	/* This SMB *always* returns ASCII names. Remove the unicode bit in flags2. */
	SSVAL(req->outbuf, smb_flg2,
	      (SVAL(req->outbuf, smb_flg2) & (~FLAGS2_UNICODE_STRINGS)));

	DEBUG(4,("%s mask=%s path=%s dtype=%d nument=%u of %u\n",
		smb_fn_name(req->cmd),
		mask,
		directory,
		dirtype,
		numentries,
		maxentries ));
 out:
	TALLOC_FREE(directory);
	TALLOC_FREE(smb_fname);
	END_PROFILE(SMBsearch);
	return;
}

/****************************************************************************
 Reply to a fclose (stop directory search).
****************************************************************************/

void reply_fclose(struct smb_request *req)
{
	int status_len;
	char status[21];
	int dptr_num= -2;
	const char *p;
	char *path = NULL;
	NTSTATUS err;
	bool path_contains_wcard = False;
	TALLOC_CTX *ctx = talloc_tos();
	struct smbd_server_connection *sconn = smbd_server_conn;

	START_PROFILE(SMBfclose);

	if (lp_posix_pathnames()) {
		reply_unknown_new(req, req->cmd);
		END_PROFILE(SMBfclose);
		return;
	}

	p = (const char *)req->buf + 1;
	p += srvstr_get_path_req_wcard(ctx, req, &path, p, STR_TERMINATE,
				       &err, &path_contains_wcard);
	if (!NT_STATUS_IS_OK(err)) {
		reply_nterror(req, err);
		END_PROFILE(SMBfclose);
		return;
	}
	p++;
	status_len = SVAL(p,0);
	p += 2;

	if (status_len == 0) {
		reply_doserror(req, ERRSRV, ERRsrverror);
		END_PROFILE(SMBfclose);
		return;
	}

	memcpy(status,p,21);

	if(dptr_fetch(sconn, status+12,&dptr_num)) {
		/*  Close the dptr - we know it's gone */
		dptr_close(sconn, &dptr_num);
	}

	reply_outbuf(req, 1, 0);
	SSVAL(req->outbuf,smb_vwv0,0);

	DEBUG(3,("search close\n"));

	END_PROFILE(SMBfclose);
	return;
}

/****************************************************************************
 Reply to an open.
****************************************************************************/

void reply_open(struct smb_request *req)
{
	connection_struct *conn = req->conn;
	struct smb_filename *smb_fname = NULL;
	char *fname = NULL;
	uint32 fattr=0;
	SMB_OFF_T size = 0;
	time_t mtime=0;
	int info;
	files_struct *fsp;
	int oplock_request;
	int deny_mode;
	uint32 dos_attr;
	uint32 access_mask;
	uint32 share_mode;
	uint32 create_disposition;
	uint32 create_options = 0;
	NTSTATUS status;
	bool ask_sharemode = lp_parm_bool(SNUM(conn), "smbd", "search ask sharemode", true);
	TALLOC_CTX *ctx = talloc_tos();

	START_PROFILE(SMBopen);

	if (req->wct < 2) {
		reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
		goto out;
	}

	oplock_request = CORE_OPLOCK_REQUEST(req->inbuf);
	deny_mode = SVAL(req->vwv+0, 0);
	dos_attr = SVAL(req->vwv+1, 0);

	srvstr_get_path_req(ctx, req, &fname, (const char *)req->buf+1,
			    STR_TERMINATE, &status);
	if (!NT_STATUS_IS_OK(status)) {
		reply_nterror(req, status);
		goto out;
	}

	status = filename_convert(ctx,
				conn,
				req->flags2 & FLAGS2_DFS_PATHNAMES,
				fname,
				0,
				NULL,
				&smb_fname);
	if (!NT_STATUS_IS_OK(status)) {
		if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
			reply_botherror(req,
					NT_STATUS_PATH_NOT_COVERED,
					ERRSRV, ERRbadpath);
			goto out;
		}
		reply_nterror(req, status);
		goto out;
	}

	if (!map_open_params_to_ntcreate(smb_fname, deny_mode,
					 OPENX_FILE_EXISTS_OPEN, &access_mask,
					 &share_mode, &create_disposition,
					 &create_options)) {
		reply_nterror(req, NT_STATUS_DOS(ERRDOS, ERRbadaccess));
		goto out;
	}

	status = SMB_VFS_CREATE_FILE(
		conn,					/* conn */
		req,					/* req */
		0,					/* root_dir_fid */
		smb_fname,				/* fname */
		access_mask,				/* access_mask */
		share_mode,				/* share_access */
		create_disposition,			/* create_disposition*/
		create_options,				/* create_options */
		dos_attr,				/* file_attributes */
		oplock_request,				/* oplock_request */
		0,					/* allocation_size */
		NULL,					/* sd */
		NULL,					/* ea_list */
		&fsp,					/* result */
		&info);					/* pinfo */

	if (!NT_STATUS_IS_OK(status)) {
		if (open_was_deferred(req->mid)) {
			/* We have re-scheduled this call. */
			goto out;
		}
		reply_openerror(req, status);
		goto out;
	}

	size = smb_fname->st.st_ex_size;
	fattr = dos_mode(conn, smb_fname);

	/* Deal with other possible opens having a modified
	   write time. JRA. */
	if (ask_sharemode) {
		struct timespec write_time_ts;

		ZERO_STRUCT(write_time_ts);
		get_file_infos(fsp->file_id, NULL, &write_time_ts);
		if (!null_timespec(write_time_ts)) {
			update_stat_ex_mtime(&smb_fname->st, write_time_ts);
		}
	}

	mtime = convert_timespec_to_time_t(smb_fname->st.st_ex_mtime);

	if (fattr & aDIR) {
		DEBUG(3,("attempt to open a directory %s\n",
			 fsp_str_dbg(fsp)));
		close_file(req, fsp, ERROR_CLOSE);
		reply_doserror(req, ERRDOS,ERRnoaccess);
		goto out;
	}

	reply_outbuf(req, 7, 0);
	SSVAL(req->outbuf,smb_vwv0,fsp->fnum);
	SSVAL(req->outbuf,smb_vwv1,fattr);
	if(lp_dos_filetime_resolution(SNUM(conn)) ) {
		srv_put_dos_date3((char *)req->outbuf,smb_vwv2,mtime & ~1);
	} else {
		srv_put_dos_date3((char *)req->outbuf,smb_vwv2,mtime);
	}
	SIVAL(req->outbuf,smb_vwv4,(uint32)size);
	SSVAL(req->outbuf,smb_vwv6,deny_mode);

	if (oplock_request && lp_fake_oplocks(SNUM(conn))) {
		SCVAL(req->outbuf,smb_flg,
		      CVAL(req->outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
	}

	if(EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
		SCVAL(req->outbuf,smb_flg,
		      CVAL(req->outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
	}
 out:
	TALLOC_FREE(smb_fname);
	END_PROFILE(SMBopen);
	return;
}

/****************************************************************************
 Reply to an open and X.
****************************************************************************/

void reply_open_and_X(struct smb_request *req)
{
	connection_struct *conn = req->conn;
	struct smb_filename *smb_fname = NULL;
	char *fname = NULL;
	uint16 open_flags;
	int deny_mode;
	uint32 smb_attr;
	/* Breakout the oplock request bits so we can set the
		reply bits separately. */
	int ex_oplock_request;
	int core_oplock_request;
	int oplock_request;
#if 0
	int smb_sattr = SVAL(req->vwv+4, 0);
	uint32 smb_time = make_unix_date3(req->vwv+6);
#endif
	int smb_ofun;
	uint32 fattr=0;
	int mtime=0;
	int smb_action = 0;
	files_struct *fsp;
	NTSTATUS status;
	uint64_t allocation_size;
	ssize_t retval = -1;
	uint32 access_mask;
	uint32 share_mode;
	uint32 create_disposition;
	uint32 create_options = 0;
	TALLOC_CTX *ctx = talloc_tos();

	START_PROFILE(SMBopenX);

	if (req->wct < 15) {
		reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
		goto out;
	}

	open_flags = SVAL(req->vwv+2, 0);
	deny_mode = SVAL(req->vwv+3, 0);
	smb_attr = SVAL(req->vwv+5, 0);
	ex_oplock_request = EXTENDED_OPLOCK_REQUEST(req->inbuf);
	core_oplock_request = CORE_OPLOCK_REQUEST(req->inbuf);
	oplock_request = ex_oplock_request | core_oplock_request;
	smb_ofun = SVAL(req->vwv+8, 0);
	allocation_size = (uint64_t)IVAL(req->vwv+9, 0);

	/* If it's an IPC, pass off the pipe handler. */
	if (IS_IPC(conn)) {
		if (lp_nt_pipe_support()) {
			reply_open_pipe_and_X(conn, req);
		} else {
			reply_doserror(req, ERRSRV, ERRaccess);
		}
		goto out;
	}

	/* XXXX we need to handle passed times, sattr and flags */
	srvstr_get_path_req(ctx, req, &fname, (const char *)req->buf,
			STR_TERMINATE, &status);
	if (!NT_STATUS_IS_OK(status)) {
		reply_nterror(req, status);
		goto out;
	}

	status = filename_convert(ctx,
				conn,
				req->flags2 & FLAGS2_DFS_PATHNAMES,
				fname,
				0,
				NULL,
				&smb_fname);
	if (!NT_STATUS_IS_OK(status)) {
		if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
			reply_botherror(req,
					NT_STATUS_PATH_NOT_COVERED,
					ERRSRV, ERRbadpath);
			goto out;
		}
		reply_nterror(req, status);
		goto out;
	}

	if (!map_open_params_to_ntcreate(smb_fname, deny_mode, smb_ofun,
					 &access_mask, &share_mode,
					 &create_disposition,
					 &create_options)) {
		reply_nterror(req, NT_STATUS_DOS(ERRDOS, ERRbadaccess));
		goto out;
	}

	status = SMB_VFS_CREATE_FILE(
		conn,					/* conn */
		req,					/* req */
		0,					/* root_dir_fid */
		smb_fname,				/* fname */
		access_mask,				/* access_mask */
		share_mode,				/* share_access */
		create_disposition,			/* create_disposition*/
		create_options,				/* create_options */
		smb_attr,				/* file_attributes */
		oplock_request,				/* oplock_request */
		0,					/* allocation_size */
		NULL,					/* sd */
		NULL,					/* ea_list */
		&fsp,					/* result */
		&smb_action);				/* pinfo */

	if (!NT_STATUS_IS_OK(status)) {
		if (open_was_deferred(req->mid)) {
			/* We have re-scheduled this call. */
			goto out;
		}
		reply_openerror(req, status);
		goto out;
	}

	/* Setting the "size" field in vwv9 and vwv10 causes the file to be set to this size,
	   if the file is truncated or created. */
	if (((smb_action == FILE_WAS_CREATED) || (smb_action == FILE_WAS_OVERWRITTEN)) && allocation_size) {
		fsp->initial_allocation_size = smb_roundup(fsp->conn, allocation_size);
		if (vfs_allocate_file_space(fsp, fsp->initial_allocation_size) == -1) {
			close_file(req, fsp, ERROR_CLOSE);
			reply_nterror(req, NT_STATUS_DISK_FULL);
			goto out;
		}
		retval = vfs_set_filelen(fsp, (SMB_OFF_T)allocation_size);
		if (retval < 0) {
			close_file(req, fsp, ERROR_CLOSE);
			reply_nterror(req, NT_STATUS_DISK_FULL);
			goto out;
		}
		smb_fname->st.st_ex_size =
		    SMB_VFS_GET_ALLOC_SIZE(conn, fsp, &smb_fname->st);
	}

	fattr = dos_mode(conn, smb_fname);
	mtime = convert_timespec_to_time_t(smb_fname->st.st_ex_mtime);
	if (fattr & aDIR) {
		close_file(req, fsp, ERROR_CLOSE);
		reply_doserror(req, ERRDOS, ERRnoaccess);
		goto out;
	}

	/* If the caller set the extended oplock request bit
		and we granted one (by whatever means) - set the
		correct bit for extended oplock reply.
	*/

	if (ex_oplock_request && lp_fake_oplocks(SNUM(conn))) {
		smb_action |= EXTENDED_OPLOCK_GRANTED;
	}

	if(ex_oplock_request && EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
		smb_action |= EXTENDED_OPLOCK_GRANTED;
	}

	/* If the caller set the core oplock request bit
		and we granted one (by whatever means) - set the
		correct bit for core oplock reply.
	*/

	if (open_flags & EXTENDED_RESPONSE_REQUIRED) {
		reply_outbuf(req, 19, 0);
	} else {
		reply_outbuf(req, 15, 0);
	}

	if (core_oplock_request && lp_fake_oplocks(SNUM(conn))) {
		SCVAL(req->outbuf, smb_flg,
		      CVAL(req->outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
	}

	if(core_oplock_request && EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
		SCVAL(req->outbuf, smb_flg,
		      CVAL(req->outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
	}

	SSVAL(req->outbuf,smb_vwv2,fsp->fnum);
	SSVAL(req->outbuf,smb_vwv3,fattr);
	if(lp_dos_filetime_resolution(SNUM(conn)) ) {
		srv_put_dos_date3((char *)req->outbuf,smb_vwv4,mtime & ~1);
	} else {
		srv_put_dos_date3((char *)req->outbuf,smb_vwv4,mtime);
	}
	SIVAL(req->outbuf,smb_vwv6,(uint32)smb_fname->st.st_ex_size);
	SSVAL(req->outbuf,smb_vwv8,GET_OPENX_MODE(deny_mode));
	SSVAL(req->outbuf,smb_vwv11,smb_action);

	if (open_flags & EXTENDED_RESPONSE_REQUIRED) {
		SIVAL(req->outbuf, smb_vwv15, STD_RIGHT_ALL_ACCESS);
	}

	chain_reply(req);
 out:
	TALLOC_FREE(smb_fname);
	END_PROFILE(SMBopenX);
	return;
}

/****************************************************************************
 Reply to a SMBulogoffX.
****************************************************************************/

void reply_ulogoffX(struct smb_request *req)
{
	struct smbd_server_connection *sconn = smbd_server_conn;
	user_struct *vuser;

	START_PROFILE(SMBulogoffX);

	vuser = get_valid_user_struct(sconn, req->vuid);

	if(vuser == NULL) {
		DEBUG(3,("ulogoff, vuser id %d does not map to user.\n",
			 req->vuid));
	}

	/* in user level security we are supposed to close any files
		open by this user */
	if ((vuser != NULL) && (lp_security() != SEC_SHARE)) {
		file_close_user(req->vuid);
	}

	invalidate_vuid(sconn, req->vuid);

	reply_outbuf(req, 2, 0);

	DEBUG( 3, ( "ulogoffX vuid=%d\n", req->vuid ) );

	END_PROFILE(SMBulogoffX);
	req->vuid = UID_FIELD_INVALID;
	chain_reply(req);
}

/****************************************************************************
 Reply to a mknew or a create.
****************************************************************************/

void reply_mknew(struct smb_request *req)
{
	connection_struct *conn = req->conn;
	struct smb_filename *smb_fname = NULL;
	char *fname = NULL;
	uint32 fattr = 0;
	struct smb_file_time ft;
	files_struct *fsp;
	int oplock_request = 0;
	NTSTATUS status;
	uint32 access_mask = FILE_GENERIC_READ | FILE_GENERIC_WRITE;
	uint32 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
	uint32 create_disposition;
	uint32 create_options = 0;
	TALLOC_CTX *ctx = talloc_tos();

	START_PROFILE(SMBcreate);
	ZERO_STRUCT(ft);

        if (req->wct < 3) {
		reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
		goto out;
	}

	fattr = SVAL(req->vwv+0, 0);
	oplock_request = CORE_OPLOCK_REQUEST(req->inbuf);

	/* mtime. */
	ft.mtime = convert_time_t_to_timespec(srv_make_unix_date3(req->vwv+1));

	srvstr_get_path_req(ctx, req, &fname, (const char *)req->buf + 1,
			    STR_TERMINATE, &status);
	if (!NT_STATUS_IS_OK(status)) {
		reply_nterror(req, status);
		goto out;
	}

	status = filename_convert(ctx,
				conn,
				req->flags2 & FLAGS2_DFS_PATHNAMES,
				fname,
				0,
				NULL,
				&smb_fname);
	if (!NT_STATUS_IS_OK(status)) {
		if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
			reply_botherror(req,
					NT_STATUS_PATH_NOT_COVERED,
					ERRSRV, ERRbadpath);
			goto out;
		}
		reply_nterror(req, status);
		goto out;
	}

	if (fattr & aVOLID) {
		DEBUG(0,("Attempt to create file (%s) with volid set - "
			 "please report this\n",
			 smb_fname_str_dbg(smb_fname)));
	}

	if(req->cmd == SMBmknew) {
		/* We should fail if file exists. */
		create_disposition = FILE_CREATE;
	} else {
		/* Create if file doesn't exist, truncate if it does. */
		create_disposition = FILE_OVERWRITE_IF;
	}

	status = SMB_VFS_CREATE_FILE(
		conn,					/* conn */
		req,					/* req */
		0,					/* root_dir_fid */
		smb_fname,				/* fname */
		access_mask,				/* access_mask */
		share_mode,				/* share_access */
		create_disposition,			/* create_disposition*/
		create_options,				/* create_options */
		fattr,					/* file_attributes */
		oplock_request,				/* oplock_request */
		0,					/* allocation_size */
		NULL,					/* sd */
		NULL,					/* ea_list */
		&fsp,					/* result */
		NULL);					/* pinfo */

	if (!NT_STATUS_IS_OK(status)) {
		if (open_was_deferred(req->mid)) {
			/* We have re-scheduled this call. */
			goto out;
		}
		reply_openerror(req, status);
		goto out;
	}

	ft.atime = smb_fname->st.st_ex_atime; /* atime. */
	status = smb_set_file_time(conn, fsp, smb_fname, &ft, true);
	if (!NT_STATUS_IS_OK(status)) {
		END_PROFILE(SMBcreate);
		goto out;
	}

	reply_outbuf(req, 1, 0);
	SSVAL(req->outbuf,smb_vwv0,fsp->fnum);

	if (oplock_request && lp_fake_oplocks(SNUM(conn))) {
		SCVAL(req->outbuf,smb_flg,
				CVAL(req->outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
	}

	if(EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
		SCVAL(req->outbuf,smb_flg,
				CVAL(req->outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
	}

	DEBUG(2, ("reply_mknew: file %s\n", smb_fname_str_dbg(smb_fname)));
	DEBUG(3, ("reply_mknew %s fd=%d dmode=0x%x\n",
		  smb_fname_str_dbg(smb_fname), fsp->fh->fd,
		  (unsigned int)fattr));

 out:
	TALLOC_FREE(smb_fname);
	END_PROFILE(SMBcreate);
	return;
}

/****************************************************************************
 Reply to a create temporary file.
****************************************************************************/

void reply_ctemp(struct smb_request *req)
{
	connection_struct *conn = req->conn;
	struct smb_filename *smb_fname = NULL;
	char *fname = NULL;
	uint32 fattr;
	files_struct *fsp;
	int oplock_request;
	int tmpfd;
	char *s;
	NTSTATUS status;
	TALLOC_CTX *ctx = talloc_tos();

	START_PROFILE(SMBctemp);

	if (req->wct < 3) {
		reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
		goto out;
	}

	fattr = SVAL(req->vwv+0, 0);
	oplock_request = CORE_OPLOCK_REQUEST(req->inbuf);

	srvstr_get_path_req(ctx, req, &fname, (const char *)req->buf+1,
			    STR_TERMINATE, &status);
	if (!NT_STATUS_IS_OK(status)) {
		reply_nterror(req, status);
		goto out;
	}
	if (*fname) {
		fname = talloc_asprintf(ctx,
				"%s/TMXXXXXX",
				fname);
	} else {
		fname = talloc_strdup(ctx, "TMXXXXXX");
	}

	if (!fname) {
		reply_nterror(req, NT_STATUS_NO_MEMORY);
		goto out;
	}

	status = filename_convert(ctx, conn,
				req->flags2 & FLAGS2_DFS_PATHNAMES,
				fname,
				0,
				NULL,
				&smb_fname);
	if (!NT_STATUS_IS_OK(status)) {
		if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
			reply_botherror(req, NT_STATUS_PATH_NOT_COVERED,
					ERRSRV, ERRbadpath);
			goto out;
		}
		reply_nterror(req, status);
		goto out;
	}

	tmpfd = mkstemp(smb_fname->base_name);
	if (tmpfd == -1) {
		reply_nterror(req, map_nt_error_from_unix(errno));
		goto out;
	}

	SMB_VFS_STAT(conn, smb_fname);

	/* We should fail if file does not exist. */
	status = SMB_VFS_CREATE_FILE(
		conn,					/* conn */
		req,					/* req */
		0,					/* root_dir_fid */
		smb_fname,				/* fname */
		FILE_GENERIC_READ | FILE_GENERIC_WRITE, /* access_mask */
		FILE_SHARE_READ | FILE_SHARE_WRITE,	/* share_access */
		FILE_OPEN,				/* create_disposition*/
		0,					/* create_options */
		fattr,					/* file_attributes */
		oplock_request,				/* oplock_request */
		0,					/* allocation_size */
		NULL,					/* sd */
		NULL,					/* ea_list */
		&fsp,					/* result */
		NULL);					/* pinfo */

	/* close fd from mkstemp() */
	close(tmpfd);

	if (!NT_STATUS_IS_OK(status)) {
		if (open_was_deferred(req->mid)) {
			/* We have re-scheduled this call. */
			goto out;
		}
		reply_openerror(req, status);
		goto out;
	}

	reply_outbuf(req, 1, 0);
	SSVAL(req->outbuf,smb_vwv0,fsp->fnum);

	/* the returned filename is relative to the directory */
	s = strrchr_m(fsp->fsp_name->base_name, '/');
	if (!s) {
		s = fsp->fsp_name->base_name;
	} else {
		s++;
	}

#if 0
	/* Tested vs W2K3 - this doesn't seem to be here - null terminated filename is the only
	   thing in the byte section. JRA */
	SSVALS(p, 0, -1); /* what is this? not in spec */
#endif
	if (message_push_string(&req->outbuf, s, STR_ASCII|STR_TERMINATE)
	    == -1) {
		reply_nterror(req, NT_STATUS_NO_MEMORY);
		goto out;
	}

	if (oplock_request && lp_fake_oplocks(SNUM(conn))) {
		SCVAL(req->outbuf, smb_flg,
		      CVAL(req->outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
	}

	if (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
		SCVAL(req->outbuf, smb_flg,
		      CVAL(req->outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
	}

	DEBUG(2, ("reply_ctemp: created temp file %s\n", fsp_str_dbg(fsp)));
	DEBUG(3, ("reply_ctemp %s fd=%d umode=0%o\n", fsp_str_dbg(fsp),
		    fsp->fh->fd, (unsigned int)smb_fname->st.st_ex_mode));
 out:
	TALLOC_FREE(smb_fname);
	END_PROFILE(SMBctemp);
	return;
}

/*******************************************************************
 Check if a user is allowed to rename a file.
********************************************************************/

static NTSTATUS can_rename(connection_struct *conn, files_struct *fsp,
			   uint16 dirtype, SMB_STRUCT_STAT *pst)
{
	uint32 fmode;

	if (!CAN_WRITE(conn)) {
		return NT_STATUS_MEDIA_WRITE_PROTECTED;
	}

	fmode = dos_mode(conn, fsp->fsp_name);
	if ((fmode & ~dirtype) & (aHIDDEN | aSYSTEM)) {
		return NT_STATUS_NO_SUCH_FILE;
	}

	if (S_ISDIR(pst->st_ex_mode)) {
		if (fsp->posix_open) {
			return NT_STATUS_OK;
		}

		/* If no pathnames are open below this
		   directory, allow the rename. */

		if (file_find_subpath(fsp)) {
			return NT_STATUS_ACCESS_DENIED;
		}
		return NT_STATUS_OK;
	}

	if (fsp->access_mask & (DELETE_ACCESS|FILE_WRITE_ATTRIBUTES)) {
		return NT_STATUS_OK;
	}

	return NT_STATUS_ACCESS_DENIED;
}

/*******************************************************************
 * unlink a file with all relevant access checks
 *******************************************************************/

static NTSTATUS do_unlink(connection_struct *conn,
			struct smb_request *req,
			struct smb_filename *smb_fname,
			uint32 dirtype)
{
	uint32 fattr;
	files_struct *fsp;
	uint32 dirtype_orig = dirtype;
	NTSTATUS status;
	int ret;
	bool posix_paths = lp_posix_pathnames();

	DEBUG(10,("do_unlink: %s, dirtype = %d\n",
		  smb_fname_str_dbg(smb_fname),
		  dirtype));

	if (!CAN_WRITE(conn)) {
		return NT_STATUS_MEDIA_WRITE_PROTECTED;
	}

	if (posix_paths) {
		ret = SMB_VFS_LSTAT(conn, smb_fname);
	} else {
		ret = SMB_VFS_LSTAT(conn, smb_fname);
	}
	if (ret != 0) {
		return map_nt_error_from_unix(errno);
	}

	fattr = dos_mode(conn, smb_fname);

	if (dirtype & FILE_ATTRIBUTE_NORMAL) {
		dirtype = aDIR|aARCH|aRONLY;
	}

	dirtype &= (aDIR|aARCH|aRONLY|aHIDDEN|aSYSTEM);
	if (!dirtype) {
		return NT_STATUS_NO_SUCH_FILE;
	}

	if (!dir_check_ftype(conn, fattr, dirtype)) {
		if (fattr & aDIR) {
			return NT_STATUS_FILE_IS_A_DIRECTORY;
		}
		return NT_STATUS_NO_SUCH_FILE;
	}

	if (dirtype_orig & 0x8000) {
		/* These will never be set for POSIX. */
		return NT_STATUS_NO_SUCH_FILE;
	}

#if 0
	if ((fattr & dirtype) & FILE_ATTRIBUTE_DIRECTORY) {
                return NT_STATUS_FILE_IS_A_DIRECTORY;
        }

        if ((fattr & ~dirtype) & (FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM)) {
                return NT_STATUS_NO_SUCH_FILE;
        }

	if (dirtype & 0xFF00) {
		/* These will never be set for POSIX. */
		return NT_STATUS_NO_SUCH_FILE;
	}

	dirtype &= 0xFF;
	if (!dirtype) {
		return NT_STATUS_NO_SUCH_FILE;
	}

	/* Can't delete a directory. */
	if (fattr & aDIR) {
		return NT_STATUS_FILE_IS_A_DIRECTORY;
	}
#endif

#if 0 /* JRATEST */
	else if (dirtype & aDIR) /* Asked for a directory and it isn't. */
		return NT_STATUS_OBJECT_NAME_INVALID;
#endif /* JRATEST */

	/* Fix for bug #3035 from SATOH Fumiyasu <fumiyas@miraclelinux.com>

	  On a Windows share, a file with read-only dosmode can be opened with
	  DELETE_ACCESS. But on a Samba share (delete readonly = no), it
	  fails with NT_STATUS_CANNOT_DELETE error.

	  This semantic causes a problem that a user can not
	  rename a file with read-only dosmode on a Samba share
	  from a Windows command prompt (i.e. cmd.exe, but can rename
	  from Windows Explorer).
	*/

	if (!lp_delete_readonly(SNUM(conn))) {
		if (fattr & aRONLY) {
			return NT_STATUS_CANNOT_DELETE;
		}
	}

	/* On open checks the open itself will check the share mode, so
	   don't do it here as we'll get it wrong. */

	status = SMB_VFS_CREATE_FILE
		(conn,			/* conn */
		 req,			/* req */
		 0,			/* root_dir_fid */
		 smb_fname,		/* fname */
		 DELETE_ACCESS,		/* access_mask */
		 FILE_SHARE_NONE,	/* share_access */
		 FILE_OPEN,		/* create_disposition*/
		 FILE_NON_DIRECTORY_FILE, /* create_options */
		 			/* file_attributes */
		 posix_paths ? FILE_FLAG_POSIX_SEMANTICS|0777 :
				FILE_ATTRIBUTE_NORMAL,
		 0,			/* oplock_request */
		 0,			/* allocation_size */
		 NULL,			/* sd */
		 NULL,			/* ea_list */
		 &fsp,			/* result */
		 NULL);			/* pinfo */

	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(10, ("SMB_VFS_CREATEFILE failed: %s\n",
			   nt_errstr(status)));
		return status;
	}

	/* The set is across all open files on this dev/inode pair. */
	if (!set_delete_on_close(fsp, True, &conn->server_info->utok)) {
		close_file(req, fsp, NORMAL_CLOSE);
		return NT_STATUS_ACCESS_DENIED;
	}

	return close_file(req, fsp, NORMAL_CLOSE);
}

/****************************************************************************
 The guts of the unlink command, split out so it may be called by the NT SMB
 code.
****************************************************************************/

NTSTATUS unlink_internals(connection_struct *conn, struct smb_request *req,
			  uint32 dirtype, struct smb_filename *smb_fname,
			  bool has_wild)
{
	char *fname_dir = NULL;
	char *fname_mask = NULL;
	int count=0;
	NTSTATUS status = NT_STATUS_OK;
	TALLOC_CTX *ctx = talloc_tos();

	/* Split up the directory from the filename/mask. */
	status = split_fname_dir_mask(ctx, smb_fname->base_name,
				      &fname_dir, &fname_mask);
	if (!NT_STATUS_IS_OK(status)) {
		goto out;
	}

	/*
	 * We should only check the mangled cache
	 * here if unix_convert failed. This means
	 * that the path in 'mask' doesn't exist
	 * on the file system and so we need to look
	 * for a possible mangle. This patch from
	 * Tine Smukavec <valentin.smukavec@hermes.si>.
	 */

	if (!VALID_STAT(smb_fname->st) &&
	    mangle_is_mangled(fname_mask, conn->params)) {
		char *new_mask = NULL;
		mangle_lookup_name_from_8_3(ctx, fname_mask,
					    &new_mask, conn->params);
		if (new_mask) {
			TALLOC_FREE(fname_mask);
			fname_mask = new_mask;
		}
	}

	if (!has_wild) {

		/*
		 * Only one file needs to be unlinked. Append the mask back
		 * onto the directory.
		 */
		TALLOC_FREE(smb_fname->base_name);
		smb_fname->base_name = talloc_asprintf(smb_fname,
						       "%s/%s",
						       fname_dir,
						       fname_mask);
		if (!smb_fname->base_name) {
			status = NT_STATUS_NO_MEMORY;
			goto out;
		}
		if (dirtype == 0) {
			dirtype = FILE_ATTRIBUTE_NORMAL;
		}

		status = check_name(conn, smb_fname->base_name);
		if (!NT_STATUS_IS_OK(status)) {
			goto out;
		}

		status = do_unlink(conn, req, smb_fname, dirtype);
		if (!NT_STATUS_IS_OK(status)) {
			goto out;
		}

		count++;
	} else {
		struct smb_Dir *dir_hnd = NULL;
		long offset = 0;
		char *dname = NULL;

		if ((dirtype & SAMBA_ATTRIBUTES_MASK) == aDIR) {
			status = NT_STATUS_OBJECT_NAME_INVALID;
			goto out;
		}

		if (strequal(fname_mask,"????????.???")) {
			TALLOC_FREE(fname_mask);
			fname_mask = talloc_strdup(ctx, "*");
			if (!fname_mask) {
				status = NT_STATUS_NO_MEMORY;
				goto out;
			}
		}

		status = check_name(conn, fname_dir);
		if (!NT_STATUS_IS_OK(status)) {
			goto out;
		}

		dir_hnd = OpenDir(talloc_tos(), conn, fname_dir, fname_mask,
				  dirtype);
		if (dir_hnd == NULL) {
			status = map_nt_error_from_unix(errno);
			goto out;
		}

		/* XXXX the CIFS spec says that if bit0 of the flags2 field is set then
		   the pattern matches against the long name, otherwise the short name 
		   We don't implement this yet XXXX
		*/

		status = NT_STATUS_NO_SUCH_FILE;

		while ((dname = ReadDirName(dir_hnd, &offset,