net.c 10.8 KB
Newer Older
Tim Schwartz's avatar
Tim Schwartz committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 * Copyright 2007 Tim Schwartz
 *
 * This library 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; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

19
#include <windows.h>
20
#include <lm.h>
21
#include <wine/unicode.h>
22
#include <wine/debug.h>
23

24
#include "resources.h"
25

26 27
WINE_DEFAULT_DEBUG_CHANNEL(net);

28
#define NET_START 0001
Tim Schwartz's avatar
Tim Schwartz committed
29 30
#define NET_STOP  0002

31
static int output_write(const WCHAR* str, int len)
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
{
    DWORD ret, count;
    ret = WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), str, len, &count, NULL);
    if (!ret)
    {
        DWORD lenA;
        char* strA;

        /* On Windows WriteConsoleW() fails if the output is redirected. So fall
         * back to WriteFile(), assuming the console encoding is still the right
         * one in that case.
         */
        lenA = WideCharToMultiByte(GetConsoleOutputCP(), 0, str, len,
                                   NULL, 0, NULL, NULL);
        strA = HeapAlloc(GetProcessHeap(), 0, lenA);
        if (!strA)
            return 0;

        WideCharToMultiByte(GetConsoleOutputCP(), 0, str, len, strA, lenA,
                            NULL, NULL);
        WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), strA, len, &count, FALSE);
        HeapFree(GetProcessHeap(), 0, strA);
    }
    return count;
}

58
static int output_vprintf(const WCHAR* fmt, __ms_va_list va_args)
59
{
60 61
    WCHAR str[8192];
    int len;
62

63 64 65 66 67
    SetLastError(NO_ERROR);
    len = FormatMessageW(FORMAT_MESSAGE_FROM_STRING, fmt, 0, 0, str,
                         sizeof(str)/sizeof(*str), &va_args);
    if (len == 0 && GetLastError() != NO_ERROR)
        WINE_FIXME("Could not format string: le=%u, fmt=%s\n", GetLastError(), wine_dbgstr_w(fmt));
68 69 70 71 72
    else
        output_write(str, len);
    return 0;
}

73
static int __cdecl output_printf(const WCHAR* fmt, ...)
74
{
75
    __ms_va_list arguments;
76

77
    __ms_va_start(arguments, fmt);
78
    output_vprintf(fmt, arguments);
79
    __ms_va_end(arguments);
80 81 82
    return 0;
}

83
static int __cdecl output_string(int msg, ...)
84 85
{
    WCHAR fmt[8192];
86
    __ms_va_list arguments;
87

88
    LoadStringW(GetModuleHandleW(NULL), msg, fmt, sizeof(fmt)/sizeof(fmt[0]));
89
    __ms_va_start(arguments, msg);
90
    output_vprintf(fmt, arguments);
91
    __ms_va_end(arguments);
92 93 94
    return 0;
}

95
static BOOL output_error_string(DWORD error)
96
{
97 98
    LPWSTR pBuffer;
    if (FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
99
            FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER,
100
            NULL, error, 0, (LPWSTR)&pBuffer, 0, NULL))
101
    {
102
        output_write(pBuffer, lstrlenW(pBuffer));
103 104 105 106 107 108
        LocalFree(pBuffer);
        return TRUE;
    }
    return FALSE;
}

109
static BOOL net_use(int argc, const WCHAR* argv[])
110 111 112
{
    USE_INFO_2 *buffer, *connection;
    DWORD read, total, resume_handle, rc, i;
113
    WCHAR* status[STRING_RECONN-STRING_OK+1];
114 115 116 117 118
    resume_handle = 0;
    buffer = NULL;

    if(argc<3)
    {
119 120 121 122 123
        HMODULE hmod = GetModuleHandleW(NULL);

        /* Load the status strings */
        for (i = 0; i < sizeof(status)/sizeof(*status); i++)
        {
124 125
            status[i] = HeapAlloc(GetProcessHeap(), 0, 1024 * sizeof(**status));
            LoadStringW(hmod, STRING_OK+i, status[i], 1024);
126 127
        }

128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
        do {
            rc = NetUseEnum(NULL, 2, (BYTE **) &buffer, 2048, &read, &total, &resume_handle);
            if (rc != ERROR_MORE_DATA && rc != ERROR_SUCCESS)
            {
                break;
            }

	    if(total == 0)
	    {
	        output_string(STRING_NO_ENTRIES);
		break;
	    }

            output_string(STRING_USE_HEADER);
            for (i = 0, connection = buffer; i < read; ++i, ++connection)
143
                output_string(STRING_USE_ENTRY, status[connection->ui2_status], connection->ui2_local,
144 145 146 147 148
				connection->ui2_remote, connection->ui2_refcount);

            if (buffer != NULL) NetApiBufferFree(buffer);
        } while (rc == ERROR_MORE_DATA);

149 150 151 152
        /* Release the status strings */
        for (i = 0; i < sizeof(status)/sizeof(*status); i++)
            HeapFree(GetProcessHeap(), 0, status[i]);

153 154 155 156 157 158
	return TRUE;
    }

    return FALSE;
}

