singularity /base/Applications/TftpClient/tftp.cs

Language C# Lines 392
MD5 Hash e6e584b36544eaa0a70d286f0c7c8c45 Estimated Cost $8,408 (why?)
Repository https://singularity.svn.codeplex.com/svn View Raw File
  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
///////////////////////////////////////////////////////////////////////////////
//
//  Microsoft Research Singularity
//
//  Copyright (c) Microsoft Corporation.  All rights reserved.
//
//  Note:
//

using System;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;

using Microsoft.Singularity;
using Microsoft.Singularity.Directory;
using Microsoft.Singularity.Channels;
using Microsoft.Singularity.FileSystem;
using Microsoft.Singularity.V1.Services;

using FileSystem.Utils;

namespace Microsoft.Singularity.Applications
{
    internal enum TftpOpcode : ushort
    {
        RRQ=1, WRQ=2, DATA=3, ACK=4, ERROR=5
    };

    internal struct TftpHdr
    {
        public TftpOpcode Opcode;
        public ushort Arg;

        public TftpHdr(byte[]! buffer, int offset)
        {
            Opcode = (TftpOpcode)((ushort)buffer[offset+0] << 8 | buffer[offset+1]);
            Arg    = (ushort)((ushort)buffer[offset+2] << 8 | buffer[offset+3]);
            //              UnMarshal(buffer, offset);
        }
        public void Marshal(byte[]! buffer, int offset)
        {
            buffer[offset+0] = (byte)((ushort)Opcode>>8 & 0xff);
            buffer[offset+1] = (byte)((ushort)Opcode>>0 & 0xff);
            buffer[offset+2] = (byte)(Arg>>8 & 0xff);
            buffer[offset+3] = (byte)(Arg>>0 & 0xff);
        }
        public void UnMarshal(byte[]! buffer, int offset)
        {
            Opcode = (TftpOpcode)((ushort)buffer[offset+0] << 8 | buffer[offset+1]);
            Arg    = (ushort)((ushort)buffer[offset+2] << 8 | buffer[offset+3]);
        }
    };

     public class TftpClient
    {
        Socket! s;

        public TftpClient(IPAddress! server)
        {
            Socket s = this.s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint ep = new System.Net.IPEndPoint(server, 69);
            Console.Write("EP= {0}\n", ep);
            // Connect here
            s.Connect(ep);
        }

        static int BuildRequest(byte[]! packet, TftpOpcode op, string! filename)
        {
            TftpHdr hdr = new TftpHdr();
            byte[] tmp;

            hdr.Opcode = op;
            hdr.Marshal(packet, 0);
            int off = 2;
            tmp = Encoding.ASCII.GetBytes(filename);
            tmp.CopyTo(packet, off);
            off += tmp.Length;
            packet[off++] = 0;
            tmp = Encoding.ASCII.GetBytes("octet");
            tmp.CopyTo(packet, off);
            off += tmp.Length;
            packet[off++] = 0;
            Console.WriteLine("Done");
            return off;
        }

