summaryrefslogtreecommitdiff
path: root/desktop/source/registration/com/sun/star/servicetag/SysnetRegistryHelper.java
blob: 2508565b515e91206e75aceed772342adba4f76b (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
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: Registration.java,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

package com.sun.star.servicetag;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import static com.sun.star.servicetag.Util.*;
import static com.sun.star.servicetag.RegistrationDocument.*;

/**
 * Class containing additional methods that are not yet
 * in the JDK Registry class.  Note that all methods in this class
 * will be superceeded by the JDK classes.
 */
public class SysnetRegistryHelper {

    private static final String STCLIENT_SOLARIS = "/usr/bin/stclient";
    private static final String STCLIENT_LINUX = "/opt/sun/servicetag/bin/stclient";
    // stclient exit value (see sthelper.h)
    private static final int ST_ERR_NOT_AUTH = 245;
    private static final int ST_ERR_REC_NOT_FOUND = 225;

    // The stclient output has to be an exported interface
    private static final String INSTANCE_URN_OPEN_ELEMENT = "<instance_urn>";
    private static final String INSTANCE_URN_CLOSE_ELEMENT = "</instance_urn>";
    private static final String REGISTRY_URN = "<registry urn=\"";
    private static final String INSTANCE_URN_DESC = "Product instance URN=";
    private static boolean initialized = false;
    private static boolean supportsHelperClass = true; // default
    private static File stclient = null;
    private static String stclientPath = null;

    // System properties for testing
    private static String SVCTAG_STCLIENT_CMD = "servicetag.stclient.cmd";
    private static String SVCTAG_STHELPER_SUPPORTED = "servicetag.sthelper.supported";

    private synchronized static String getSTclient() {
        if (!initialized) {
            // the system property always overrides the default setting
            if (System.getProperty(SVCTAG_STHELPER_SUPPORTED) != null) {
                supportsHelperClass = Boolean.getBoolean(SVCTAG_STHELPER_SUPPORTED);
            }

            // This is only used for testing
            stclientPath = System.getProperty(SVCTAG_STCLIENT_CMD);         
            if (stclientPath != null) {
                return stclientPath;
            }

            // Initialization to determine the platform's stclient pathname
            String os = System.getProperty("os.name");
            if (os.equals("SunOS")) {
                stclient = new File(STCLIENT_SOLARIS);
            } else if (os.equals("Linux")) {
                stclient = new File(STCLIENT_LINUX);
            } else if (os.startsWith("Windows")) {
        stclient = getWindowsStClientFile();
            } else {
                if (isVerbose()) {
                    System.out.println("Running on non-Sun JDK");
                }
            }
            initialized = true;
        }

        // com.sun.servicetag package has to be compiled with JDK 5 as well
        // JDK 5 doesn't support the File.canExecute() method.
        // Risk not checking isExecute() for the stclient command is very low.

        if (stclientPath == null && stclient != null && stclient.exists()) {
            stclientPath = stclient.getAbsolutePath();
        }
        return stclientPath;
    }

    private static List<String> getCommandList() {
        // Set up the arguments to call stclient
        List<String> command = new ArrayList<String>();
        if (System.getProperty(SVCTAG_STCLIENT_CMD) != null) {
            // This is for jtreg testing use. This will be set to something
            // like:
            // $JAVA_HOME/bin/java -cp $TEST_DIR \
            //    -Dstclient.registry.path=$TEST_DIR/registry.xml \
            //    SvcTagClient
            //
            // On Windows, the JAVA_HOME and TEST_DIR path could contain
            // space e.g. c:\Program Files\Java\jdk1.6.0_05\bin\java. 
            // The SVCTAG_STCLIENT_CMD must be set with a list of 
            // space-separated parameters.  If a parameter contains spaces,
            // it must be quoted with '"'.

            String cmd = getSTclient();
            int len = cmd.length();
            int i = 0;
            while (i < len) {
                char separator = ' ';
                if (cmd.charAt(i) == '"') {
                    separator = '"';
                    i++;
                }
                // look for the separator or matched the closing '"'
                int j;
                for (j = i+1; j < len; j++) {
                    if (cmd.charAt(j) == separator) {
                        break;
                    } 
                }

                if (i == j-1) {
                    // add an empty parameter
                    command.add("\"\"");
                } else {
                    // double quotes and space are not included
                    command.add(cmd.substring(i,j));
                }

                // skip spaces
                for (i = j+1; i < len; i++) {
                    if (!Character.isSpaceChar(cmd.charAt(i))) {
                        break;
                    }
                }
            }
            if (isVerbose()) {
                System.out.println("Command list:");
                for (String s : command) {
                    System.out.println(s);
                }
            }
        } else { 
            command.add(getSTclient());
        }
        return command;
    }

    // Returns null if the service tag record not found;
    // or throw UnauthorizedAccessException or IOException
    // based on the exitValue.
    private static ServiceTag checkReturnError(int exitValue, 
                                               String output,
                                               ServiceTag st) throws IOException {
        switch (exitValue) {
            case ST_ERR_REC_NOT_FOUND:
                return null;
            case ST_ERR_NOT_AUTH:
                if (st != null) {
                    throw new UnauthorizedAccessException(
                        "Not authorized to access " + st.getInstanceURN() + 
                        " installer_uid=" + st.getInstallerUID());
                } else  {
                    throw new UnauthorizedAccessException(
                        "Not authorized:" + output); 
                }
            default: 
                throw new IOException("stclient exits with error" +
                     " (" + exitValue + ")\n" + output); 
        }
    }

    /**
     * Returns a {@code ServiceTag} object of the given  <tt>instance_urn</tt>
     * in this registry.
     *
     * @param instanceURN the  <tt>instance_urn</tt> of the service tag
     * @return a {@code ServiceTag} object of the given <tt>instance_urn</tt>
     * in this registry; or {@code null} if not found.
     *
     * @throws java.io.IOException if an I/O error occurs in this operation.
     */
    private static ServiceTag getServiceTag(String instanceURN) throws IOException {
        if (instanceURN == null) {
            throw new NullPointerException("instanceURN is null");
        }

        List<String> command = getCommandList();
        command.add("-g");
        command.add("-i");
        command.add(instanceURN);

        ProcessBuilder pb = new ProcessBuilder(command);
        Process p = pb.start();
        String output = commandOutput(p);
        if (isVerbose()) {
            System.out.println("Output from stclient -g command:");
            System.out.println(output);
        }
        if (p.exitValue() == 0) {
            return parseServiceTag(output);
        } else {
            return checkReturnError(p.exitValue(), output, null);
        }
    }

    private static ServiceTag parseServiceTag(String output) throws IOException {
        BufferedReader in = null;
        try {
            Properties props = new Properties();
            // parse the service tag output from stclient
            in = new BufferedReader(new StringReader(output));
            String line = null;
            while ((line = in.readLine()) != null) {
                if ((line = line.trim()).length() > 0) {
                    String[] ss = line.trim().split("=", 2);
                    if (ss.length == 2) {
                        props.setProperty(ss[0].trim(), ss[1].trim());
                    } else {
                        props.setProperty(ss[0].trim(), "");
                    }
                }
            }

            String urn = props.getProperty(ST_NODE_INSTANCE_URN);
            String productName = props.getProperty(ST_NODE_PRODUCT_NAME);
            String productVersion = props.getProperty(ST_NODE_PRODUCT_VERSION);
            String productURN = props.getProperty(ST_NODE_PRODUCT_URN);
            String productParent = props.getProperty(ST_NODE_PRODUCT_PARENT);
            String productParentURN = props.getProperty(ST_NODE_PRODUCT_PARENT_URN);
            String productDefinedInstanceID =
                props.getProperty(ST_NODE_PRODUCT_DEFINED_INST_ID);
            String productVendor = props.getProperty(ST_NODE_PRODUCT_VENDOR);
            String platformArch = props.getProperty(ST_NODE_PLATFORM_ARCH);
            String container = props.getProperty(ST_NODE_CONTAINER);
            String source = props.getProperty(ST_NODE_SOURCE);
            int installerUID =
                Util.getIntValue(props.getProperty(ST_NODE_INSTALLER_UID));
            Date timestamp =
                Util.parseTimestamp(props.getProperty(ST_NODE_TIMESTAMP));

            return new ServiceTag(urn,
                                  productName,
                                  productVersion,
                                  productURN,
                                  productParent,
                                  productParentURN,
                                  productDefinedInstanceID,
                                  productVendor,
                                  platformArch,
                                  container,
                                  source,
                                  installerUID,
                                  timestamp);
        } finally {
            if (in != null) {
                in.close();
            }
        }

    }

    /**
     * Returns the urn of this registry.
     * 
     * @return a {@code String} for the urn of this registry.
     * 
     * @throws java.io.IOException if an I/O error occurs in this operation.
     */
    // Once JDK makes this method available, we'll deprecate this method
    // @deprecated Use the JDK version when available.
    public static String getRegistryURN() throws IOException {
        List<String> command = getCommandList();
        command.add("-x");

        BufferedReader in = null;
        try {
            ProcessBuilder pb = new ProcessBuilder(command);
            Process p = pb.start();
            String output = commandOutput(p);

            String registryURN = null;
            if (p.exitValue() == 0) {
                // parse the service tag output from stclient
                in = new BufferedReader(new StringReader(output));
                String line = null;
                while ((line = in.readLine()) != null) {
                    String s = line.trim();
                    if (s.indexOf(REGISTRY_URN) != -1) {
                        s = s.substring(s.indexOf(REGISTRY_URN)
                            + REGISTRY_URN.length());
                        if (s.indexOf("\"") != -1) {
                            s = s.substring(0, s.indexOf("\""));
                            registryURN = s;
                            break;
                        }
                    }
                }
            } else {
                checkReturnError(p.exitValue(), output, null);
            }
            return registryURN;
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }

    /**
     * Returns all the service tags in this registry.
     *
     * @return a {@code Set} of {@code ServiceTag} objects
     * in this registry.
     *
     * @throws java.io.IOException if an I/O error occurs in this operation.
     */
    // Once JDK makes this method available, we'll deprecate this method
    // @deprecated Use the JDK version when available.
    public static Set<ServiceTag> getServiceTags() throws IOException {
        List<String> command = getCommandList();
        command.add("-x");

        BufferedReader in = null;
        try {
            ProcessBuilder pb = new ProcessBuilder(command);
            Process p = pb.start();
            String output = commandOutput(p);

            Set<ServiceTag> instances = new HashSet<ServiceTag>();
            if (p.exitValue() == 0) {
                // parse the service tag output from stclient
                in = new BufferedReader(new StringReader(output));
                String line = null;
                while ((line = in.readLine()) != null) {
                    String s = line.trim();
                    if (s.indexOf(INSTANCE_URN_OPEN_ELEMENT) != -1
                            && s.indexOf(INSTANCE_URN_CLOSE_ELEMENT) != -1) {
                        s = s.substring(s.indexOf(INSTANCE_URN_OPEN_ELEMENT)
                            + INSTANCE_URN_OPEN_ELEMENT.length(),
                            s.indexOf(INSTANCE_URN_CLOSE_ELEMENT));
                        try {
                            instances.add(getServiceTag(s));
                        } catch (Exception e) {
                        }
                    }
                }
            } else {
                checkReturnError(p.exitValue(), output, null);
            }
            return instances;
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }
}