summaryrefslogtreecommitdiff
path: root/usr/src/lib/libslp/javalib/com/sun/slp/SrvLocHeader.java
blob: a35c18756780238d9112854f8c2fa174364c25ce (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
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2001-2002 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 *
 */

//  SrvLocHeader.java: Abstract superclass for SLP Headers
//  Author:           James Kempf
//  Created On:       Mon Sep 14 12:47:20 1998
//  Last Modified By: James Kempf
//  Last Modified On: Mon Nov 23 14:32:50 1998
//  Update Count:     55
//

package com.sun.slp;

import java.util.*;
import java.net.*;
import java.io.*;

/**
 * SrvLocHeader handles different versions of the SLP header. Clients
 * call the instance methods returned by newInstance(). If no version
 * specific subclass exists for the version number, null is returned
 * from newInstance. Parsing of the header and message bodies, and
 * creation of error replies are handled by the version specific
 * subclasses. We also let the SrvLocHeader serve as a SrvLocMsg object
 * to handle the SrvAck, which only has an error code.
 *
 * @author James Kempf
 */

abstract class SrvLocHeader extends Object implements SrvLocMsg, Cloneable {

    // Table of header classes. Keys are the version number.

    private static final Hashtable classTable = new Hashtable();

    // Offset to XID.

    static final int XID_OFFSET = 10;

    // Common constants and instance variables.

    // Number of bytes in the version and function fields.

    static int VERSION_FUNCTION_BYTES = 2;

    // SLP function codes. Even though SAAdvert isn't in all versions,
    //  we include it here.

    static final int SrvReq  = 1;
    static final int SrvRply = 2;
    static final int SrvReg = 3;
    static final int SrvDereg = 4;
    static final int SrvAck = 5;
    static final int AttrRqst = 6;
    static final int AttrRply = 7;
    static final int DAAdvert = 8;
    static final int SrvTypeRqst = 9;
    static final int SrvTypeRply = 10;
    static final int SAAdvert = 11;

    static final String[] functionCodeAbbr = {
	"0",
	"SrvReq",
	"SrvRply",
	"SrvReg",
	"SrvDereg",
	"SrvAck",
	"AttrRqst",
	"AttrRply",
	"DAAdvert",
	"SrvTypeRqst",
	"SrvTypeRply",
	"SAAdvert",
    };

    // Sizes of data items.

    protected static final int BYTE_SIZE = 1;
    protected static final int SHORT_SIZE = 2;
    protected static final int INT24_SIZE = 3;

    //
    // Header instance variables.
    //

    // Unprotected for less code.

    int    version = 0;			// version number
    int    functionCode = 0;		// function code
    int    length = 0;			// packet length
    short  xid = 0;			// transaction id
    short  errCode =
	ServiceLocationException.OK;	// not applicable to start
    Locale locale = Defaults.locale;	// language locale
    Vector previousResponders = null;	// list of previous responders
    Vector scopes = null;		// list of scopes
    boolean overflow = false;		// Overflow flag
    boolean fresh = false;		// Fresh flag
    boolean mcast = false;		// Mulitcast flag.
    byte[] payload = new byte[0];	// bytes of outgoing payload,
    int nbytes = 0;			// number of bytes processed
    int packetLength = 0;		// length of packet.
    int iNumReplies = 0;		// number of replies.


    protected static short uniqueXID = 0;	// outgoing transaction id.

    // Message description.

    private String msgType;
    private String msgDescription;


    SrvLocHeader() {

	packetLength = SLPConfig.getSLPConfig().getMTU();

    }

    //
    // SrvLocMsg Implementation.
    //

    public SrvLocHeader getHeader() {
	return this;

    }

    public short getErrorCode() {
	return errCode;

    }

    // Return number of replies to this message.

    public int getNumReplies() {
	return iNumReplies;

    }

    //
    // SrvLocHeader Interface.
    //

    // Register a new header class for version. Serious error, causing
    //  program termination, if we can't find it.

    static void addHeaderClass(String className, int version) {

	try {

	    Class headerClass = Class.forName(className);

	    classTable.put(new Integer(version), headerClass);

	} catch (ClassNotFoundException ex) {

	    Assert.slpassert(false,
			  "no_class",
			  new Object[] {className});

	}
    }

    // Create a version specific instance. We use a naming convention
    //  to identify the version specific classes used to create the
    //  instance.

    static SrvLocHeader newInstance(int version) {

	try {

	    // Get header class.

	    Class hdrClass = (Class)classTable.get(new Integer(version));

	    if (hdrClass == null) {
		return null;

	    }

	    SrvLocHeader hdr = (SrvLocHeader)hdrClass.newInstance();

	    return hdr;

	} catch (Exception ex) {

	    SLPConfig.getSLPConfig().writeLog("slh_creation_exception",
					      new Object[] {
		new Integer(version),
		    ex,
		    ex.getMessage()});
	    return null;

	}

    }

    // Parse the incoming stream to obtain the header.

    abstract void parseHeader(int functionCode, DataInputStream dis)
	throws ServiceLocationException, IOException, IllegalArgumentException;

    // Parse the incoming stream to obtain the message.

    abstract SrvLocMsg parseMsg(DataInputStream dis)
	throws ServiceLocationException, IOException, IllegalArgumentException;

    // Externalize the message.

    abstract void
	externalize(ByteArrayOutputStream baos,
		    boolean multicast,
		    boolean isTCP)
	throws ServiceLocationException;

    // Return the appropriately versioned DAAdvert.

    abstract SDAAdvert
	getDAAdvert(short xid,
		    long timestamp,
		    ServiceURL url,
		    Vector scopes,
		    Vector attrs)
	throws ServiceLocationException;

    //
    // Methods that some subclasses may reimplement.
    //

    // Parse any options.

    void parseOptions(DataInputStream dis)
	throws ServiceLocationException,
	       IOException,
	       IllegalArgumentException {

    }

    // Create an error reply for this message. This reply will be appropriate
    //  for the server to send back to the client. Default is to do nothing,
    //  which is the code for the client.

    SrvLocMsg makeErrorReply(Exception ex) {
	return null;

    }

    //
    //  Common utilities for all versions.
    //

    // Set the packet length to the incoming value.

    void setPacketLength(int newLength) {

	if (newLength > 0) {
	    packetLength = newLength;

	}
    }

    // Add an Internet address to the previous responders list.

    void addPreviousResponder(InetAddress addr) {

	String hostAddr = addr.getHostAddress();

	Assert.slpassert((previousResponders != null),
		      "prev_resp_reply",
		      new Object[0]);

	if (!previousResponders.contains(hostAddr)) {
	    previousResponders.addElement(hostAddr);

	}
    }

    // Get a unique transaction id.

    synchronized static short getUniqueXID() {
	if (uniqueXID == 0) {
	    Random r = new Random();
	    uniqueXID = (short)(r.nextInt() &0xFFFF);
	}
	uniqueXID++;
	return (short)(uniqueXID & 0xFFFF);
    }

    // Parse 2-byte integer, bump byte count.

    int getInt(DataInputStream dis)
	throws ServiceLocationException, IOException {

	int ret = getInteger(dis);

	nbytes += SHORT_SIZE;

	return ret;
    }


    // Parse a 2-byte integer from the input stream.

    static int getInteger(DataInputStream dis)
	throws ServiceLocationException, IOException {

	byte[] b = new byte[2];

	dis.readFully(b, 0, 2);

	int x = (int)((char)b[0] & 0xFF);
	int y = (int)((char)b[1] & 0xFF);
	int z = x << 8;
	z += y;
	return z;
    }

    // Parse 2-byte integer, bump byte count.

    void putInt(int z, ByteArrayOutputStream baos) {

	putInteger(z, baos);

	nbytes += SHORT_SIZE;

    }

    // Parse a 2-byte integer to the output stream.

    static void putInteger(int z, ByteArrayOutputStream baos) {
	baos.write((byte) ((0xFF00 & z)>>8));
	baos.write((byte) (0xFF & z));
    }


    // Parse a 3-byte integer from the byte input stream.

    protected int getInt24(DataInputStream dis)
	throws ServiceLocationException, IOException {

	byte[] b = new byte[3];

	dis.readFully(b, 0, 3);

	int w = (int)((char)b[0] & 0xFF);
	int x = (int)((char)b[1] & 0xFF);
	int y = (int)((char)b[2] & 0xFF);
	int z = w << 16;
	z += x << 8;
	z += y;
	nbytes += 3;
	return z;
    }

    // Parse a 3-byte integer to the output stream.

    protected void putInt24(int z, ByteArrayOutputStream baos) {
	baos.write((byte) ((0xFF0000 & z) >> 16));
	baos.write((byte) ((0xFF00 & z)>>8));
	baos.write((byte) (0xFF & z));

	nbytes += 3;
    }


    // Parse string, bump byte count. Use UTF8 encoding.

    byte[] getString(StringBuffer buf, DataInputStream dis)
	throws ServiceLocationException, IOException {

	byte[] ret = getStringField(buf, dis, Defaults.UTF8);

	nbytes += ret.length + SHORT_SIZE;

	return ret;
    }

    // Parse a string with an initial length from the input stream.
    //  Convert it to the proper encoding. Return the raw bytes for
    //  auth block creation.

    static byte[]
	getStringField(StringBuffer buf, DataInputStream dis, String encoding)
	throws ServiceLocationException, IOException {

	// Clear out buffer first.

	buf.setLength(0);

	// First get the length.

	int i, n = 0;

	n = getInteger(dis);

	// Now get the bytes.

	byte[] bytes = new byte[n];

	dis.readFully(bytes, 0, n);

	// Convert to string and return.

	buf.append(getBytesString(bytes, encoding));

	return bytes;

    }

    // Parse out string, bump byte count. Use UTF8 encoding.

    byte[] putString(String string, ByteArrayOutputStream baos) {

	byte[] bytes = putStringField(string, baos, Defaults.UTF8);

	nbytes += bytes.length + SHORT_SIZE;

	return bytes;

    }

    // Put a string with an initial length into the byte stream, converting
    //  into the proper encoding.

    static byte[]
	putStringField(String string,
		       ByteArrayOutputStream baos,
		       String encoding) {

	byte[] bytes = getStringBytes(string, encoding);

	// Put out the string's length in the encoding.

	putInteger(bytes.length, baos);

	// Now really write out the bytes.

	baos.write(bytes, 0, bytes.length);

	return bytes;

    }

    // Convert a Unicode string into encoded bytes.

    static byte[] getStringBytes(String string, String encoding) {

	try {
	    return string.getBytes(encoding);

	} catch (UnsupportedEncodingException ex) {
	    return  new byte[0];  // won't happen, hopefully...

	}
    }

    // Convert bytes into a Unicode string.

    static String getBytesString(byte[] bytes, String encoding) {

	try {
	    return new String(bytes, encoding);

	} catch (UnsupportedEncodingException ex) {
	    return "";  // won't happen, hopefully ...

	}

    }

    // Parse a comma separated list of strings from the vector into the
    //  output stream.

    protected byte[]
	parseCommaSeparatedListOut(Vector v,
				   ByteArrayOutputStream baos) {

	return putString(vectorToCommaSeparatedList(v), baos);

    }

    /**
     * Create a comma separated list of strings out of the vector.
     *
     * @param v A Vector of strings.
     */

    static String
	vectorToCommaSeparatedList(Vector v) {

	// Construct in a string buffer first.

	int i, n = v.size();
	StringBuffer buf = new StringBuffer();


	for (i = 0; i < n; i++) {
	    String string = (String)v.elementAt(i);

	    // Add comma for previous one if we need it.

	    if (i != 0) {
		buf.append(',');
	    }

	    buf.append(string);

	}

	// Return the bytes.

	return buf.toString();
    }

    /**
     * @parameter The string has the format = STRING *("," STRING)
     * @parameter A boolean indicating whether parens should be ignored or
     * 		used for grouping.
     * @return  A vector (of Strings) based upon the (comma delimited) string.
     */
    static Vector parseCommaSeparatedListIn(String s, boolean ignoreParens)
	throws ServiceLocationException {

	if (s == null)
	    return new Vector();
	if (s.length() == 0)
	    return new Vector();
	StringTokenizer st = new StringTokenizer(s, ",()", true);
	try {
	    int level = 0;
	    String el = "";
	    Vector v = new Vector();

	    while (st.hasMoreElements()) {
		String tok = st.nextToken();

		// It's an open paren, so begin collecting.

		if (tok.equals("(")) {

		    // Increment the level if not ignoring parens, add to token

		    if (!ignoreParens) {
			level++;

		    }

		    el += tok;

		} else if (tok.equals(")")) {
	
		    // Decrement level if not ignoring parens.

		    if (!ignoreParens) {
			level--;

		    }

		    el += tok;

		} else if (tok.equals(",")) {

		    // Add if collecting.

		    if (level != 0) {
			el += tok;

		    } else {

			// Check for empty token.

			if (el.length() <= 0) {
			    throw
				new ServiceLocationException(
					ServiceLocationException.PARSE_ERROR,
					"csl_syntax_error",
					new Object[] {s});
			}

			// If not collecting, then close off the element.

			v.addElement(el);
			el = "";

		    }
		} else {
		    el += tok;

		}
	    }

	    // Add last token, but check first for empty token.

	    if (el.length() <= 0) {
		throw
		    new ServiceLocationException(
				ServiceLocationException.PARSE_ERROR,
				"csl_syntax_error",
				new Object[] {s});
	    }

	    v.addElement(el);

	    // If we're still collecting on close, then there's a syntax error.

	    if (level != 0) {
		throw
		    new ServiceLocationException(
				ServiceLocationException.PARSE_ERROR,
				"csl_syntax_error",
				new Object[] {s});
	    }

	    return v;
	} catch (NoSuchElementException nsee) {
	    throw
		new ServiceLocationException(
				ServiceLocationException.PARSE_ERROR,
				"csl_syntax_error",
				new Object[] {s});

	}
    }

    // Allow clients to clone the header.

    public Object clone()
	throws CloneNotSupportedException {
	SrvLocHeader hdr = (SrvLocHeader)super.clone();

	// Reinitialize some stuff. Subclasses must reimplement nbytes
	//  header size calculation.

	hdr.length = 0;
	hdr.payload = new byte[0];
	hdr.iNumReplies = 0;
	// packetlength stays the same, we may be using the same transport.

	return hdr;

    }

    // Construct a description of the header. Messages add individual
    //  descriptions to this.

    protected void constructDescription(String msgType,
					String msgDescription) {
	this.msgType = msgType;
	this.msgDescription = msgDescription;
    }

    public String getMsgType() {
	if (msgType == null) {
	    if (functionCode > 0 && functionCode < functionCodeAbbr.length) {
		return functionCodeAbbr[functionCode];
	    } else {
		return String.valueOf(functionCode);
	    }
	} else {
	    return msgType;
	}
    }

    public String getMsgDescription() {
	return (msgDescription == null) ? "" : msgDescription;
    }
}