        public string Get(string! filename, string localName, bool verboseMode)
        {
            TftpHdr hdr = new TftpHdr();
            byte[] request;
            byte[] reply = new byte[8192];
            int success;
            FileContract.Imp persistHandle = null ;
            long curPos = 0 ;
            int len;
            int rc;

            if (null != localName) {
                Console.WriteLine ("Creating file "+localName);
                success = FileUtils.CreateFile(localName);
                if (0 == success) {
                    persistHandle = FileUtils.OpenFile(localName);
                    if (null == persistHandle) {
                        Console.WriteLine("unable to open file " + localName);
                        return "";
                    }
                }
                else {
                    Console.WriteLine("unable to create file " + localName);
                    return "";
                }
            }

            request = new byte[4 + 512];

            len = BuildRequest(request, TftpOpcode.RRQ, filename);
            bool done = false;
            hdr.UnMarshal(request, 0);
            rc = s.Send(request, len, SocketFlags.None);
            if (verboseMode) Console.WriteLine("Sent RRQ rc={0}", rc);

            byte []! in ExHeap buf = new[ExHeap] byte[512];
            //string str = null;
            int count = 0;
            int lastBlock = -1;
            while (!done) {
                //Socket.Select(listenList, null, null, 1000);
                if (s.Poll(1000000, SelectMode.SelectRead)) {
                    rc = s.Receive(reply);
                    if (verboseMode) Console.WriteLine("Receive rc={0}", rc);
                    if (rc >= 4) {
                        TftpHdr rh = new TftpHdr(reply, 0);
                        //Console.WriteLine("Opcode {0} Arg {1} rc={2} curPos={3}", rh.Opcode, rh.Arg, rc, curPos);
                        if (rh.Arg == lastBlock)
                                Console.WriteLine(" duplicate block? block ="+rh.Arg);
                        lastBlock = rh.Arg;
                        if (rh.Opcode == TftpOpcode.DATA) {
                            if (!verboseMode) {
                                Console.Write(".");
                                if (count++ > 50) {
                                    count = 0;
                                    Console.Write("\n");
                                }
                            }
                            else {
                                //str = Encoding.ASCII.GetString(reply, 4, rc-4);
                                //Console.WriteLine("pos="+curPos+" str="+str);
                                //str = null;
                            }
                            if (persistHandle != null) {
                                Bitter.FromByteArray(buf,0,rc-4,reply,4);
                                persistHandle.SendWrite(buf,0,curPos,rc-4);
                                switch receive {
                                    case persistHandle.AckWrite( _buf, bytesWritten,  error) :
                                        buf = _buf;
                                        curPos = rh.Arg * 512;
                                        break;
                                    case persistHandle.ChannelClosed() :
                                        Console.WriteLine("File handle closed. Quitting");
                                        delete persistHandle;
                                        return null;
                                        break;
                                    case unsatisfiable:
                                        Console.WriteLine("receive is unsatisfiable. Quitting");
                                        delete persistHandle;
                                        return null;
                                        break;
                                }
                            }
                        }
                        // Build new ack packet - acts as REQ for next block
                        hdr.Opcode = TftpOpcode.ACK;
                        hdr.Arg = rh.Arg;
                        hdr.Marshal(request, 0);
                        len = 4;
                    }
                    if (rc < 512 + 4) done = true;
                }
                else {
                    //Console.WriteLine("poll for data failed!");
                    //return null;
                }
                rc = s.Send(request, len, SocketFlags.None);
                if (verboseMode)Console.WriteLine("Sent {0} {1}  rc {2}", hdr.Opcode, hdr.Arg, rc);
                //Thread.Sleep(1000);
            }
            if (persistHandle != null) {
                Console.WriteLine("Closing EP handle via delete");
                delete persistHandle;
            }
            delete buf;
            return null;
        }

