summaryrefslogtreecommitdiff
path: root/open-vm-tools/services/plugins/dndcp/dnd/dndCommon.c
blob: 631236356922ed6948611732fc31819f2ccf3bca (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
/*********************************************************
 * Copyright (C) 2005-2015 VMware, Inc. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation version 2.1 and no 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 Lesser GNU General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA.
 *
 *********************************************************/

/*
 * dndCommon.c --
 *
 *     Implementation of bora/lib/public/dnd.h functions that are common to
 *     Linux and Windows platforms
 */


#include <stdlib.h>
#include <time.h>
#include <limits.h>

#include "vmware.h"
#include "dndInt.h"
#include "dnd.h"
#include "file.h"
#include "str.h"
#include "random.h"
#include "util.h"
#include "cpNameUtil.h"
#include "hgfsEscape.h"
#include "hgfsServerPolicy.h"
#include "hgfsVirtualDir.h"
#include "unicodeOperations.h"
#include "hostinfo.h"

#define LOGLEVEL_MODULE dnd
#include "loglevel_user.h"

#define WIN_DIRSEPC     '\\'
#define WIN_DIRSEPS     "\\"

static ConstUnicode DnDCreateRootStagingDirectory(void);

/*
 *-----------------------------------------------------------------------------
 *
 * DnD_CreateStagingDirectory --
 *
 *    Generate a unique staging directory name, create the directory, and
 *    return the name. The caller is responsible for freeing the returned
 *    string.
 *
 *    Our staging directory structure is comprised of a "root" staging
 *    directory that itself contains multiple staging directories that are
 *    intended to be used on a per-DnD and per-user basis.  That is, each DnD
 *    by a particular user will have its own staging directory within the root.
 *    Sometimes these directories are emptied after the DnD (either because it
 *    was cancelled or the destination application told us to), and we resuse
 *    any empty directories that we can.  This function will return a directory
 *    to be reused if possible and fall back on creating a new one if
 *    necessary.
 *
 * Results:
 *    A string containing the newly created name, or NULL on failure.
 *
 * Side effects:
 *    A directory is created
 *
 *-----------------------------------------------------------------------------
 */

Unicode
DnD_CreateStagingDirectory(void)
{
   ConstUnicode root;
   Unicode *stagingDirList;
   int numStagingDirs;
   int i;
   Unicode ret = NULL;
   Bool found = FALSE;

   /*
    * Make sure the root staging directory is created with the correct
    * permissions.
    */
   root = DnDCreateRootStagingDirectory();
   if (!root) {
      return NULL;
   }

   /* Look for an existing, empty staging directory */
   numStagingDirs = File_ListDirectory(root, &stagingDirList);
   if (numStagingDirs < 0) {
      goto exit;
   }

   for (i = 0; i < numStagingDirs; i++) {
      if (!found) {
         Unicode stagingDir;

         stagingDir = Unicode_Append(root, stagingDirList[i]);

         if (File_IsEmptyDirectory(stagingDir) &&
             DnDStagingDirectoryUsable(stagingDir)) {
               ret = Unicode_Append(stagingDir, DIRSEPS);
               /*
                * We can use this directory.  Make sure to continue to loop
                * so we don't leak the remaining stagindDirList[i]s.
                */
               found = TRUE;
         }

         Unicode_Free(stagingDir);
      }
   }

   Unicode_FreeList(stagingDirList, numStagingDirs);

   /* Only create a directory if we didn't find one above. */
   if (!found) {
      rqContext *context;

      context = Random_QuickSeed((unsigned)time(NULL));

      for (i = 0; i < 10; i++) {
         Unicode temp;

         /* Each staging directory is given a random name. */
         Unicode_Free(ret);
         temp = Unicode_Format("%08x%c", Random_Quick(context), DIRSEPC);
         VERIFY(temp);
         ret = Unicode_Append(root, temp);
         Unicode_Free(temp);

         if (File_CreateDirectory(ret) &&
             DnDSetPermissionsOnStagingDir(ret)) {
            found = TRUE;
            break;
         }
      }

      free(context);
   }

exit:
   if (!found && ret != NULL) {
      Unicode_Free(ret);
      ret = NULL;
   }

   return ret;
}


/*
 *-----------------------------------------------------------------------------
 *
 * DnD_DeleteStagingFiles --
 *
 *    Attempts to delete all files in the staging directory. This does not
 *    delete the directory itself.
 *
 * Results:
 *    TRUE if all files were deleted. FALSE if there was an error.
 *
 * Side effects:
 *    None
 *
 *-----------------------------------------------------------------------------
 */

Bool
DnD_DeleteStagingFiles(ConstUnicode stagingDir,  // IN:
                       Bool onReboot)            // IN:
{
   Bool ret = TRUE;

   ASSERT(stagingDir);

   if (!File_Exists(stagingDir)) {
      /* The stagingDir is already gone. */
      return TRUE;
   }

   if (!File_IsDirectory(stagingDir)) {
      return FALSE;
   }

   if (onReboot) {
      if (File_UnlinkDelayed(stagingDir)) {
         ret = FALSE;
      }
   } else {
      int i;
      int numFiles;
      Unicode base;
      Unicode *fileList = NULL;

      /* get list of files in current directory */
      numFiles = File_ListDirectory(stagingDir, &fileList);

      if (numFiles == -1) {
         return FALSE;
      }

      /* delete everything in the directory */
      base = Unicode_Append(stagingDir, DIRSEPS);

      for (i = 0; i < numFiles; i++) {
         Unicode curPath;

         curPath = Unicode_Append(base, fileList[i]);

         if (File_IsDirectory(curPath)) {
            if (!File_DeleteDirectoryTree(curPath)) {
               ret = FALSE;
            }
         } else {
            if (File_Unlink(curPath) == -1) {
               ret = FALSE;
            }
         }

         Unicode_Free(curPath);
      }

      Unicode_Free(base);
   }

   return ret;
}

/*
 *----------------------------------------------------------------------------
 *
 * DnDCreateRootStagingDirectory --
 *
 *    Checks if the root staging directory exists with the correct permissions,
 *    or creates it if necessary.
 *
 * Results:
 *    The path of the root directory on success, NULL on failure.
 *
 * Side effects:
 *    None.
 *
 *----------------------------------------------------------------------------
 */

static ConstUnicode
DnDCreateRootStagingDirectory(void)
{
   ConstUnicode root;

   /*
    * DnD_GetFileRoot() gives us a pointer to a static string, so there's no
    * need to free anything.
    */
   root = DnD_GetFileRoot();
   if (!root) {
      return NULL;
   }

   if (File_Exists(root)) {
      if (!DnDRootDirUsable(root) &&
          !DnDSetPermissionsOnRootDir(root)) {
         /*
          * The directory already exists and its permissions are wrong and
          * cannot be set, so there's not much we can do.
          */
         return NULL;
      }
   } else {
      if (!File_CreateDirectory(root) ||
          !DnDSetPermissionsOnRootDir(root)) {
         /* We couldn't create the directory or set the permissions. */
         return NULL;
      }
   }

   return root;
}


/*
 *----------------------------------------------------------------------------
 *
 * DnDPrependFileRoot --
 *
 *    Given a buffer of '\0' delimited filenames, this prepends the file root
 *    to each one and uses delimiter for delimiting the output buffer.  The
 *    buffer pointed to by *src will be freed and *src will point to a new
 *    buffer containing the results.  *srcSize is set to the size of the new
 *    buffer, not including the NUL-terminator.
 *
 *    The logic here and in the called functions appears to be UTF8-safe.
 *
 * Results:
 *    TRUE on success, FALSE on failure.
 *
 * Side effects:
 *    *src will be freed, and a new buffer will be allocated. This buffer must
 *    be freed by the caller.
 *
 *----------------------------------------------------------------------------
 */

Bool
DnDPrependFileRoot(ConstUnicode fileRoot,  // IN    : file root to append
                   char delimiter,         // IN    : delimiter for output buffer
                   char **src,             // IN/OUT: NUL-delimited list of paths
                   size_t *srcSize)        // IN/OUT: size of list
{
   char *newData = NULL;
   size_t newDataLen = 0;
   Bool firstPass = TRUE;
   const char *begin;
   const char *end;
   const char *next;
   size_t rootLen;
   int len;

   ASSERT(fileRoot);
   ASSERT(src);
   ASSERT(*src);
   ASSERT(srcSize);

   rootLen = strlen(fileRoot);

   /*
    * To prevent CPName_GetComponent() errors, we set begin to the first
    * Non-NUL character in *src, and end to the last NUL character in *src.  We
    * assume that the components are delimited with single NUL characters; if
    * that is not true, CPName_GetComponent() will fail.
    */

   for (begin = *src; *begin == '\0'; begin++)
      ;
   end = CPNameUtil_Strrchr(*src, *srcSize, '\0');

   /* Get the length of this component, and a pointer to the next */
   while ((len = CPName_GetComponent(begin, end, &next)) != 0) {
      size_t origNewDataLen = newDataLen;
      int escapedLen;

      if (len < 0) {
         Log("%s: error getting next component\n", __FUNCTION__);
         if (!firstPass) {
            free(newData);
         }

         return FALSE;
      }

      /*
       * Append this component to our list: allocate one more for NUL on first
       * pass and delimiter on all other passes.
       */

      escapedLen = HgfsEscape_GetSize(begin, len);
      if (escapedLen < 0) {
         Log("%s: error calculating buffer size\n", __FUNCTION__);
         return FALSE;
      } else if (0 == escapedLen) {
         newDataLen += rootLen + len + 1;
         newData = (char *)Util_SafeRealloc(newData, newDataLen);

         if (!firstPass) {
            ASSERT(origNewDataLen > 0);
            newData[origNewDataLen - 1] = delimiter;
         }
         memcpy(newData + origNewDataLen, fileRoot, rootLen);
         memcpy(newData + origNewDataLen + rootLen, begin, len);
      } else {
         newDataLen += rootLen + 1;
         newData = (char *)Util_SafeRealloc(newData, newDataLen);

         if (!firstPass) {
            ASSERT(origNewDataLen > 0);
            newData[origNewDataLen - 1] = delimiter;
         }
         memcpy(newData + origNewDataLen, fileRoot, rootLen);
         HgfsEscape_Do(begin, len, escapedLen, newData + origNewDataLen + rootLen);
      }
      newData[newDataLen - 1] = '\0';

      firstPass = FALSE;
      begin = next;
   }

   free(*src);
   *src = newData;
   /* Not including NUL terminator */
   *srcSize = newDataLen - 1;
   return TRUE;
}


/*
 *----------------------------------------------------------------------------
 *
 * DnD_LegacyConvertToCPName --
 *
 *    Converts paths received from older tools that do not send data in CPName
 *    format across the backdoor.  Older tools send paths in Windows format so
 *    this implementation must always convert from Windows path to CPName path,
 *    regardless of the platform we are running on.
 *
 *    The logic here and in the called functions appears to be UTF8-safe.
 *
 * Results:
 *    On success, returns the number of bytes used in the cross-platform name,
 *    NOT including the final terminating NUL character.  On failure, returns
 *    a negative error.
 *
 * Side effects:
 *    None.
 *
 *----------------------------------------------------------------------------
 */

int
DnD_LegacyConvertToCPName(const char *nameIn,   // IN:  Buffer to convert
                          size_t bufOutSize,    // IN:  Size of output buffer
                          char *bufOut)         // OUT: Output buffer
{
   const char partialName[] = HGFS_SERVER_POLICY_ROOT_SHARE_NAME;
   const size_t partialNameLen = HGFS_STR_LEN(HGFS_SERVER_POLICY_ROOT_SHARE_NAME);
   const char *partialNameSuffix = "";
   size_t partialNameSuffixLen;
   char *fullName;
   size_t fullNameSize;
   size_t nameSize;
   int result;

   ASSERT(nameIn);
   ASSERT(bufOut);

   /*
    * Create the full name. Note that Str_Asprintf should not be
    * used here as it uses FormatMessages which interprets 'data', a UTF-8
    * string, as a string in the current locale giving wrong results.
    */

   /*
    * Is this file path a UNC path?
    */
   if (nameIn[0] == WIN_DIRSEPC && nameIn[1] == WIN_DIRSEPC) {
      partialNameSuffix    = WIN_DIRSEPS HGFS_UNC_DIR_NAME WIN_DIRSEPS;
      partialNameSuffixLen = HGFS_STR_LEN(WIN_DIRSEPS) +
                             HGFS_STR_LEN(HGFS_UNC_DIR_NAME) +
                             HGFS_STR_LEN(WIN_DIRSEPS);
   } else {
      partialNameSuffix    = WIN_DIRSEPS HGFS_DRIVE_DIR_NAME WIN_DIRSEPS;
      partialNameSuffixLen = HGFS_STR_LEN(WIN_DIRSEPS) +
                             HGFS_STR_LEN(HGFS_DRIVE_DIR_NAME) +
                             HGFS_STR_LEN(WIN_DIRSEPS);
   }

   /* Skip any path separators at the beginning of the input string */
   while (*nameIn == WIN_DIRSEPC) {
      nameIn++;
   }

   nameSize = strlen(nameIn);
   fullNameSize = partialNameLen + partialNameSuffixLen + nameSize;
   fullName = (char *)Util_SafeMalloc(fullNameSize + 1);

   memcpy(fullName, partialName, partialNameLen);
   memcpy(fullName + partialNameLen, partialNameSuffix, partialNameSuffixLen);
   memcpy(fullName + partialNameLen + partialNameSuffixLen, nameIn, nameSize);
   fullName[fullNameSize] = '\0';

   LOG(4, ("%s: generated name is \"%s\"\n", __FUNCTION__, fullName));

   /*
    * CPName_ConvertTo implementation is performed here without calling any
    * CPName_ functions.  This is safer since those functions might change, but
    * the legacy behavior we are special casing here will not.
    */

   {
      char const *winNameIn = fullName;
      char const *origOut = bufOut;
      char const *endOut = bufOut + bufOutSize;
      char const pathSep = WIN_DIRSEPC;
      char *ignores = ":";

      /* Skip any path separators at the beginning of the input string */
      while (*winNameIn == pathSep) {
         winNameIn++;
      }

      /*
       * Copy the string to the output buf, converting all path separators into
       * '\0' and ignoring the specified characters.
       */

      for (; *winNameIn != '\0' && bufOut < endOut; winNameIn++) {
         if (ignores) {
            char *currIgnore = ignores;
            Bool ignore = FALSE;

            while (*currIgnore != '\0') {
               if (*winNameIn == *currIgnore) {
                  ignore = TRUE;
                  break;
               }
               currIgnore++;
            }

            if (!ignore) {
               *bufOut = (*winNameIn == pathSep) ? '\0' : *winNameIn;
               bufOut++;
            }
         } else {
            *bufOut = (*winNameIn == pathSep) ? '\0' : *winNameIn;
            bufOut++;
         }
      }

      /*
       * NUL terminate. XXX This should go away.
       *
       * When we get rid of NUL termination here, this test should
       * also change to "if (*winNameIn != '\0')".
       */

      if (bufOut == endOut) {
         result = -1;
         goto out;
      }
      *bufOut = '\0';

      /* Path name size should not require more than 4 bytes. */
      ASSERT((bufOut - origOut) <= 0xFFFFFFFF);

      /* If there were any trailing path separators, dont count them [krishnan] */
      result = (int)(bufOut - origOut);
      while ((result >= 1) && (origOut[result - 1] == 0)) {
         result--;
      }

      /*
       * Make exception and call CPName_Print() here, since it's only for
       * logging
       */

      LOG(4, ("%s: CPName is \"%s\"\n", __FUNCTION__, 
              CPName_Print(origOut, result)));
   }

out:
   free(fullName);

   return result;
}


/*
 *-----------------------------------------------------------------------------
 *
 * DnD_CPNameListToDynBufArray --
 *
 *    Export CPName file list from binary buffer to DynBufArray.
 *
 * Results:
 *    TRUE if success, FALSE otherwise.
 *
 * Side effects:
 *    Memory may allocated for DynBufArray if success.
 *
 *-----------------------------------------------------------------------------
 */

Bool
DnD_CPNameListToDynBufArray(char *fileList,           // IN: CPName format
                            size_t listSize,          // IN
                            DynBufArray *dynBufArray) // OUT
{
   DynBuf buf;
   BufRead r;
   int32 pathLen;
   size_t count;
   size_t i;

   ASSERT(fileList);
   r.pos = fileList;
   r.unreadLen = listSize;

   DynBufArray_Init(dynBufArray, 0);

   while (r.unreadLen > 0) {
      DynBuf_Init(&buf);
      if (!DnDReadBuffer(&r, &pathLen, sizeof pathLen) ||
          (pathLen > r.unreadLen) ||
          !DynBuf_Append(&buf, r.pos, pathLen)) {
         goto error;
      }

      if (!DnDSlideBuffer(&r, pathLen)) {
         goto error;
      }

      if (!DynBufArray_Push(dynBufArray, buf)) {
         goto error;
      }
   }
   return TRUE;

error:
   DynBuf_Destroy(&buf);

   count = DynBufArray_Count(dynBufArray);
   for (i = 0; i < count; i++) {
      DynBuf *b = DynArray_AddressOf(dynBufArray, i);
      DynBuf_Destroy(b);
   }
   DynBufArray_SetCount(dynBufArray, 0);
   DynBufArray_Destroy(dynBufArray);
   return FALSE;
}


/*
 *-----------------------------------------------------------------------------
 *
 * DnD_GetLastDirName --
 *
 *    Try to get last directory name from a full path name.
 *
 * Results:
 *    The allocated Unicode string, or NULL on failure.
 *
 * Side effects:
 *    None.
 *
 *-----------------------------------------------------------------------------
 */

Unicode
DnD_GetLastDirName(ConstUnicode str) // IN
{
   size_t end = strlen(str);
   size_t start;
   size_t res = 0;

   if (end != 0 && DIRSEPC == str[end - 1]) {
      end--;
   }

   if (end == 0) {
      return 0;
   }

   start = end;

   while (start && DIRSEPC != str[start - 1]) {
      start--;
   }

   /* There should be at lease 1 DIRSEPC before end. */
   if (start == 0) {
      return 0;
   }

   res = end - start;
   return Unicode_AllocWithLength(str + start, res, STRING_ENCODING_UTF8);
}


/* Transport layer big buffer support functions. */

/*
 *-----------------------------------------------------------------------------
 *
 * DnD_TransportBufInit --
 *
 *    Initialize transport layer buffer with DnD message.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    Buffer memory is allocated.
 *
 *-----------------------------------------------------------------------------
 */

void
DnD_TransportBufInit(DnDTransportBuffer *buf, // OUT
                     uint8 *msg,              // IN
                     size_t msgSize,          // IN
                     uint32 seqNum)           // IN
{
   ASSERT(buf);
   ASSERT(msgSize <= DNDMSG_MAX_ARGSZ);

   free(buf->buffer);
   buf->buffer = Util_SafeMalloc(msgSize);
   memcpy(buf->buffer, msg, msgSize);
   buf->seqNum = seqNum;
   buf->totalSize = msgSize;
   buf->offset = 0;
}


/*
 *-----------------------------------------------------------------------------
 *
 * DnD_TransportBufReset --
 *
 *    Reset transport layer buffer.
 *
 * Results:
 *    None.
 *
 * Side effects:
 *    None.
 *
 *-----------------------------------------------------------------------------
 */

void
DnD_TransportBufReset(DnDTransportBuffer *buf) // IN/OUT
{
   ASSERT(buf);

   free(buf->buffer);
   buf->buffer = NULL;

   buf->seqNum = 0;
   buf->totalSize = 0;
   buf->offset = 0;
   buf->lastUpdateTime = 0;
}


/*
 *-----------------------------------------------------------------------------
 *
 * DnD_TransportBufGetPacket --
 *
 *    Get a transport layer packet from transport layer buffer.
 *
 * Results:
 *    Transport layer packet size, or 0 if failed.
 *
 * Side effects:
 *    Memory may be allocated for packet.
 *
 *-----------------------------------------------------------------------------
 */

size_t
DnD_TransportBufGetPacket(DnDTransportBuffer *buf,           // IN/OUT
                          DnDTransportPacketHeader **packet) // OUT
{
   size_t payloadSize;

   ASSERT(buf);

   if (buf->totalSize < buf->offset) {
      return 0;
   }

   if ((buf->totalSize - buf->offset) > DND_MAX_TRANSPORT_PACKET_PAYLOAD_SIZE) {
      payloadSize = DND_MAX_TRANSPORT_PACKET_PAYLOAD_SIZE;
   } else {
      payloadSize = buf->totalSize - buf->offset;
   }

   *packet = (DnDTransportPacketHeader *)Util_SafeMalloc(
      payloadSize + DND_TRANSPORT_PACKET_HEADER_SIZE);
   (*packet)->type = DND_TRANSPORT_PACKET_TYPE_PAYLOAD;
   (*packet)->seqNum = buf->seqNum;
   (*packet)->totalSize = buf->totalSize;
   (*packet)->payloadSize = payloadSize;
   (*packet)->offset = buf->offset;

   memcpy((*packet)->payload,
          buf->buffer + buf->offset,
          payloadSize);
   buf->offset += payloadSize;

   /* This time is used for timeout purpose. */
   buf->lastUpdateTime = Hostinfo_SystemTimerUS();

   return payloadSize + DND_TRANSPORT_PACKET_HEADER_SIZE;
}


/*
 *-----------------------------------------------------------------------------
 *
 * DnD_TransportBufAppendPacket --
 *
 *    Put a received packet into transport layer buffer.
 *
 * Results:
 *    TRUE if success, FALSE otherwise.
 *
 * Side effects:
 *    Memory may be allocated for transport layer buffer.
 *
 *-----------------------------------------------------------------------------
 */

Bool
DnD_TransportBufAppendPacket(DnDTransportBuffer *buf,          // IN/OUT
                             DnDTransportPacketHeader *packet, // IN
                             size_t packetSize)                // IN
{
   ASSERT(buf);
   ASSERT(packetSize == (packet->payloadSize + DND_TRANSPORT_PACKET_HEADER_SIZE) &&
          packetSize <= DND_MAX_TRANSPORT_PACKET_SIZE &&
          (packet->payloadSize + packet->offset) <= packet->totalSize &&
          packet->totalSize <= DNDMSG_MAX_ARGSZ);

   if (packetSize != (packet->payloadSize + DND_TRANSPORT_PACKET_HEADER_SIZE) ||
       packetSize > DND_MAX_TRANSPORT_PACKET_SIZE ||
       (packet->payloadSize + packet->offset) > packet->totalSize ||
       packet->totalSize > DNDMSG_MAX_ARGSZ) {
      goto error;
   }

   /*
    * If seqNum does not match, it means either this is the first packet, or there
    * is a timeout in another side. Reset the buffer in all cases.
    */
   if (buf->seqNum != packet->seqNum) {
      DnD_TransportBufReset(buf);
   }

   if (!buf->buffer) {
      ASSERT(!packet->offset);
      if (packet->offset) {
         goto error;
      }
      buf->buffer = Util_SafeMalloc(packet->totalSize);
      buf->totalSize = packet->totalSize;
      buf->seqNum = packet->seqNum;
      buf->offset = 0;
   }

   if (buf->offset != packet->offset) {
      goto error;
   }

   memcpy(buf->buffer + buf->offset,
          packet->payload,
          packet->payloadSize);
   buf->offset += packet->payloadSize;
   return TRUE;

error:
   DnD_TransportBufReset(buf);
   return FALSE;
}


/*
 *-----------------------------------------------------------------------------
 *
 * DnD_TransportMsgToPacket --
 *
 *    Get a packet from small size message.
 *
 * Results:
 *    Transport layer packet size, or 0 if failed.
 *
 * Side effects:
 *    Memory may be allocated for packet.
 *
 *-----------------------------------------------------------------------------
 */

size_t
DnD_TransportMsgToPacket(uint8 *msg,                        // IN
                         size_t msgSize,                    // IN
                         uint32 seqNum,                     // IN
                         DnDTransportPacketHeader **packet) // OUT
{
   size_t packetSize;

   ASSERT(msgSize > 0 && msgSize <= DND_MAX_TRANSPORT_PACKET_PAYLOAD_SIZE);
   ASSERT(msg);
   ASSERT(packet);

   if (msgSize <=0 ||
       msgSize > DND_MAX_TRANSPORT_PACKET_PAYLOAD_SIZE ||
       !msg || !packet) {
      return 0;
   }

   packetSize = msgSize + DND_TRANSPORT_PACKET_HEADER_SIZE;

   *packet = (DnDTransportPacketHeader *)Util_SafeMalloc(packetSize);

   (*packet)->type = DND_TRANSPORT_PACKET_TYPE_SINGLE;
   (*packet)->seqNum = seqNum;
   (*packet)->totalSize = msgSize;
   (*packet)->payloadSize = msgSize;
   (*packet)->offset = 0;

   memcpy((*packet)->payload, msg, msgSize);

   return packetSize;
}


/*
 *-----------------------------------------------------------------------------
 *
 * DnD_TransportReqPacket --
 *
 *    Generate a request packet with empty payload. After got a payload, receive
 *    side should send a DND_TRANSPORT_PACKET_TYPE_REQUEST packet to ask for
 *    next payload packet.
 *
 * Results:
 *    Transport layer packet size.
 *
 * Side effects:
 *    Memory is allocated for packet.
 *
 *-----------------------------------------------------------------------------
 */

size_t
DnD_TransportReqPacket(DnDTransportBuffer *buf,           // IN
                       DnDTransportPacketHeader **packet) // OUT
{
   *packet = (DnDTransportPacketHeader *)Util_SafeMalloc(
      DND_TRANSPORT_PACKET_HEADER_SIZE);

   (*packet)->type = DND_TRANSPORT_PACKET_TYPE_REQUEST;
   (*packet)->seqNum = buf->seqNum;
   (*packet)->totalSize = buf->totalSize;
   (*packet)->payloadSize = 0;
   (*packet)->offset = buf->offset;
   return DND_TRANSPORT_PACKET_HEADER_SIZE;
}


/*
 *----------------------------------------------------------------------------
 *
 * DnDReadBuffer --
 *
 *      Copies len bytes of data from b to out. Subsequent calls to this
 *      function will copy data from the last unread point.
 *
 * Results:
 *      TRUE when data is successfully copies to out, FALSE otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

Bool
DnDReadBuffer(BufRead *b,       // IN/OUT: buffer to read from
              void *out,        // OUT: the output buffer
              size_t len)       // IN: the amount to read
{
   ASSERT(b);
   ASSERT(out);

   if (len > b->unreadLen) {
      return FALSE;
   }

   memcpy(out, b->pos, len);
   if (!DnDSlideBuffer(b, len)) {
      return FALSE;
   }

   return TRUE;
}


/*
 *----------------------------------------------------------------------------
 *
 * DnDSlideBuffer --
 *
 *      Ignore len bytes of data in b. Subsequent calls to DnDReadBuffer will
 *      copy data from the last point.
 *
 * Results:
 *      TRUE when pos is successfully changed, FALSE otherwise.
 *
 * Side effects:
 *      None.
 *
 *----------------------------------------------------------------------------
 */

Bool
DnDSlideBuffer(BufRead *b, // IN/OUT: buffer to read from
               size_t len) // IN: the amount to read
{
   ASSERT(b);

   if (len > b->unreadLen) {
      return FALSE;
   }

   b->pos += len;
   b->unreadLen -= len;

   return TRUE;
}