159 160
static BOOL net_enum_services(void)
{
161
    static const WCHAR runningW[]={' ',' ',' ',' ','%','1','\n',0};
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
    SC_HANDLE SCManager;
    LPENUM_SERVICE_STATUS_PROCESSW services;
    DWORD size, i, count, resume;
    BOOL success = FALSE;

    SCManager = OpenSCManagerW(NULL, NULL, SC_MANAGER_ALL_ACCESS);
    if(!SCManager)
    {
        output_string(STRING_NO_SCM);
        return FALSE;
    }

    EnumServicesStatusExW(SCManager, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, SERVICE_ACTIVE, NULL, 0, &size, &count, NULL, NULL);
    if(GetLastError() != ERROR_MORE_DATA)
    {
        output_error_string(GetLastError());
        goto end;
    }
    services = HeapAlloc(GetProcessHeap(), 0, size);
    resume = 0;
    if(!EnumServicesStatusExW(SCManager, SC_ENUM_PROCESS_INFO, SERVICE_WIN32, SERVICE_ACTIVE, (LPBYTE)services, size, &size, &count, &resume, NULL))
    {
        output_error_string(GetLastError());
        goto end;
    }
    output_string(STRING_RUNNING_HEADER);
    for(i = 0; i < count; i++)
    {
190
        output_printf(runningW, services[i].lpDisplayName);
191 192 193 194 195 196 197 198 199 200 201 202
        WINE_TRACE("service=%s state=%d controls=%x\n",
                   wine_dbgstr_w(services[i].lpServiceName),
                   services[i].ServiceStatusProcess.dwCurrentState,
                   services[i].ServiceStatusProcess.dwControlsAccepted);
    }
    success = TRUE;

 end:
    CloseServiceHandle(SCManager);
    return success;
}

Tim Schwartz's avatar
Tim Schwartz committed
203 204
static BOOL StopService(SC_HANDLE SCManager, SC_HANDLE serviceHandle)
{
205
    LPENUM_SERVICE_STATUSW dependencies = NULL;
Tim Schwartz's avatar
Tim Schwartz committed
206 207 208 209 210 211
    DWORD buffer_size = 0;
    DWORD count = 0, counter;
    BOOL result;
    SC_HANDLE dependent_serviceHandle;
    SERVICE_STATUS_PROCESS ssp;

212
    result = EnumDependentServicesW(serviceHandle, SERVICE_ACTIVE, dependencies, buffer_size, &buffer_size, &count);
Tim Schwartz's avatar
Tim Schwartz committed
213 214 215 216

    if(!result && (GetLastError() == ERROR_MORE_DATA))
    {
        dependencies = HeapAlloc(GetProcessHeap(), 0, buffer_size);
217
        if(EnumDependentServicesW(serviceHandle, SERVICE_ACTIVE, dependencies, buffer_size, &buffer_size, &count))
Tim Schwartz's avatar
Tim Schwartz committed
218 219 220
        {
            for(counter = 0; counter < count; counter++)
            {
221
                output_string(STRING_STOP_DEP, dependencies[counter].lpDisplayName);
222
                dependent_serviceHandle = OpenServiceW(SCManager, dependencies[counter].lpServiceName, SC_MANAGER_ALL_ACCESS);
Tim Schwartz's avatar
Tim Schwartz committed
223
                if(dependent_serviceHandle) result = StopService(SCManager, dependent_serviceHandle);
224
                CloseServiceHandle(dependent_serviceHandle);
225
                if(!result) output_string(STRING_CANT_STOP, dependencies[counter].lpDisplayName);
Tim Schwartz's avatar
Tim Schwartz committed
226 227 228 229 230 231 232 233
           }
        }
    }

    if(result) result = ControlService(serviceHandle, SERVICE_CONTROL_STOP, (LPSERVICE_STATUS)&ssp);
    HeapFree(GetProcessHeap(), 0, dependencies);
    return result;
}
234