        public string Put(string! filename, string localName)
        {
            TftpHdr hdr = new TftpHdr();
            byte[] request;
            byte[] reply = new byte[8192];
            byte []! in ExHeap buf;
            FileContract.Imp  fileHandle = null ;

            int len;
            int rc;
            long fileLength = 0;
            ErrorCode errorOut; 

            if (null != localName) {
                DirectoryServiceContract.Imp! rootNS = DirectoryService.NewClientEndpoint();
                FileAttributesRecord record;
                bool ok  = FileUtils.GetAttributes(localName, rootNS, out record, out  errorOut);
                delete rootNS; 
                
                if (!ok) {
                    Console.WriteLine("Unable to open file ({0}) for send. reason:{1}",
                        localName, SdsUtils.ErrorCodeToString(errorOut)
                        );
                    return null;
                }

                fileLength = record.FileSize;

                fileHandle = FileUtils.OpenFile(localName);
                if (null == fileHandle) {
                    Console.WriteLine("Unable to open file "+localName+" for send");
                    return null;
                }
            }
            request = new byte[4 + 512];

            len = BuildRequest(request, TftpOpcode.WRQ, filename);
            int pos = 0;
            bool done = false;

            rc = s.Send(request, len, SocketFlags.None);
            Console.WriteLine("Sent WRQ rc={0}", rc);

            buf = new[ExHeap] byte[512];
            int threshold = 20;
            int waitCount = 0;
            Console.WriteLine(" file size =" + fileLength);
            while (!done) {
                //Socket.Select(listenList, null, null, 1000);
                if (s.Poll(100000, SelectMode.SelectRead)) {
                    rc = s.Receive(reply);
                    Console.WriteLine("Receive rc={0}", rc);
                    if (rc >= 4) {
                        TftpHdr rh = new TftpHdr(reply, 0);
                        Console.WriteLine("PUT: Opcode {0} Arg {1}", rh.Opcode, rh.Arg);

                        if (rh.Opcode == TftpOpcode.ACK) {
                            int datalen;
                            int error;
                            long bytesRead;
                            Console.WriteLine("ACK for block {0}, pos={1}", rh.Arg,pos);
                            waitCount = 0;
                            if (pos >= fileLength) {
                                Console.WriteLine(" here");
                                bytesRead = 0;
                            }
                            else {
                if (fileHandle == null)
                    throw new Exception("fileHandle is null when I want to SendRead");
                                fileHandle.SendRead(buf, 0, pos, 512);
                                fileHandle.RecvAckRead(out buf, out bytesRead, out error);
                                if (error != 0) DebugStub.Break();

                                // If we get an ack we can send the next block
                                pos = (rh.Arg+1) * 512;
                            }
                             // Build new DATA packet
                            hdr.Opcode = TftpOpcode.DATA;
                            hdr.Arg = rh.Arg;
                            hdr.Arg++;
                            hdr.Marshal(request, 0);
                            datalen = Math.Min(512, (int)bytesRead);
                            if (datalen < 512) done = true;
                            //Encoding.ASCII.GetBytes(contents, pos, datalen, request, 4);
                            Bitter.ToByteArray(buf,0,datalen,request,4);
                            len = 4 + datalen;
                        }
                        else {
                            Console.WriteLine("NOT AN ACK!\n");
                            DebugStub.Break();
                        }
                    }
                    rc = s.Send(request, len, SocketFlags.None);
                    Console.WriteLine("Sent {0} {1}  rc {2}", hdr.Opcode, hdr.Arg, rc);
                }
                else {
                    Console.WriteLine("Waiting.");
                    waitCount++;
                    if (waitCount > threshold) {
                        Console.WriteLine (" exceeded timeout threshold");
                        done = true;
                        break;
                    }
                }
                //Thread.Sleep(1000);
            }
            Console.WriteLine("Done");
            delete buf;
            if (fileHandle != null)
                delete fileHandle;
            return null;
        }

        private static IPAddress GetServerAddress(string server)
        {
            try {
                return IPAddress.Parse(server);
            }
            catch {
            }

            try {
                IPHostEntry he = Dns.GetHostByName(server);
                return he.AddressList[0];
            }
            catch {
            }
            return null;
        }

        private static void Usage()
        {
            Console.WriteLine("Usage: tftpclient <server> [-i] <put|get> <getfilename> [ <putfilename> ]");
        }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        public static int Main(string[]! args)
        {
            bool verboseMode = false;
            String localName, remoteName;
            if (args.Length < 4 || args.Length > 6) {
                Usage();
                return 1;
            }

            IPAddress server = GetServerAddress(args[1]);
            if (server == null) {
                Console.WriteLine("Could not find server : {0}", args[1]);
                return 2;
            }

            int pos =2;
            if (args[pos] == "-v") {
                verboseMode = true;
                pos++;
            }

            bool doGet;
            switch (args[pos]) {
                case "get":
                    doGet = true;
                    break;
                case "put":
                    doGet = false;
                    break;
                default:
                    Usage();
                    return -1;
            }
            pos++;
            remoteName = (!)args[pos];
            pos++;
            localName = null;
            if (pos >= args.Length) {
                Console.WriteLine("no destination given");
            }
            else {
                localName = args[pos];
            }
            Console.WriteLine("doGet="+doGet+" src="+remoteName+" dest="+localName);
            TftpClient tftpClient = new TftpClient(server);
            if (doGet) {
                string contents = tftpClient.Get(remoteName,localName,verboseMode);
                if (verboseMode) Console.WriteLine("Contents:\n{0}", contents);
            }
            else {
                //put
                tftpClient.Put(remoteName,localName);
            }
            return 0;
        } // end Main
    } // end class TftpClient
} // end namespace Microsoft.Singularity.Shell
Back to Top