summaryrefslogtreecommitdiffstats
path: root/src/external/pkg.m4
blob: a8b3d06c8192229aab14cdc643a8be8f789376fd (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
# pkg.m4 - Macros to locate and utilise pkg-config.            -*- Autoconf -*-
# 
# Copyright © 2004 Scott James Remnant <scott@netsplit.com>.
#
# 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/>.
#
# As a special exception to the GNU General Public License, if you
# distribute this file as part of a program that contains a
# configuration script generated by Autoconf, you may include it under
# the same distribution terms that you use for the rest of that program.

# PKG_PROG_PKG_CONFIG([MIN-VERSION])
# ----------------------------------
AC_DEFUN([PKG_PROG_PKG_CONFIG],
[m4_pattern_forbid([^_?PKG_[A-Z_]+$])
m4_pattern_allow([^PKG_CONFIG(_PATH)?$])
AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility])dnl
if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then
	AC_PATH_TOOL([PKG_CONFIG], [pkg-config])
fi
if test -n "$PKG_CONFIG"; then
	_pkg_min_version=m4_default([$1], [0.9.0])
	AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version])
	if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then
		AC_MSG_RESULT([yes])
	else
		AC_MSG_RESULT([no])
		PKG_CONFIG=""
	fi
		
fi[]dnl
])# PKG_PROG_PKG_CONFIG

# PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
#
# Check to see whether a particular set of modules exists.  Similar
# to PKG_CHECK_MODULES(), but does not set variables or print errors.
#
#
# Similar to PKG_CHECK_MODULES, make sure that the first instance of
# this or PKG_CHECK_MODULES is called, or make sure to call
# PKG_CHECK_EXISTS manually
# --------------------------------------------------------------
AC_DEFUN([PKG_CHECK_EXISTS],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
if test -n "$PKG_CONFIG" && \
    AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then
  m4_ifval([$2], [$2], [:])
m4_ifvaln([$3], [else
  $3])dnl
fi])