235
static BOOL net_service(int operation, const WCHAR* service_name)
236 237 238
{
    SC_HANDLE SCManager, serviceHandle;
    BOOL result = 0;
239 240
    WCHAR service_display_name[4096];
    DWORD buffer_size;
241

242
    SCManager = OpenSCManagerW(NULL, NULL, SC_MANAGER_ALL_ACCESS);
243 244
    if(!SCManager)
    {
245
        output_string(STRING_NO_SCM);
246 247
        return FALSE;
    }
248
    serviceHandle = OpenServiceW(SCManager, service_name, SC_MANAGER_ALL_ACCESS);
249 250
    if(!serviceHandle)
    {
251
        output_string(STRING_NO_SVCHANDLE);
252 253 254 255
        CloseServiceHandle(SCManager);
        return FALSE;
    }

256 257 258
    buffer_size = sizeof(service_display_name)/sizeof(*service_display_name);
    GetServiceDisplayNameW(SCManager, service_name, service_display_name, &buffer_size);
    if (!service_display_name[0]) lstrcpyW(service_display_name, service_name);
259 260 261 262

    switch(operation)
    {
    case NET_START:
263
        output_string(STRING_START_SVC, service_display_name);
264
        result = StartServiceW(serviceHandle, 0, NULL);
265

266
        if(result) output_string(STRING_START_SVC_SUCCESS, service_display_name);
267 268 269 270 271
        else
        {
            if (!output_error_string(GetLastError()))
                output_string(STRING_START_SVC_FAIL, service_display_name);
        }
272
        break;
Tim Schwartz's avatar
Tim Schwartz committed
273
    case NET_STOP:
274
        output_string(STRING_STOP_SVC, service_display_name);
Tim Schwartz's avatar
Tim Schwartz committed
275 276
        result = StopService(SCManager, serviceHandle);

277
        if(result) output_string(STRING_STOP_SVC_SUCCESS, service_display_name);
278 279 280 281 282
        else
        {
            if (!output_error_string(GetLastError()))
                output_string(STRING_STOP_SVC_FAIL, service_display_name);
        }
Tim Schwartz's avatar
Tim Schwartz committed
283
        break;
284 285 286 287 288 289
    }

    CloseServiceHandle(serviceHandle);
    CloseServiceHandle(SCManager);
    return result;
}
Tim Schwartz's avatar
Tim Schwartz committed
290

291 292 293 294 295 296
static int arg_is(const WCHAR* str1, const WCHAR* str2)
{
    return CompareStringW(LOCALE_USER_DEFAULT, NORM_IGNORECASE, str1, -1, str2, -1) == CSTR_EQUAL;
}

int wmain(int argc, const WCHAR* argv[])
Tim Schwartz's avatar
Tim Schwartz committed
297
{
298
    static const WCHAR helpW[]={'h','e','l','p',0};
299
    static const WCHAR shelpW[]={'/','h','e','l','p',0};
300 301 302
    static const WCHAR startW[]={'s','t','a','r','t',0};
    static const WCHAR stopW[]={'s','t','o','p',0};
    static const WCHAR useW[]={'u','s','e',0};
303

Tim Schwartz's avatar
Tim Schwartz committed
304 305
    if (argc < 2)
    {
306
        output_string(STRING_USAGE);
Tim Schwartz's avatar
Tim Schwartz committed
307 308 309
        return 1;
    }

310
    if(arg_is(argv[1], helpW))
Tim Schwartz's avatar
Tim Schwartz committed
311
    {
312 313 314 315 316 317 318 319 320 321 322 323 324
        if(argc > 3)
        {
            output_string(STRING_USAGE);
            return 1;
        }
        if(argc == 2)
            output_string(STRING_USAGE);
        else if(arg_is(argv[2], startW))
            output_string(STRING_START_USAGE);
        else if(arg_is(argv[2], stopW))
            output_string(STRING_STOP_USAGE);
        else
            output_string(STRING_USAGE);
Tim Schwartz's avatar
Tim Schwartz committed
325
    }
326
    else if(arg_is(argv[1], startW))
327
    {
328
        if(argc > 3)
329
        {
330
            output_string(STRING_START_USAGE);
331 332
            return 1;
        }
333 334 335 336 337 338
        if (argc == 2)
        {
            if (!net_enum_services())
                return 1;
        }
        else if(arg_is(argv[2], shelpW))
339 340
            output_string(STRING_START_USAGE);
        else if(!net_service(NET_START, argv[2]))
341 342
            return 1;
    }
343
    else if(arg_is(argv[1], stopW))
Tim Schwartz's avatar
Tim Schwartz committed
344
    {
345
        if(argc != 3)
Tim Schwartz's avatar
Tim Schwartz committed
346
        {
347
            output_string(STRING_STOP_USAGE);
Tim Schwartz's avatar
Tim Schwartz committed
348 349
            return 1;
        }
350 351 352
        if(arg_is(argv[2], shelpW))
            output_string(STRING_STOP_USAGE);
        else if(!net_service(NET_STOP, argv[2]))
Tim Schwartz's avatar
Tim Schwartz committed
353 354
            return 1;
    }
355
    else if(arg_is(argv[1], useW))
356 357 358
    {
        if(!net_use(argc, argv)) return 1;
    }
359 360
    else
        output_string(STRING_USAGE);
361

362
    return 0;
Tim Schwartz's avatar
Tim Schwartz committed
363
}