# _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES])
# ---------------------------------------------
m4_define([_PKG_CONFIG],
[if test -n "$PKG_CONFIG"; then
    if test -n "$$1"; then
        pkg_cv_[]$1="$$1"
    else
        PKG_CHECK_EXISTS([$3],
                         [pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null`],
			 [pkg_failed=yes])
    fi
else
	pkg_failed=untried
fi[]dnl
])# _PKG_CONFIG

# _PKG_SHORT_ERRORS_SUPPORTED
# -----------------------------
AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])
if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
        _pkg_short_errors_supported=yes
else
        _pkg_short_errors_supported=no
fi[]dnl
])# _PKG_SHORT_ERRORS_SUPPORTED


# PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
# [ACTION-IF-NOT-FOUND])
#
#
# Note that if there is a possibility the first call to
# PKG_CHECK_MODULES might not happen, you should be sure to include an
# explicit call to PKG_PROG_PKG_CONFIG in your configure.ac
#
#
# --------------------------------------------------------------
AC_DEFUN([PKG_CHECK_MODULES],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl
AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl

pkg_failed=no
AC_MSG_CHECKING([for $1])

_PKG_CONFIG([$1][_CFLAGS], [cflags], [$2])
_PKG_CONFIG([$1][_LIBS], [libs], [$2])

m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS
and $1[]_LIBS to avoid the need to call pkg-config.
See the pkg-config man page for more details.])

if test $pkg_failed = yes; then
        _PKG_SHORT_ERRORS_SUPPORTED
        if test $_pkg_short_errors_supported = yes; then
	        $1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --errors-to-stdout --print-errors "$2"`
        else 
	        $1[]_PKG_ERRORS=`$PKG_CONFIG --errors-to-stdout --print-errors "$2"`
        fi
	# Put the nasty error message in config.log where it belongs
	echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD

	ifelse([$4], , [AC_MSG_ERROR(dnl
[Package requirements ($2) were not met:

$$1_PKG_ERRORS

Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.

_PKG_TEXT
])],
		[AC_MSG_RESULT([no])
                $4])
elif test $pkg_failed = untried; then
	ifelse([$4], , [AC_MSG_FAILURE(dnl
[The pkg-config script could not be found or is too old.  Make sure it
is in your PATH or set the PKG_CONFIG environment variable to the full
path to pkg-config.

_PKG_TEXT

To get pkg-config, see <http://www.freedesktop.org/software/pkgconfig>.])],
		[$4])
else
	$1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS
	$1[]_LIBS=$pkg_cv_[]$1[]_LIBS
        AC_MSG_RESULT([yes])
	ifelse([$3], , :, [$3])
fi[]dnl
])# PKG_CHECK_MODULES
151'>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
// --- BEGIN COPYRIGHT BLOCK ---
// 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; version 2 of the License.
//
// 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, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import netscape.security.x509.X500Name;

import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.authentication.IAuthToken;
import com.netscape.certsrv.authorization.AuthzToken;
import com.netscape.certsrv.authorization.EAuthzAccessDenied;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IArgBlock;
import com.netscape.certsrv.ca.ICertificateAuthority;
import com.netscape.certsrv.dbs.certdb.ICertRecord;
import com.netscape.certsrv.dbs.certdb.ICertificateRepository;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.request.IRequestList;
import com.netscape.certsrv.request.IRequestQueue;
import com.netscape.certsrv.request.IRequestRecord;
import com.netscape.cms.servlet.base.CMSServlet;
import com.netscape.cms.servlet.common.CMSRequest;
import com.netscape.cms.servlet.common.CMSTemplate;
import com.netscape.cms.servlet.common.CMSTemplateParams;
import com.netscape.cms.servlet.common.ECMSGWException;

/**
 * Provide statistical queries of request and certificate records.
 *
 * @version $Revision$, $Date$
 */
public class Monitor extends CMSServlet {

    /**
     *
     */
    private static final long serialVersionUID = -8492837942132357692L;
    private final static String TPL_FILE = "monitor.template";
    private final static String INFO = "Monitor";

    private ICertificateRepository mCertDB = null;
    private IRequestQueue mQueue = null;
    private X500Name mAuthName = null;
    private String mFormPath = null;

    private int mTotalCerts = 0;
    private int mTotalReqs = 0;

    /**
     * Constructs query servlet.
     */
    public Monitor() {
        super();
    }

    /**
     * initialize the servlet. This servlet uses the template file
     * 'monitor.template' to render the response.
     *
     * @param sc servlet configuration, read from the web.xml file
     */

    public void init(ServletConfig sc) throws ServletException {
        super.init(sc);
        // override success to render own template.
        mTemplates.remove(CMSRequest.SUCCESS);

        if (mAuthority instanceof ICertificateAuthority) {
            ICertificateAuthority ca = (ICertificateAuthority) mAuthority;

            mCertDB = ca.getCertificateRepository();
            mAuthName = ca.getX500Name();
        }
        mQueue = mAuthority.getRequestQueue();

        mFormPath = "/" + mAuthority.getId() + "/" + TPL_FILE;

        if (mOutputTemplatePath != null)
            mFormPath = mOutputTemplatePath;
    }

    /**
     * Process the HTTP request.
     * <ul>
     * <li>http.param startTime start of time period to query
     * <li>http.param endTime end of time period to query
     * <li>http.param interval time between queries
     * <li>http.param numberOfIntervals number of queries to run
     * <li>http.param maxResults =number
     * <li>http.param timeLimit =time
     * </ul>
     */
    public void process(CMSRequest cmsReq) throws EBaseException {
        HttpServletRequest req = cmsReq.getHttpReq();
        HttpServletResponse resp = cmsReq.getHttpResp();

        IAuthToken authToken = authenticate(cmsReq);
        AuthzToken authzToken = null;

        try {
            authzToken = authorize(mAclMethod, authToken,
                        mAuthzResourceName, "read");
        } catch (EAuthzAccessDenied e) {
            log(ILogger.LL_FAILURE,
                    CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
        } catch (Exception e) {
            log(ILogger.LL_FAILURE,
                    CMS.getLogMessage("ADMIN_SRVLT_AUTH_FAILURE", e.toString()));
        }

        if (authzToken == null) {
            cmsReq.setStatus(CMSRequest.UNAUTHORIZED);
            return;
        }

        String startTime = null;
        String endTime = null;
        String interval = null;
        String numberOfIntervals = null;

        EBaseException error = null;

        IArgBlock header = CMS.createArgBlock();
        IArgBlock ctx = CMS.createArgBlock();
        CMSTemplateParams argSet = new CMSTemplateParams(header, ctx);

        CMSTemplate form = null;
        Locale[] locale = new Locale[1];

        try {
            form = getTemplate(mFormPath, req, locale);
        } catch (IOException e) {
            log(ILogger.LL_FAILURE,
                    CMS.getLogMessage("CMSGW_ERR_GET_TEMPLATE", mFormPath, e.toString()));
            throw new ECMSGWException(CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
        }

        try {
            startTime = req.getParameter("startTime");
            endTime = req.getParameter("endTime");
            interval = req.getParameter("interval");
            numberOfIntervals = req.getParameter("numberOfIntervals");

            process(argSet, header, startTime, endTime, interval, numberOfIntervals, locale[0]);
        } catch (EBaseException e) {
            log(ILogger.LL_FAILURE,
                    CMS.getLogMessage("CMSGW_ERR_PROCESSING_REQ", e.toString()));
            error = e;
        }

        try {
            ServletOutputStream out = resp.getOutputStream();

            if (error == null) {
                String xmlOutput = req.getParameter("xml");
                if (xmlOutput != null && xmlOutput.equals("true")) {
                    outputXML(resp, argSet);
                } else {
                    resp.setContentType("text/html");
                    form.renderOutput(out, argSet);
                    cmsReq.setStatus(CMSRequest.SUCCESS);
                }
            } else {
                cmsReq.setStatus(CMSRequest.ERROR);
                cmsReq.setError(error);
            }
        } catch (IOException e) {
            log(ILogger.LL_FAILURE,
                    CMS.getLogMessage("CMSGW_ERR_STREAM_TEMPLATE",
                            e.toString()));
            throw new ECMSGWException(CMS.getUserMessage("CMS_GW_DISPLAY_TEMPLATE_ERROR"));
        }
    }

    private void process(CMSTemplateParams argSet, IArgBlock header,
            String startTime, String endTime,
            String interval, String numberOfIntervals,
            Locale locale)
            throws EBaseException {
        if (interval == null || interval.length() == 0) {
            header.addStringValue("error", "Invalid interval: " + interval);
            return;
        }
        if (numberOfIntervals == null || numberOfIntervals.length() == 0) {
            header.addStringValue("error", "Invalid number of intervals: " + numberOfIntervals);
            return;
        }

        Date startDate = StringToDate(startTime);

        if (startDate == null) {
            header.addStringValue("error", "Invalid start time: " + startTime);
            return;
        }

        int iInterval = 0;

        try {
            iInterval = Integer.parseInt(interval);
        } catch (NumberFormatException nfe) {
            header.addStringValue("error", "Invalid interval: " + interval);
            return;
        }

        int iNumberOfIntervals = 0;

        try {
            iNumberOfIntervals = Integer.parseInt(numberOfIntervals);
        } catch (NumberFormatException nfe) {
            header.addStringValue("error", "Invalid number of intervals: " + numberOfIntervals);
            return;
        }

        header.addStringValue("startDate", startDate.toString());
        header.addStringValue("startTime", startTime);
        header.addIntegerValue("interval", iInterval);
        header.addIntegerValue("numberOfIntervals", iNumberOfIntervals);

        mTotalCerts = 0;
        mTotalReqs = 0;

        Date d1 = startDate;

        for (int i = 0; i < iNumberOfIntervals; i++) {
            Date d2 = nextDate(d1, iInterval - 1);
            IArgBlock rarg = CMS.createArgBlock();
            String e = getIntervalInfo(rarg, d1, d2);

            if (e != null) {
                header.addStringValue("error", e);
                return;
            }
            argSet.addRepeatRecord(rarg);
            d1 = nextDate(d2, 1);
        }

        header.addIntegerValue("totalNumberOfCertificates", mTotalCerts);
        header.addIntegerValue("totalNumberOfRequests", mTotalReqs);

        if (mAuthName != null)
            header.addStringValue("issuerName", mAuthName.toString());

        return;
    }

    Date nextDate(Date d, int seconds) {
        return new Date(d.getTime() + seconds * 1000);
    }

    String getIntervalInfo(IArgBlock arg, Date startDate, Date endDate) {
        if (startDate != null && endDate != null) {
            String startTime = DateToZString(startDate);
            String endTime = DateToZString(endDate);
            String filter = null;

            arg.addStringValue("startTime", startTime);
            arg.addStringValue("endTime", endTime);

            try {
                if (mCertDB != null) {
                    filter = Filter(ICertRecord.ATTR_CREATE_TIME, startTime, endTime);

                    Enumeration<Object> e = mCertDB.findCertRecs(filter);

                    int count = 0;

                    while (e != null && e.hasMoreElements()) {
                        ICertRecord rec = (ICertRecord) e.nextElement();

                        if (rec != null) {
                            count++;
                        }
                    }
                    arg.addIntegerValue("numberOfCertificates", count);
                    mTotalCerts += count;
                }

                if (mQueue != null) {
                    filter = Filter(IRequestRecord.ATTR_CREATE_TIME, startTime, endTime);

                    IRequestList reqList = mQueue.listRequestsByFilter(filter);

                    int count = 0;

                    while (reqList != null && reqList.hasMoreElements()) {
                        IRequestRecord rec = (IRequestRecord) reqList.nextRequest();

                        if (rec != null) {
                            if (count == 0) {
                                arg.addStringValue("firstRequest", rec.getRequestId().toString());
                            }
                            count++;
                        }
                    }
                    arg.addIntegerValue("numberOfRequests", count);
                    mTotalReqs += count;
                }
            } catch (Exception ex) {
                return "Exception: " + ex;
            }

            return null;
        } else {
            return "Missing start or end date";
        }
    }

    Date StringToDate(String z) {
        Date d = null;

        if (z != null && (z.length() == 14 ||
                z.length() == 15 && (z.charAt(14) == 'Z' || z.charAt(14) == 'z'))) {
            // 20020516132030Z or 20020516132030
            try {
                int year = Integer.parseInt(z.substring(0, 4));
                int month = Integer.parseInt(z.substring(4, 6)) - 1;
                int date = Integer.parseInt(z.substring(6, 8));
                int hour = Integer.parseInt(z.substring(8, 10));
                int minute = Integer.parseInt(z.substring(10, 12));
                int second = Integer.parseInt(z.substring(12, 14));
                Calendar calendar = Calendar.getInstance();
                calendar.set(year, month, date, hour, minute, second);
                d = calendar.getTime();
            } catch (NumberFormatException nfe) {
            }
        } else if (z != null && z.length() > 1 && z.charAt(0) == '-') { // -5
            try {
                int i = Integer.parseInt(z);

                d = new Date();
                d = nextDate(d, i);
            } catch (NumberFormatException nfe) {
            }
        }

        return d;
    }

    String DateToZString(Date d) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);

        String time = "" + (calendar.get(Calendar.YEAR));
        int i = calendar.get(Calendar.MONTH) + 1;

        if (i < 10)
            time += "0";
        time += i;
        i = calendar.get(Calendar.DAY_OF_MONTH);
        if (i < 10)
            time += "0";
        time += i;
        i = calendar.get(Calendar.HOUR_OF_DAY);
        if (i < 10)
            time += "0";
        time += i;
        i = calendar.get(Calendar.MINUTE);
        if (i < 10)
            time += "0";
        time += i;
        i = calendar.get(Calendar.SECOND);
        if (i < 10)
            time += "0";
        time += i + "Z";
        return time;
    }

    String Filter(String name, String start, String end) {
        String filter = "(&(" + name + ">=" + start + ")(" + name + "<=" + end + "))";

        return filter;
    }

    String uriFilter(String name, String start, String end) {
        String filter = "(%26(" + name + "%3e%3d" + start + ")(" + name + "%3c%3d" + end + "))";

        return filter;
    }
}