unsigned long
get_symbol(char *name)
{
	FILE *f;
	unsigned long addr;
	char dummy;
	char sname[512];
	struct utsname ver;
	int ret;
	int rep = 0;
	int oldstyle = 0;
 
	f = fopen("/proc/kallsyms", "r");
	if (f == NULL) {
		f = fopen("/proc/ksyms", "r");
		if (f == NULL)
			goto fallback;
		oldstyle = 1;
	}
 
repeat:
	ret = 0;
	while(ret != EOF) {
		if (!oldstyle)
			ret = fscanf(f, "%p %c %s\n", (void **)&addr, &dummy, sname);
		else {
			ret = fscanf(f, "%p %s\n", (void **)&addr, sname);
			if (ret == 2) {
				char *p;
				if (strstr(sname, "_O/") || strstr(sname, "_S."))
					continue;
				p = strrchr(sname, '_');
				if (p > ((char *)sname + 5) && !strncmp(p - 3, "smp", 3)) {
					p = p - 4;
					while (p > (char *)sname && *(p - 1) == '_')
						p--;
					*p = '\0';
				}
			}
		}
		if (ret == 0) {
			fscanf(f, "%s\n", sname);
			continue;
		}
		if (!strcmp(name, sname)) {
			fclose(f);
			return addr;
		}
	}
 
	fclose(f);
	if (rep)
		return 0;
fallback:
	uname(&ver);
	if (strncmp(ver.release, "2.6", 3))
		oldstyle = 1;
	sprintf(sname, "/boot/System.map-%s", ver.release);
	f = fopen(sname, "r");
	if (f == NULL)
		return 0;
	rep = 1;
	goto repeat;
}
Example #2
0
/** @brief detects the OS Version
 *  @return String with OS Version.
 */
QString System::osVersionString(void)
{
    QString result;
#if defined(Q_OS_WIN32)
    SYSTEM_INFO sysinfo;
    OSVERSIONINFO osvi;
    ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    GetVersionEx(&osvi);
    GetSystemInfo(&sysinfo);

    result = QString("Windows version %1.%2, ").arg(osvi.dwMajorVersion).arg(osvi.dwMinorVersion);
    if(osvi.szCSDVersion)
        result += QString("build %1 (%2)").arg(osvi.dwBuildNumber)
            .arg(QString::fromWCharArray(osvi.szCSDVersion));
    else
        result += QString("build %1").arg(osvi.dwBuildNumber);
    result += QString("<br/>CPU: %1, %2 processor(s)").arg(sysinfo.dwProcessorType)
              .arg(sysinfo.dwNumberOfProcessors);
#endif
#if defined(Q_OS_LINUX) || defined(Q_OS_MACX)
    struct utsname u;
    int ret;
    ret = uname(&u);

#if defined(Q_OS_MACX)
    ItemCount cores = MPProcessors();
#else
    long cores = sysconf(_SC_NPROCESSORS_ONLN);
#endif
    if(ret != -1) {
        result = QString("CPU: %1, %2 processor(s)").arg(u.machine).arg(cores);
        result += QString("<br/>System: %2<br/>Release: %3<br/>Version: %4")
            .arg(u.sysname).arg(u.release).arg(u.version);
    }
    else {
        result = QString("(Error when retrieving system information)");
    }
#if defined(Q_OS_MACX)
    SInt32 major;
    SInt32 minor;
    SInt32 bugfix;
    OSErr error;
    error = Gestalt(gestaltSystemVersionMajor, &major);
    error = Gestalt(gestaltSystemVersionMinor, &minor);
    error = Gestalt(gestaltSystemVersionBugFix, &bugfix);

    result += QString("<br/>OS X %1.%2.%3 ").arg(major).arg(minor).arg(bugfix);
    // 1: 86k, 2: ppc, 10: i386
    SInt32 arch;
    error = Gestalt(gestaltSysArchitecture, &arch);
    switch(arch) {
        case 1:
        result.append("(86k)");
        break;
    case 2:
        result.append("(ppc)");
        break;
    case 10:
        result.append("(x86)");
        break;
    default:
        result.append("(unknown)");
        break;
    }
#endif
#endif
    result += QString("<br/>Qt version %1").arg(qVersion());
    return result;
}
Example #3
0
/* Do not free the returned pointer */
const char *
sysapi_kernel_version_raw(void)
{
#if !defined(WIN32)
	struct utsname buf;

	if( uname(&buf) < 0 ) {
		_sysapi_kernel_version = strdup("N/A");
		return _sysapi_kernel_version;
	}
#endif

#if defined(LINUX)
	if (strncmp(buf.release, "2.2.", 4) == MATCH) {
		_sysapi_kernel_version = strdup("2.2.x");
	} else if (strncmp(buf.release, "2.3.", 4) == MATCH) {
		_sysapi_kernel_version = strdup("2.3.x");
	} else if (strncmp(buf.release, "2.4.", 4) == MATCH) {
		_sysapi_kernel_version = strdup("2.4.x");
	} else if (strncmp(buf.release, "2.5.", 4) == MATCH) {
		_sysapi_kernel_version = strdup("2.5.x");
	} else if (strncmp(buf.release, "2.6.", 4) == MATCH) {
		_sysapi_kernel_version = strdup("2.6.x");
	} else if (strncmp(buf.release, "2.7.", 4) == MATCH) {
		_sysapi_kernel_version = strdup("2.7.x");
	} else if (strncmp(buf.release, "2.8.", 4) == MATCH) {
		_sysapi_kernel_version = strdup("2.8.x");
	} else {
		_sysapi_kernel_version = strdup(buf.release);
	}
#elif defined(Solaris)
	if (strcmp(buf.release, "2.10") == MATCH ||
		strcmp(buf.release, "5.10") == MATCH)
	{
		_sysapi_kernel_version = strdup("2.10");

	} else if (strcmp(buf.release, "2.9") == MATCH ||
			strcmp(buf.release, "5.9") == MATCH)
	{
		_sysapi_kernel_version = strdup("2.9");

	} else if (strcmp(buf.release, "2.8") == MATCH ||
				strcmp(buf.release, "5.8") == MATCH)
	{
		_sysapi_kernel_version = strdup("2.8");

	} else if (strcmp(buf.release, "2.7") == MATCH ||
				strcmp(buf.release, "5.7") == MATCH)
	{
		_sysapi_kernel_version = strdup("2.7");

	} else if(strcmp(buf.release, "5.6") == MATCH ||
				strcmp(buf.release, "2.6") == MATCH)
	{
		_sysapi_kernel_version = strdup("2.6");

	} else if (strcmp(buf.release, "5.5.1") == MATCH ||
				strcmp(buf.release, "2.5.1") == MATCH)
	{
		_sysapi_kernel_version = strdup("2.5.1");

	} else if (strcmp(buf.release, "5.5") == MATCH ||
				strcmp(buf.release, "2.5") == MATCH)
	{
		_sysapi_kernel_version = strdup("2.5");

	} else {
		_sysapi_kernel_version = strdup(buf.release);

	}

#elif defined(Darwin) || defined(CONDOR_FREEBSD)
	_sysapi_kernel_version = strdup(buf.release);
#elif defined(AIX)
	_sysapi_kernel_version = strdup(buf.release);
#elif defined(HPUX)
	_sysapi_kernel_version = strdup(buf.release);
#elif defined(WIN32)
	_sysapi_kernel_version = strdup("Unknown");
#else
#	error Please port sysapi_kernel_version_raw() to this platform!
#endif
	
	return _sysapi_kernel_version;
}
Example #4
0
void fs_overlayfs(void) {
	// check kernel version
	struct utsname u;
	int rv = uname(&u);
	if (rv != 0)
		errExit("uname");
	int major;
	int minor;
	if (2 != sscanf(u.release, "%d.%d", &major, &minor)) {
		fprintf(stderr, "Error: cannot extract Linux kernel version: %s\n", u.version);
		exit(1);
	}
	
	if (arg_debug)
		printf("Linux kernel version %d.%d\n", major, minor);
	int oldkernel = 0;
	if (major < 3) {
		fprintf(stderr, "Error: minimum kernel version required 3.x\n");
		exit(1);
	}
	if (major == 3 && minor < 18)
		oldkernel = 1;
	
	// build overlay directories
	fs_build_mnt_dir();

	char *oroot;
	if(asprintf(&oroot, "%s/oroot", RUN_MNT_DIR) == -1)
		errExit("asprintf");
	if (mkdir(oroot, S_IRWXU | S_IRWXG | S_IRWXO))
		errExit("mkdir");
	if (chown(oroot, 0, 0) < 0)
		errExit("chown");
	if (chmod(oroot, S_IRWXU  | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) < 0)
		errExit("chmod");

	char *basedir = RUN_MNT_DIR;
	if (arg_overlay_keep) {
		// set base for working and diff directories
		basedir = cfg.overlay_dir;
		if (mkdir(basedir, S_IRWXU | S_IRWXG | S_IRWXO) != 0) {
			fprintf(stderr, "Error: cannot create overlay directory\n");
			exit(1);
		}
	}

	char *odiff;
	if(asprintf(&odiff, "%s/odiff", basedir) == -1)
		errExit("asprintf");
	if (mkdir(odiff, S_IRWXU | S_IRWXG | S_IRWXO))
		errExit("mkdir");
	if (chown(odiff, 0, 0) < 0)
		errExit("chown");
	if (chmod(odiff, S_IRWXU  | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) < 0)
		errExit("chmod");
	
	char *owork;
	if(asprintf(&owork, "%s/owork", basedir) == -1)
		errExit("asprintf");
	if (mkdir(owork, S_IRWXU | S_IRWXG | S_IRWXO))
		errExit("mkdir");
	if (chown(owork, 0, 0) < 0)
		errExit("chown");
	if (chmod(owork, S_IRWXU  | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) < 0)
		errExit("chmod");
	
	// mount overlayfs
	if (arg_debug)
		printf("Mounting OverlayFS\n");
	char *option;
	if (oldkernel) { // old Ubuntu/OpenSUSE kernels
		if (arg_overlay_keep) {
			fprintf(stderr, "Error: option --overlay= not available for kernels older than 3.18\n");
			exit(1);
		}
		if (asprintf(&option, "lowerdir=/,upperdir=%s", odiff) == -1)
			errExit("asprintf");
		if (mount("overlayfs", oroot, "overlayfs", MS_MGC_VAL, option) < 0)
			errExit("mounting overlayfs");
	}
	else { // kernel 3.18 or newer
		if (asprintf(&option, "lowerdir=/,upperdir=%s,workdir=%s", odiff, owork) == -1)
			errExit("asprintf");
//printf("option #%s#\n", option);			
		if (mount("overlay", oroot, "overlay", MS_MGC_VAL, option) < 0)
			errExit("mounting overlayfs");
	}
	printf("OverlayFS configured in %s directory\n", basedir);
	
	// mount-bind dev directory
	if (arg_debug)
		printf("Mounting /dev\n");
	char *dev;
	if (asprintf(&dev, "%s/dev", oroot) == -1)
		errExit("asprintf");
	if (mount("/dev", dev, NULL, MS_BIND|MS_REC, NULL) < 0)
		errExit("mounting /dev");

	// chroot in the new filesystem
	if (chroot(oroot) == -1)
		errExit("chroot");
	// update /var directory in order to support multiple sandboxes running on the same root directory
	if (!arg_private_dev)
		fs_dev_shm();
	fs_var_lock();
	fs_var_tmp();
	fs_var_log();
	fs_var_lib();
	fs_var_cache();
	fs_var_utmp();

	// don't leak user information
	restrict_users();

	disable_firejail_config();

	// cleanup and exit
	free(option);
	free(oroot);
	free(odiff);
}
Example #5
0
/*---------------------------------------------------------------*/
int main(int argc, char *argv[]) {
    int nargs,r,c,s,n,segid,err;
    double val;

    nargs = handle_version_option (argc, argv, vcid, "$Name: stable5 $");
    if (nargs && argc - nargs == 1) exit (0);
    argc -= nargs;
    cmdline = argv2cmdline(argc,argv);
    uname(&uts);
    getcwd(cwd,2000);

    Progname = argv[0] ;
    argc --;
    argv++;
    ErrorInit(NULL, NULL, NULL) ;
    DiagInit(NULL, NULL, NULL) ;
    if (argc == 0) usage_exit();
    parse_commandline(argc, argv);
    check_options();
    if (checkoptsonly) return(0);
    dump_options(stdout);

    SUBJECTS_DIR = getenv("SUBJECTS_DIR");
    if (SUBJECTS_DIR == NULL) {
        printf("ERROR: SUBJECTS_DIR not defined in environment\n");
        exit(1);
    }

    if (DoDavid) {
        printf("Loading David's stat file\n");
        nitems = LoadDavidsTable(statfile, &lutindex, &log10p);
    }
    if (DoSue) {
        printf("Loading Sue's stat file\n");
        nitems = LoadSuesTable(statfile, datcol1, log10flag, &lutindex, &log10p);
    }
    if (nitems == 0) {
        printf("ERROR: could not find any items in %s\n",statfile);
        exit(1);
    }

    if (annot == NULL) {
        seg = MRIread(segfile);
        if (seg == NULL) exit(1);
    } else {
        printf("Constructing seg from annotation\n");
        sprintf(tmpstr,"%s/%s/surf/%s.white",SUBJECTS_DIR,subject,hemi);
        mris = MRISread(tmpstr);
        if (mris==NULL) exit(1);
        sprintf(tmpstr,"%s/%s/label/%s.%s.annot",SUBJECTS_DIR,subject,hemi,annot);
        err = MRISreadAnnotation(mris, tmpstr);
        if (err) exit(1);
        seg = MRISannotIndex2Seg(mris);
    }

    out = MRIallocSequence(seg->width,seg->height,seg->depth,MRI_FLOAT,1);
    MRIcopyHeader(seg,out);

    for (c=0; c < seg->width; c++) {
        //printf("%3d ",c);
        //if(c%20 == 19) printf("\n");
        fflush(stdout);
        for (r=0; r < seg->height; r++) {
            for (s=0; s < seg->depth; s++) {
                segid = MRIgetVoxVal(seg,c,r,s,0);
                val = 0;
                if (segid != 0) {
                    if (annot != NULL) {
                        if (strcmp(hemi,"lh")==0) segid = segid + 1000;
                        if (strcmp(hemi,"rh")==0) segid = segid + 2000;
                        MRIsetVoxVal(seg,c,r,s,0,segid);
                    }
                    for (n=0; n < nitems; n++) {
                        if (lutindex[n] == segid) {
                            val = log10p[n];
                            break;
                        }
                    }
                }
                MRIsetVoxVal(out,c,r,s,0,val);
            }
        }
    }
    printf("\n");
    MRIwrite(out,outfile);
    MRIwrite(seg,"segtmp.mgh");

    printf("mri_stats2seg done\n");
    return 0;
}
Example #6
0
/* return the Url of the user's X display
 * this must be of the form:
 *   x11: [protocol/] [hostname] : [:] displaynumber [.screennumber] \
 *	[ ; auth= auth_data ]
 */
char *
GetXUrl(char *display_name, char *auth)
{
    char *dpy_name, *proto;
    char *url, *ptr;
    char *name;
    int len, proto_len, dpy_len, name_len, auth_len;

    len = 5;			/* this is for "x11:" */

    /* if of the form "x11:display" change it to "display" */
    if (strncmp(display_name, "x11:", 4) == 0)
	dpy_name = display_name + 4;
    else
	dpy_name = display_name;

    /* if protocol is specified store it and remove it from display name  */
    ptr = strchr(dpy_name, '/');
    if (ptr != NULL) {
	proto = dpy_name;
	proto_len = ptr - dpy_name;
	dpy_name = ptr + 1;
	/* if local forget it */
	if (strncmp(proto, "local", proto_len) == 0)
	    proto_len = 0;
    } else
	proto_len = 0;

    /* if of the form "unix:0.0" change it to ":0.0" */
    if (strncmp(dpy_name, "unix", 4) == 0)
	dpy_name += 4;

    /* if of the form ":0.0" get the real hostname */
    if (dpy_name[0] == ':') {
	struct utsname host;

	uname(&host);
	name = host.nodename;
    } else {			/* otherwise get canonical hostname */
	char hostname[MAXHOSTNAMELEN], *ptr;
	struct hostent *host;

	ptr = strchr(dpy_name, ':');
	if (ptr == NULL) {	/* no display number - not valid actually... */
	    strcpy(hostname, dpy_name);
	    dpy_name = NULL;
	} else {
	    strncpy(hostname, dpy_name, ptr - dpy_name);
	    hostname[ptr - dpy_name] = '\0';
	    /* since we have the canonical name skip the one we were given */
	    dpy_name = ptr;
	}
	host = gethostbyname(hostname);
	name = host->h_name;
    }
    name_len = strlen(name);

    dpy_len = dpy_name == NULL ? 0 : strlen(dpy_name);
    auth_len = auth == NULL ? 0 : 6 + strlen(auth); /* 6 for ";auth=" */
    len += proto_len + 1 + name_len + dpy_len + auth_len;

    url = ptr = (char *)Malloc(len);
    if (url == NULL)
	return NULL;

    strcpy(ptr, "x11:");
    ptr += 4;
    if (proto_len != 0) {
	strncpy(ptr, proto, proto_len + 1);
	ptr += proto_len + 1;
    }
    if (name_len != 0) {
	strcpy(ptr, name);
	ptr += name_len;
    }
    if (dpy_len != 0) {
	strcpy(ptr, dpy_name);
	ptr += dpy_len;
    }
    if (auth_len != 0)
	sprintf(ptr, ";auth=%s", auth);
    else
	*ptr = '\0';

    return url;
}
Example #7
0
std::string CSysInfo::GetUserAgent()
{
  static std::string result;
  if (!result.empty())
    return result;

  result = GetAppName() + "/" + CSysInfo::GetVersionShort() + " (";
#if defined(TARGET_WINDOWS)
  result += GetKernelName() + " " + GetKernelVersion();
  BOOL bIsWow = FALSE;
  if (IsWow64Process(GetCurrentProcess(), &bIsWow) && bIsWow)
      result.append("; WOW64");
  else
  {
    SYSTEM_INFO si = {};
    GetSystemInfo(&si);
    if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
      result.append("; Win64; x64");
    else if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64)
      result.append("; Win64; IA64");
    else if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_ARM)
      result.append("; ARM");
  }
#elif defined(TARGET_DARWIN)
#if defined(TARGET_DARWIN_IOS)
  std::string iDevStr(GetModelName()); // device model name with number of model version
  size_t iDevStrDigit = iDevStr.find_first_of("0123456789");
  std::string iDev(iDevStr, 0, iDevStrDigit);  // device model name without number 
  if (iDevStrDigit == 0)
    iDev = "unknown";
  result += iDev + "; ";
  std::string iOSVerison(GetOsVersion());
  size_t lastDotPos = iOSVerison.rfind('.');
  if (lastDotPos != std::string::npos && iOSVerison.find('.') != lastDotPos
      && iOSVerison.find_first_not_of('0', lastDotPos + 1) == std::string::npos)
    iOSVerison.erase(lastDotPos);
  StringUtils::Replace(iOSVerison, '.', '_');
  if (iDev == "iPad" || iDev == "AppleTV")
    result += "CPU OS ";
  else
    result += "CPU iPhone OS ";
  result += iOSVerison + " like Mac OS X";
#else
  result += "Macintosh; ";
  std::string cpuFam(GetBuildTargetCpuFamily());
  if (cpuFam == "x86")
    result += "Intel ";
  else if (cpuFam == "PowerPC")
    result += "PPC ";
  result += "Mac OS X ";
  std::string OSXVersion(GetOsVersion());
  StringUtils::Replace(OSXVersion, '.', '_');
  result += OSXVersion;
#endif
#elif defined(TARGET_ANDROID)
  result += "Linux; Android ";
  std::string versionStr(GetOsVersion());
  const size_t verLen = versionStr.length();
  if (verLen >= 2 && versionStr.compare(verLen - 2, 2, ".0", 2) == 0)
    versionStr.erase(verLen - 2); // remove last ".0" if any
  result += versionStr;
  std::string deviceInfo(GetModelName());

  char buildId[PROP_VALUE_MAX];
  int propLen = __system_property_get("ro.build.id", buildId);
  if (propLen > 0 && propLen <= PROP_VALUE_MAX)
  {
    if (!deviceInfo.empty())
      deviceInfo += " ";
    deviceInfo += "Build/";
    deviceInfo.append(buildId, propLen);
  }

  if (!deviceInfo.empty())
    result += "; " + deviceInfo;
#elif defined(TARGET_POSIX)
  result += "X11; ";
  struct utsname un;
  if (uname(&un) == 0)
  {
    std::string cpuStr(un.machine);
    if (cpuStr == "x86_64" && GetXbmcBitness() == 32)
      cpuStr = "i686 (x86_64)";
    result += un.sysname;
    result += " ";
    result += cpuStr;
  }
  else
    result += "Unknown";
#else
  result += "Unknown";
#endif
  result += ")";

  if (GetAppName() != "Kodi")
    result += " Kodi_Fork_" + GetAppName() + "/1.0"; // default fork number is '1.0', replace it with actual number if necessary

#ifdef TARGET_LINUX
  // Add distribution name
  std::string linuxOSName(GetOsName(true));
  if (!linuxOSName.empty())
    result += " " + linuxOSName + "/" + GetOsVersion();
#endif

#ifdef TARGET_RASPBERRY_PI
  result += " HW_RaspberryPi/1.0";
#elif defined (TARGET_DARWIN_IOS)
  std::string iDevVer;
  if (iDevStrDigit == std::string::npos)
    iDevVer = "0.0";
  else
    iDevVer.assign(iDevStr, iDevStrDigit, std::string::npos);
  StringUtils::Replace(iDevVer, ',', '.');
  result += " HW_" + iDev + "/" + iDevVer;
#endif
  // add more device IDs here if needed. 
  // keep only one device ID in result! Form:
  // result += " HW_" + "deviceID" + "/" + "1.0"; // '1.0' if device has no version

#if defined(TARGET_ANDROID)
  // Android has no CPU string by default, so add it as additional parameter
  struct utsname un1;
  if (uname(&un1) == 0)
  {
    std::string cpuStr(un1.machine);
    StringUtils::Replace(cpuStr, ' ', '_');
    result += " Sys_CPU/" + cpuStr;
  }
#endif

  result += " App_Bitness/" + StringUtils::Format("%d", GetXbmcBitness());

  std::string fullVer(CSysInfo::GetVersion());
  StringUtils::Replace(fullVer, ' ', '-');
  result += " Version/" + fullVer;

  return result;
}
Example #8
0
int main(int argc, char *argv[])
{
	int ret, i, action = -1;
	char config_file[PATH_MAX] = {};
	int type = 0;
	struct utsname u;
	int version, major, minor;

	/* Check kernel version: it must be >= 2.6.18 */
	if (uname(&u) == -1) {
		dlog(LOG_ERR, "Can't retrieve kernel version via uname()");
		exit(EXIT_FAILURE);
	}
	sscanf(u.release, "%d.%d.%d", &version, &major, &minor);
	if (version < 2 && major < 6 && minor < 18) {
		dlog(LOG_ERR, "Linux kernel version must be >= 2.6.18");
		exit(EXIT_FAILURE);
	}

	for (i=1; i<argc; i++) {
		switch(argv[i][1]) {
		case 'd':
			set_operation_mode(&type, DAEMON, argv);
			CONFIG(running_mode) = DAEMON;
			break;
		case 'c':
			set_operation_mode(&type, REQUEST, argv);
			i = set_action_by_table(i, argc, argv,
						CT_COMMIT, EXP_COMMIT,
						ALL_COMMIT, &action);
			break;
		case 'i':
			set_operation_mode(&type, REQUEST, argv);
			i = set_action_by_table(i, argc, argv,
						CT_DUMP_INTERNAL,
						EXP_DUMP_INTERNAL,
						CT_DUMP_INTERNAL, &action);
			break;
		case 'e':
			set_operation_mode(&type, REQUEST, argv);
			i = set_action_by_table(i, argc, argv,
						CT_DUMP_EXTERNAL,
						EXP_DUMP_EXTERNAL,
						CT_DUMP_EXTERNAL, &action);
			break;
		case 'C':
			if (++i < argc) {
				strncpy(config_file, argv[i], PATH_MAX);
				if (strlen(argv[i]) >= PATH_MAX){
					config_file[PATH_MAX-1]='\0';
					dlog(LOG_WARNING, "Path to config file"
					     " to long. Cutting it down to %d"
					     " characters", PATH_MAX);
				}
				break;
			}
			show_usage(argv[0]);
			dlog(LOG_ERR, "Missing config filename");
			break;
		case 'F':
			set_operation_mode(&type, REQUEST, argv);
			i = set_action_by_table(i, argc, argv,
						CT_FLUSH_MASTER,
						EXP_FLUSH_MASTER,
						ALL_FLUSH_MASTER, &action);
			break;
		case 'f':
			set_operation_mode(&type, REQUEST, argv);
			if (i+1 < argc && argv[i+1][0] != '-') {
				if (strncmp(argv[i+1], "internal",
					    strlen(argv[i+1])) == 0) {
					action = CT_FLUSH_INT_CACHE;
					i++;
				} else if (strncmp(argv[i+1], "external",
						 strlen(argv[i+1])) == 0) {
					action = CT_FLUSH_EXT_CACHE;
					i++;
				} else {
					dlog(LOG_ERR, "unknown parameter `%s' "
					     "for option `-f'", argv[i + 1]);
					exit(EXIT_FAILURE);
				}
			} else {
				/* default to general flushing */
				action = ALL_FLUSH_CACHE;
			}
			break;
		case 'R':
			set_operation_mode(&type, REQUEST, argv);
			i = set_action_by_table(i, argc, argv,
						CT_RESYNC_MASTER,
						EXP_RESYNC_MASTER,
						ALL_RESYNC_MASTER, &action);
			break;
		case 'B':
			set_operation_mode(&type, REQUEST, argv);
			action = SEND_BULK;
			break;
		case 't':
			set_operation_mode(&type, REQUEST, argv);
			action = RESET_TIMERS;
			break;
		case 'k':
			set_operation_mode(&type, REQUEST, argv);
			action = KILL;
			break;
		case 's':
			set_operation_mode(&type, REQUEST, argv);
			/* we've got a parameter */
			if (i+1 < argc && argv[i+1][0] != '-') {
				if (strncmp(argv[i+1], "network",
					    strlen(argv[i+1])) == 0) {
					action = STATS_NETWORK;
					i++;
				} else if (strncmp(argv[i+1], "cache",
						 strlen(argv[i+1])) == 0) {
					action = STATS_CACHE;
					i++;
				} else if (strncmp(argv[i+1], "runtime",
						 strlen(argv[i+1])) == 0) {
					action = STATS_RUNTIME;
					i++;
				} else if (strncmp(argv[i+1], "multicast",
						 strlen(argv[i+1])) == 0) {
					dlog(LOG_WARNING, "use `link' "
					     "instead of `multicast' as "
					     "parameter.");
					action = STATS_LINK;
					i++;
				} else if (strncmp(argv[i+1], "link",
						 strlen(argv[i+1])) == 0) {
					action = STATS_LINK;
					i++;
				} else if (strncmp(argv[i+1], "rsqueue",
						strlen(argv[i+1])) == 0) {
					action = STATS_RSQUEUE;
					i++;
				} else if (strncmp(argv[i+1], "process",
						 strlen(argv[i+1])) == 0) {
					action = STATS_PROCESS;
					i++;
				} else if (strncmp(argv[i+1], "queue",
						strlen(argv[i+1])) == 0) {
					action = STATS_QUEUE;
					i++;
				} else if (strncmp(argv[i+1], "ct",
						strlen(argv[i+1])) == 0) {
					action = STATS;
					i++;
				} else if (strncmp(argv[i+1], "expect",
						strlen(argv[i+1])) == 0) {
					action = EXP_STATS;
					i++;
				} else {
					dlog(LOG_ERR, "unknown parameter `%s' "
					     "for option `-s'", argv[i + 1]);
					exit(EXIT_FAILURE);
				}
			} else {
				/* default to general statistics */
				action = STATS;
			}
			break;
		case 'S':
			dlog(LOG_WARNING,"-S option is obsolete. Ignoring.");
			break;
		case 'n':
			set_operation_mode(&type, REQUEST, argv);
			action = REQUEST_DUMP;
			break;
		case 'x':
			if (action == CT_DUMP_INTERNAL)
				action = CT_DUMP_INT_XML;
			else if (action == CT_DUMP_EXTERNAL)
				action = CT_DUMP_EXT_XML;
			else if (action == EXP_DUMP_INTERNAL)
				action = EXP_DUMP_INT_XML;
			else if (action == EXP_DUMP_EXTERNAL)
				action = EXP_DUMP_EXT_XML;
			else {
				show_usage(argv[0]);
				dlog(LOG_ERR,  "Invalid parameters");
				exit(EXIT_FAILURE);

			}
			break;
		case 'v':
			show_version();
			exit(EXIT_SUCCESS);
		case 'h':
			show_usage(argv[0]);
			exit(EXIT_SUCCESS);
		default:
			show_usage(argv[0]);
			dlog(LOG_ERR, "Unknown option: %s", argv[i]);
			return 0;
			break;
		}
	}

	if (!config_file[0])
		strcpy(config_file, DEFAULT_CONFIGFILE);

	umask(0177);

	if ((ret = init_config(config_file)) == -1) {
		dlog(LOG_ERR, "can't open config file `%s'", config_file);
		exit(EXIT_FAILURE);
	}

	if (type == REQUEST) {
		if (do_local_request(action, &conf.local, local_step) == -1) {
			dlog(LOG_ERR, "can't connect: is conntrackd "
			     "running? appropriate permissions?");
			exit(EXIT_FAILURE);
		}
		exit(EXIT_SUCCESS);
	}

	/*
	 * Setting up logging
	 */
	if (init_log() == -1)
		exit(EXIT_FAILURE);

	/*
	 * lock file
	 */
	ret = open(CONFIG(lockfile), O_CREAT | O_EXCL | O_TRUNC, 0600);
	if (ret == -1) {
		dlog(LOG_ERR, "lockfile `%s' exists, perhaps conntrackd"
		     " already running?", CONFIG(lockfile));
		exit(EXIT_FAILURE);
	}
	close(ret);

	/*
	 * Setting process priority and scheduler
	 */
	set_nice_value(CONFIG(nice));

	if (CONFIG(sched).type != SCHED_OTHER) {
		struct sched_param schedparam = {
			.sched_priority = CONFIG(sched).prio,
		};

		ret = sched_setscheduler(0, CONFIG(sched).type, &schedparam);
		if (ret == -1) {
			dlog(LOG_ERR, "scheduler configuration failed: %s",
			     strerror(errno));
			exit(EXIT_FAILURE);
		}
	}

	/*
	 * initialization process
	 */

	if (init() == -1) {
		dlog(LOG_ERR, "conntrackd cannot start, please review your "
		     "configuration");
		close_log();
		unlink(CONFIG(lockfile));
		exit(EXIT_FAILURE);
	}

	do_chdir("/");
	close(STDIN_FILENO);

	sd_ct_watchdog_init();

	/* Daemonize conntrackd */
	if (type == DAEMON) {
		pid_t pid;

		if ((pid = fork()) == -1) {
			dlog(LOG_ERR, "fork has failed: %s", strerror(errno));
			exit(EXIT_FAILURE);
		} else if (pid) {
			sd_ct_mainpid(pid);
			exit(EXIT_SUCCESS);
		}

		setsid();

		close(STDOUT_FILENO);
		close(STDERR_FILENO);

		dlog(LOG_NOTICE, "-- starting in daemon mode --");
	} else
		dlog(LOG_NOTICE, "-- starting in console mode --");

	sd_ct_init();

	/*
	 * run main process
	 */
	select_main_loop();
	return 0;
}
/* be_sys_init:
 */
extern "C" int be_sys_init(void)
{
    int32       cookie;
    thread_info info;
    struct utsname os_name;
    char path[MAXPATHLEN];

    cookie = 0;

    if (get_next_thread_info(0, &cookie, &info) == B_OK) {
        main_thread_id = info.thread;
    }
    else {
        goto cleanup;
    }

    _be_mouse_view_attached = create_sem(0, "waiting for mouse view attach...");

    if (_be_mouse_view_attached < 0) {
        goto cleanup;
    }

    _be_sound_stream_lock = create_sem(1, "audiostream lock");

    if (_be_sound_stream_lock < 0) {
        goto cleanup;
    }

    system_started = create_sem(0, "starting system driver...");

    if(system_started < 0) {
        goto cleanup;
    }

    system_thread_id = spawn_thread(system_thread, SYS_THREAD_NAME,
                                    SYS_THREAD_PRIORITY, NULL);

    if (system_thread_id < 0) {
        goto cleanup;
    }

    resume_thread(system_thread_id);
    acquire_sem(system_started);
    delete_sem(system_started);

    uname(&os_name);
    os_type = OSTYPE_BEOS;
    os_multitasking = TRUE;

    chdir(app_path);

    _be_sys_get_executable_name(path, sizeof(path));
    path[sizeof(path)-1] = '\0';
    do_uconvert(get_filename(path), U_CURRENT, wnd_title, U_UTF8, WND_TITLE_SIZE);

    return 0;

cleanup: {
        be_sys_exit();
        return 1;
    }
}
Example #10
0
std::string GetOSVersion()
{
#if EDGE_PLATFORM_WINDOWS
	OSVERSIONINFO version_info;
	ZeroMemory(&version_info, sizeof(OSVERSIONINFO));
	version_info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);

#pragma warning(disable:4996)
	GetVersionEx(&version_info);
#pragma warning(default:4996)
	return std::to_string(version_info.dwMajorVersion).append(".").append(std::to_string(version_info.dwMinorVersion));
#elif EDGE_PLATFORM_NIX
	std::vector<std::string> qualifiers{ "ID=", "VERSION_ID=" };

	std::ifstream lsbRelease;
	lsbRelease.open("/etc/os-release", std::ifstream::in);

	if (lsbRelease.is_open())
	{
		std::string osVersion;

		for (std::string line; std::getline(lsbRelease, line); )
		{
			for (auto& qualifier : qualifiers)
			{
				if (line.compare(0, qualifier.length(), qualifier) == 0)
				{
					auto value = line.substr(qualifier.length());

					if (value.length() >= 2 && ((value[0] == '"'  && value[value.length() - 1] == '"') || (value[0] == '\'' && value[value.length() - 1] == '\'')))
					{
						value = value.substr(1, value.length() - 2);
					}

					if (value.length() == 0)
					{
						continue;
					}

					if (osVersion.length() > 0)
					{
						osVersion += " ";
					}

					osVersion += value;
				}
			}
		}

		return osVersion;
	}

	return "";
#elif EDGE_PLATFORM_APPLE
	utsname unameData;

	if (uname(&unameData) == 0)
	{
		std::string release = unameData.release;

		auto dot_position = release.find(".");

		if (dot_position == std::string::npos)
		{
			return "10.1";
		}

		auto version = atoi(release.substr(0, dot_position).c_str());
        std::stringstream versionStringStream;
        versionStringStream << (version - 4);

		return std::string("10.").append(versionStringStream.str());
	}

	else
	{
		return "10.1";
	}
#endif
}
Example #11
0
errcode_t io_open(const char *name, int flags, io_channel **channel)
{
	errcode_t ret;
	io_channel *chan = NULL;
#ifdef __linux__
	struct stat stat_buf;
	struct utsname ut;
#endif

	if (!name || !*name)
		return OCFS2_ET_BAD_DEVICE_NAME;

	ret = ocfs2_malloc0(sizeof(struct _io_channel), &chan);
	if (ret)
		return ret;

	ret = ocfs2_malloc(strlen(name)+1, &chan->io_name);
	if (ret)
		goto out_chan;
	strcpy(chan->io_name, name);
	chan->io_blksize = OCFS2_MIN_BLOCKSIZE;
	chan->io_flags = (flags & OCFS2_FLAG_RW) ? O_RDWR : O_RDONLY;
	chan->io_nocache = false;
	if (!(flags & OCFS2_FLAG_BUFFERED))
		chan->io_flags |= O_DIRECT;
	chan->io_error = 0;

	chan->io_fd = open64(name, chan->io_flags);
	if (chan->io_fd < 0) {
		/* chan will be freed, don't bother with chan->io_error */
		if (errno == ENOENT)
			ret = OCFS2_ET_NAMED_DEVICE_NOT_FOUND;
		else
			ret = OCFS2_ET_IO;
		goto out_name;
	}

	if (!(flags & OCFS2_FLAG_BUFFERED)) {
		ret = io_validate_o_direct(chan);
		if (ret)
			goto out_close;  /* FIXME: bindraw here */
	}

	/* Workaround from e2fsprogs */
#ifdef __linux__
#undef RLIM_INFINITY
#if (defined(__alpha__) || ((defined(__sparc__) || defined(__mips__)) && (SIZEOF_LONG == 4)))
#define RLIM_INFINITY	((unsigned long)(~0UL>>1))
#else
#define RLIM_INFINITY  (~0UL)
#endif
	/*
	 * Work around a bug in 2.4.10-2.4.18 kernels where writes to
	 * block devices are wrongly getting hit by the filesize
	 * limit.  This workaround isn't perfect, since it won't work
	 * if glibc wasn't built against 2.2 header files.  (Sigh.)
	 * 
	 */
	if ((flags & OCFS2_FLAG_RW) &&
	    (uname(&ut) == 0) &&
	    ((ut.release[0] == '2') && (ut.release[1] == '.') &&
	     (ut.release[2] == '4') && (ut.release[3] == '.') &&
	     (ut.release[4] == '1') && (ut.release[5] >= '0') &&
	     (ut.release[5] < '8')) &&
	    (fstat(chan->io_fd, &stat_buf) == 0) &&
	    (S_ISBLK(stat_buf.st_mode))) {
		struct rlimit	rlim;
		
		rlim.rlim_cur = rlim.rlim_max = (unsigned long) RLIM_INFINITY;
		setrlimit(RLIMIT_FSIZE, &rlim);
		getrlimit(RLIMIT_FSIZE, &rlim);
		if (((unsigned long) rlim.rlim_cur) <
		    ((unsigned long) rlim.rlim_max)) {
			rlim.rlim_cur = rlim.rlim_max;
			setrlimit(RLIMIT_FSIZE, &rlim);
		}
	}
#endif

	*channel = chan;
	return 0;

out_close:
	/* Ignore the return, leave the original error */
	close(chan->io_fd);

out_name:
	ocfs2_free(&chan->io_name);

out_chan:
	ocfs2_free(&chan);

	*channel = NULL;
	return ret;
}
Example #12
0
int
main(int argc, char **argv)
#endif
{
    int i;

#ifdef LINUXVGA
    LINUX_setup();		/* setup VGA before dropping privilege DBT 4/5/99 */
    drop_privilege();
#endif
/* make sure that we really have revoked root access, this might happen if
   gnuplot is compiled without vga support but is installed suid by mistake */
#ifdef __linux__
    setuid(getuid());
#endif

#if defined(MSDOS) && !defined(_Windows) && !defined(__GNUC__)
    PC_setup();
#endif /* MSDOS !Windows */

/* HBB: Seems this isn't needed any more for DJGPP V2? */
/* HBB: disable all floating point exceptions, just keep running... */
#if defined(DJGPP) && (DJGPP!=2)
    _control87(MCW_EM, MCW_EM);
#endif

#if defined(OS2)
    int rc;
#ifdef OS2_IPC
    char semInputReadyName[40];
    sprintf( semInputReadyName, "\\SEM32\\GP%i_Input_Ready", getpid() );
    rc = DosCreateEventSem(semInputReadyName,&semInputReady,0,0);
    if (rc != 0)
      fputs("DosCreateEventSem error\n",stderr);
#endif
    rc = RexxRegisterSubcomExe("GNUPLOT", (PFN) RexxInterface, NULL);
#endif

/* malloc large blocks, otherwise problems with fragmented mem */
#ifdef OSK
    _mallocmin(102400);
#endif

#ifdef MALLOCDEBUG
    malloc_debug(7);
#endif

/* get helpfile from home directory */
#ifndef DOSX286
# ifndef _Windows
#  if defined (__TURBOC__) && (defined (MSDOS) || defined(DOS386))
    strcpy(HelpFile, argv[0]);
    strcpy(strrchr(HelpFile, DIRSEP1), "\\gnuplot.gih");
#  endif			/*   - DJL */
# endif				/* !_Windows */
#endif /* !DOSX286 */
#ifdef __DJGPP__
    {
	char *s;
	strcpy(HelpFile, argv[0]);
	for (s = HelpFile; *s; s++)
	    if (*s == DIRSEP1)
		*s = DIRSEP2;	/* '\\' to '/' */
	strcpy(strrchr(HelpFile, DIRSEP2), "/gnuplot.gih");
    }			/* Add also some "paranoid" tests for '\\':  AP */
#endif /* DJGPP */

#ifdef VMS
    unsigned int status[2] = { 1, 0 };
#endif

#if defined(HAVE_LIBEDITLINE)
    rl_getc_function = getc_wrapper;
#endif
#if defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)
    using_history();
    /* T.Walter 1999-06-24: 'rl_readline_name' must be this fix name.
     * It is used to parse a 'gnuplot' specific section in '~/.inputrc' */
    rl_readline_name = "Gnuplot";
    rl_terminal_name = getenv("TERM");
#endif
#if defined(HAVE_LIBREADLINE)
    rl_complete_with_tilde_expansion = 1;
#endif

    for (i = 1; i < argc; i++) {
	if (!argv[i])
	    continue;

	if (!strcmp(argv[i], "-V") || !strcmp(argv[i], "--version")) {
	    printf("gnuplot %s patchlevel %s\n",
		    gnuplot_version, gnuplot_patchlevel);
	    return 0;

	} else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
	    printf( "Usage: gnuplot [OPTION]... [FILE]\n"
#ifdef X11
		    "for X11 options see 'help X11->command-line-options'\n"
#endif
		    "  -V, --version\n"
		    "  -h, --help\n"
		    "  -p  --persist\n"
		    "  -e  \"command1; command2; ...\"\n"
		    "gnuplot %s patchlevel %s\n"
#ifdef DIST_CONTACT
		    "Report bugs to "DIST_CONTACT"\n"
		    "            or %s\n",
#else
		    "Report bugs to %s\n",
#endif
		    gnuplot_version, gnuplot_patchlevel, bug_report);
	    return 0;

	} else if (!strncmp(argv[i], "-persist", 2) || !strcmp(argv[i], "--persist")) {
	    persist_cl = TRUE;
	}
    }

#ifdef X11
    /* the X11 terminal removes tokens that it recognizes from argv. */
    {
	int n = X11_args(argc, argv);
	argv += n;
	argc -= n;
    }
#endif

#ifdef APOLLO
    apollo_pfm_catch();
#endif

    setbuf(stderr, (char *) NULL);

#ifdef HAVE_SETVBUF
    /* this was once setlinebuf(). Docs say this is
     * identical to setvbuf(,NULL,_IOLBF,0), but MS C
     * faults this (size out of range), so we try with
     * size of 1024 instead. [SAS/C does that, too. -lh]
     * Failing this, I propose we just make the call and
     * ignore the return : its probably not a big deal
     */
    if (setvbuf(stdout, (char *) NULL, _IOLBF, (size_t) 1024) != 0)
	(void) fputs("Could not linebuffer stdout\n", stderr);

#ifdef X11
    /* This call used to be in x11.trm, with the following comment:
     *   Multi-character inputs like escape sequences but also mouse-pasted
     *   text got buffered and therefore didn't trigger the select() function
     *   in X11_waitforinput(). Switching to unbuffered input solved this.
     *   23 Jan 2002 (joze)
     * But switching to unbuffered mode causes all characters in the input
     * buffer to be lost. So the only safe time to do it is on program entry.
     * The #ifdef X11 is probably unnecessary, but makes the change minimal.
     * Do any non-X platforms suffer from the same problem?
     * EAM - Jan 2004.
     */
    setvbuf(stdin, (char *) NULL, _IONBF, 0);
#endif

#endif

    gpoutfile = stdout;

    /* Initialize pre-loaded user variables */
    (void) Gcomplex(&udv_pi.udv_value, M_PI, 0.0);
#ifdef HAVE_ISNAN
    udv_NaN = add_udv_by_name("NaN");
    (void) Gcomplex(&(udv_NaN->udv_value), not_a_number(), 0.0);
    udv_NaN->udv_undef = FALSE;
#endif

    init_memory();

    interactive = FALSE;
    init_terminal();		/* can set term type if it likes */
    push_terminal(0);		/* remember the default terminal */

    /* reset the terminal when exiting */
    /* this is done through gp_atexit so that other terminal functions
     * can be registered to be executed before the terminal is reset. */
    GP_ATEXIT(term_reset);

#ifdef AMIGA_SC_6_1
    if (IsInteractive(Input()) == DOSTRUE)
	interactive = TRUE;
    else
	interactive = FALSE;
#else
# if ((defined(__MSC__) && defined(_Windows)) || defined(__WIN32__)) && ! defined(WGP_CONSOLE)
    interactive = TRUE;
# else
    interactive = isatty(fileno(stdin));
# endif
#endif /* !AMIGA_SC_6_1 */

    if (argc > 1)
	interactive = noinputfiles = FALSE;
    else
	noinputfiles = TRUE;

    /* Need this before show_version is called for the first time */

#ifdef HAVE_SYS_UTSNAME_H
    {
	struct utsname uts;

	/* something is fundamentally wrong if this fails ... */
	if (uname(&uts) > -1) {
# ifdef _AIX
	    strcpy(os_name, uts.sysname);
	    sprintf(os_name, "%s.%s", uts.version, uts.release);
# elif defined(SCO)
	    strcpy(os_name, "SCO");
	    strcpy(os_rel, uts.release);
# elif defined(DJGPP)
	    if (!strncmp(uts.sysname, "??Un", 4)) /* don't print ??Unknow" */
		strcpy(os_name, "Unknown");
	    else {
		strcpy(os_name, uts.sysname);
		strcpy(os_rel, uts.release);
	    }
# else
	    strcpy(os_name, uts.sysname);
	    strcpy(os_rel, uts.release);
# ifdef OS2
	    if (!strchr(os_rel,'.'))
		/* write either "2.40" or "4.0", or empty -- don't print "OS/2 1" */
		strcpy(os_rel, "");
# endif

# endif
	}
    }
#else /* ! HAVE_SYS_UTSNAME_H */

    strcpy(os_name, OS);
    strcpy(os_rel, "");

#endif /* HAVE_SYS_UTSNAME_H */

    if (interactive)
	show_version(stderr);
    else
	show_version(NULL); /* Only load GPVAL_COMPILE_OPTIONS */

    update_gpval_variables(3);  /* update GPVAL_ variables available to user */

#ifdef VMS
    /* initialise screen management routines for command recall */
    if (status[1] = smg$create_virtual_keyboard(&vms_vkid) != SS$_NORMAL)
	done(status[1]);
    if (status[1] = smg$create_key_table(&vms_ktid) != SS$_NORMAL)
	done(status[1]);
#endif /* VMS */

    if (!SETJMP(command_line_env, 1)) {
	/* first time */
	interrupt_setup();
	/* should move this stuff another initialisation routine,
	 * something like init_set() maybe */
	get_user_env();
	init_loadpath();
	init_locale();
	/* HBB: make sure all variables start in the same mode 'reset'
	 * would set them to. Since the axis variables aren't in
	 * initialized arrays any more, this is now necessary... */
	reset_command();
	init_color();  /*  Initialization of color  */
	load_rcfile();
	init_fit();		/* Initialization of fitting module */

	if (interactive && term != 0) {		/* not unknown */
#ifdef GNUPLOT_HISTORY
	    FPRINTF((stderr, "Before read_history\n"));
#if defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)
	    expanded_history_filename = tilde_expand(GNUPLOT_HISTORY_FILE);
#else
	    expanded_history_filename = gp_strdup(GNUPLOT_HISTORY_FILE);
	    gp_expand_tilde(&expanded_history_filename);
#endif
	    FPRINTF((stderr, "expanded_history_filename = %s\n", expanded_history_filename));
	    read_history(expanded_history_filename);
	    {
		/* BEGIN: Go local to get environment variable */
		const char *temp_env = getenv ("GNUPLOT_HISTORY_SIZE");
		if (temp_env)
		    gnuplot_history_size = strtol (temp_env, (char **) NULL, 10);
	    } /* END: Go local to get environment variable */

	    /*
	     * It is safe to ignore the return values of 'atexit()' and
	     * 'on_exit()'. In the worst case, there is no history of your
	     * currrent session and you have to type all again in your next
	     * session.
	     * This is the default behaviour (traditional reasons), too.
	     * In case you don't have one of these functions, or you don't
	     * want to use them, 'write_history()' is called directly.
	     */
	    GP_ATEXIT(wrapper_for_write_history);
#endif /* GNUPLOT_HISTORY */

	    fprintf(stderr, "\nTerminal type set to '%s'\n", term->name);
	}			/* if (interactive && term != 0) */
    } else {
	/* come back here from int_error() */
	if (interactive == FALSE)
	    exit_status = EXIT_FAILURE;
#ifdef HAVE_LIBREADLINE
	else
	{
	    /* reset properly readline after a SIGINT+longjmp */
	    rl_reset_after_signal ();
	}
#endif

#ifdef AMIGA_SC_6_1
	(void) rawcon(0);
#endif
	load_file_error();	/* if we were in load_file(), cleanup */
	reset_eval_depth();     /* reset evaluate command recursion counter */
	SET_CURSOR_ARROW;

#ifdef VMS
	/* after catching interrupt */
	/* VAX stuffs up stdout on SIGINT while writing to stdout,
	   so reopen stdout. */
	if (gpoutfile == stdout) {
	    if ((stdout = freopen("SYS$OUTPUT", "w", stdout)) == NULL) {
		/* couldn't reopen it so try opening it instead */
		if ((stdout = fopen("SYS$OUTPUT", "w")) == NULL) {
		    /* don't use int_error here - causes infinite loop! */
		    fputs("Error opening SYS$OUTPUT as stdout\n", stderr);
		}
	    }
	    gpoutfile = stdout;
	}
#endif /* VMS */
	if (!interactive && !noinputfiles) {
	    term_reset();
	    exit(EXIT_FAILURE);	/* exit on non-interactive error */
	}
    }

    if (argc > 1) {
#ifdef _Windows
	TBOOLEAN noend = persist_cl;
#endif

	/* load filenames given as arguments */
	while (--argc > 0) {
	    ++argv;
	    c_token = NO_CARET;	/* in case of file not found */
#ifdef _Windows
	    if (stricmp(*argv, "-noend") == 0 || stricmp(*argv, "/noend") == 0
	       	|| stricmp(*argv, "-persist") == 0)
		noend = TRUE;
	    else
#endif
	    if (!strncmp(*argv, "-persist", 2) || !strcmp(*argv, "--persist")) {
		FPRINTF((stderr,"'persist' command line option recognized\n"));

	    } else if (strcmp(*argv, "-") == 0) {
		/* DBT 10-7-98  go interactive if "-" on command line */

		interactive = TRUE;
		/* will this work on all platforms? */

		while (!com_line());

		interactive = FALSE;

	    } else if (strcmp(*argv, "-e") == 0) {
		--argc; ++argv;
		if (argc <= 0) {
		    fprintf(stderr, "syntax:  gnuplot -e \"commands\"\n");
		    return 0;
		}
		do_string(*argv, FALSE);

	    } else
		load_file(loadpath_fopen(*argv, "r"), gp_strdup(*argv), FALSE);
	}
#ifdef _Windows
	if (noend) {
	    interactive = TRUE;
	    while (!com_line());
	}
#endif
    } else {
	/* take commands from stdin */
	while (!com_line());
    }

#if (defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)) && defined(GNUPLOT_HISTORY)
#if !defined(HAVE_ATEXIT) && !defined(HAVE_ON_EXIT)
    /* You should be here if you neither have 'atexit()' nor 'on_exit()' */
    wrapper_for_write_history();
#endif /* !HAVE_ATEXIT && !HAVE_ON_EXIT */
#endif /* (HAVE_LIBREADLINE || HAVE_LIBEDITLINE) && GNUPLOT_HISTORY */

#ifdef OS2
    RexxDeregisterSubcom("GNUPLOT", NULL);
#endif

    /* HBB 20040223: Not all compilers like exit() to end main() */
    /* exit(exit_status); */
    return exit_status;
}
Example #13
0
int
main(int argc, char **argv)
{
    extern char *optarg;
    extern int optind;
    char *zooname = NULL;	/* name of the zoo file to use */
    char *filename = "/dev/null";	/* filename to read test tags from */
    char *logfilename = NULL;
    char *failcmdfilename = NULL;
    char *outputfilename = NULL;
    struct collection *coll = NULL;
    struct tag_pgrp *running;
    struct orphan_pgrp *orphans, *orph;
	struct utsname unamebuf;
    FILE *logfile = NULL;
    FILE *failcmdfile = NULL;
    int keep_active = 1;
    int num_active = 0;
	int failcnt = 0;           /* count of total testcases that failed. */
    int err, i;
    int starts = -1;
    int timed = 0;
    int run_time = -1; char modifier = 'm'; int ret = 0;
    int stop;
    int go_idle;
    int has_brakes = 0;		/* stop everything if a test case fails */
    int sequential = 0;		/* run tests sequentially */
    int fork_in_road = 0;
    int exit_stat;
    int track_exit_stats = 0;	/* exit non-zero if any test exits non-zero */
	int fmt_print = 0;          /* enables formatted printing of logfiles. */
	int quiet_mode = 0;			/* supresses test start and test end tags. */
    int c;
    pid_t cpid;
    struct sigaction sa;

    while ((c = getopt(argc, argv, "AO:Sa:C:d:ef:hl:n:o:pqr:s:t:x:y")) != -1) {
	switch (c) {
	case 'A':	/* all-stop flag */
	    has_brakes = 1;
	    track_exit_stats = 1;
	    break;
	case 'O':	/* output buffering directory */
	    test_out_dir = strdup(optarg);
	    break;
	case 'S':	/* run tests sequentially */
	    sequential = 1;
	    break;
	case 'a':	/* name of the zoo file to use */
	    zooname = strdup(optarg);
	    break;
	case 'C':	/* name of the file where all failed commands will be */
	    failcmdfilename = strdup(optarg);
	    break;
	case 'd':	/* debug options */
	    sscanf(optarg, "%i", &Debug);
	    break;
	case 'e':	/* exit non-zero if any test exists non-zero */
	    track_exit_stats = 1;
	    break;
	case 'f':	/* filename to read test tags from */
	    filename = strdup(optarg);
	    break;
	case 'h':	/* help */
	    fprintf(stdout, "Usage: pan -n name [ -SyAehpq ] [ -s starts ]"
				 " [-t time[s|m|h|d] [ -x nactive ] [ -l logfile ]\n\t"
				 "[ -a active-file ] [ -f command-file ] "
				 "[ -C fail-command-file ] "
				 "[ -d debug-level ]\n\t[-o output-file] "
				 "[-O output-buffer-directory] [cmd]\n");
	    exit(0);
	case 'l':	/* log file */
	    logfilename = strdup(optarg);
	    break;
	case 'n':	/* tag given to pan */
	    panname = strdup(optarg);
	    break;
	case 'o':	/* send test output here */
	    outputfilename = strdup(optarg);
	    break;
	case 'p':	/* formatted printing. */
		fmt_print = 1;
		break;
	case 'q':	/* supress test start and test end messages */
		quiet_mode = 1;
		break;
	case 'r':	/* reporting type: none, rts */
	    reporttype = strdup(optarg);
	    break;
	case 's':	/* number of tags to run */
	    starts = atoi(optarg);
	    break;
	case 't':	/* run_time to run */
	    ret = sscanf(optarg, "%d%c", &run_time, &modifier);
            if (ret == 0) { fprintf(stderr, "Need proper time input: ####x where"
                                    "x is one of s,m,h,d\n"); break; }
            else if (ret == 1) { fprintf(stderr, "Only got a time value of %d "
                                 "modifiers need to come immediately after #"
                                 " assuming %c\n", run_time, modifier); }
            else
            {
               switch (modifier)
               {
                  case 's': run_time = run_time; break; 
                  case 'm': run_time = run_time * 60; break; 
                  case 'h': run_time = run_time * 60 * 60; break; 
                  case 'd': run_time = run_time * 60 * 60 * 24; break;
                  default: 
                     fprintf(stderr, "Invalid time modifier, try: s|h|m|d\n"); exit(-1);
               }
	       if (!quiet_mode)
                  printf("PAN will run for %d seconds\n", run_time);
            }
            timed = 1; //-t implies run as many starts as possible, by default
	    break;
	case 'x':	/* number of tags to keep running */
	    keep_active = atoi(optarg);
	    break;
	case 'y':	/* restart on failure or signal */
	    fork_in_road = 1;
	    break;
	}
    }

    if (panname == NULL) {
	fprintf(stderr, "pan: Must supply -n\n");
	exit(1);
    }
    if (zooname == NULL) {
	zooname = zoo_getname();
	if (zooname == NULL) {
	    fprintf(stderr,
		    "pan(%s): Must supply -a or set ZOO env variable\n",
		    panname);
	    exit(1);
	}
    }
    if (reporttype) {
	/* make sure we understand the report type */
	if (strcasecmp(reporttype, "rts")
			&& strcasecmp(reporttype, "none")
			/* && strcasecmp(reporttype, "xml")*/)
	    reporttype = "rts";
    } else {
	/* set the default */
	reporttype = "rts";
    }

    if (logfilename != NULL) {
	time_t startup;
	char *s;

	if (!strcmp(logfilename, "-")) {
	    logfile = stdout;
	} else {
	    if ((logfile = fopen(logfilename, "a+")) == NULL) {
		fprintf(stderr,
			"pan(%s): Error %s (%d) opening log file '%s'\n",
			panname, strerror(errno), errno, logfilename);
		exit(1);
	    }
	}

	time(&startup);
	s = ctime(&startup);
	*(s + strlen(s) - 1) = '\0';
	if (!fmt_print)
		fprintf(logfile, "startup='%s'\n", s);
	else
	{
		fprintf(logfile, "Test Start Time: %s\n", s);
		fprintf(logfile, "-----------------------------------------\n");
		fprintf(logfile, "%-30.20s %-10.10s %-10.10s\n", 
				"Testcase", "Result", "Exit Value");
		fprintf(logfile, "%-30.20s %-10.10s %-10.10s\n",
			   	"--------", "------", "------------");
	}
    }

    coll = get_collection(filename, optind, argc, argv);
    if(!coll)
        exit(1);
    if (coll->cnt == 0) {
	fprintf(stderr,
		"pan(%s): Must supply a file collection or a command\n",
		panname);
	exit(1);
    }

    if (Debug & Dsetup)
	dump_coll(coll);

    /* a place to store the pgrps we're watching */
    running = (struct tag_pgrp *)malloc((keep_active + 1) * sizeof(struct tag_pgrp));
    if (running == NULL) {
        fprintf(stderr, "pan(%s): Failed to allocate memory: %s\n", panname,
                strerror(errno));
	exit(2);
    }
    memset(running, 0, keep_active * sizeof(struct tag_pgrp));
    running[keep_active].pgrp = -1;	/* end sentinel */

    /* a head to the orphaned pgrp list */
    orphans = (struct orphan_pgrp *) malloc(sizeof(struct orphan_pgrp));
    memset(orphans, 0, sizeof(struct orphan_pgrp));

    srand48(time(NULL) ^ (getpid() + (getpid() << 15)));

    /* Supply a default for starts.  If we are in sequential mode, use
     * the number of commands available; otherwise 1.
     */
    if (timed == 1 && starts == -1) {	/* timed, infinite by default */
	starts = -1;
    } else if (starts == -1) {
	if (sequential) {
	    starts = coll->cnt;
	} else {
	    starts = 1;
	}
    } else if (starts == 0) {	/* if the user specified infinite, set it */
	starts = -1;
    } else {			/* else, make sure we are starting at least keep_active processes */
	if (starts < keep_active)
	    starts = keep_active;
    }

    /* if we're buffering output, but we're only running on process at a time,
     * then essentially "turn off buffering"
     */
    if (test_out_dir && (keep_active == 1)) {
	free(test_out_dir);
	test_out_dir = NULL;
    }

    if (test_out_dir) {
	struct stat sbuf;

	if (stat(test_out_dir, &sbuf) < 0) {
	    fprintf(stderr,
		    "pan(%s): stat of -O arg '%s' failed.  errno: %d  %s\n",
		    panname, test_out_dir, errno, strerror(errno));
	    exit(1);
	}
	if (!S_ISDIR(sbuf.st_mode)) {
	    fprintf(stderr, "pan(%s): -O arg '%s' must be a directory.\n",
		    panname, test_out_dir);
	    exit(1);
	}
	if (access(test_out_dir, W_OK | R_OK | X_OK) < 0) {
	    fprintf(stderr,
		    "pan(%s): permission denied on -O arg '%s'.  errno: %d  %s\n",
		    panname, test_out_dir, errno, strerror(errno));
	    exit(1);
	}
    }

    if (outputfilename) {
	if (!freopen(outputfilename, "a+", stdout)) {
	    fprintf(stderr,
		    "pan(%s): Error %s (%d) opening output file '%s'\n",
		    panname, strerror(errno), errno, outputfilename);
	    exit(1);
	}
    }

    if (failcmdfilename) {
    	if (!(failcmdfile = fopen(failcmdfilename, "a+"))) {
	    fprintf(stderr,
		    "pan(%s): Error %s (%d) opening fail cmd file '%s'\n",
		    panname, strerror(errno), errno, failcmdfilename);
	    exit(1);
    	}
    }

    if ((zoofile = zoo_open(zooname)) == NULL) {
	fprintf(stderr, "pan(%s): %s\n", panname, zoo_error);
	exit(1);
    }
    if (zoo_mark_args(zoofile, getpid(), panname, argc, argv)) {
	fprintf(stderr, "pan(%s): %s\n", panname, zoo_error);
	exit(1);
    }

    /* Allocate N spaces for max-arg commands.
     * this is an "active file cleanliness" thing
     */
    {
	char *av[2], bigarg[82];

	memset(bigarg, '.', 81);
	bigarg[81] = '\0';
	av[0] = bigarg;
	av[1] = NULL;

	for (c = 0; c < keep_active; c++) {
	    if (zoo_mark_cmdline(zoofile, c, panname, "")) {
		fprintf(stderr, "pan(%s): %s\n", panname, zoo_error);
		exit(1);
	    }
	}
	for (c = 0; c < keep_active; c++) {
	    if (zoo_clear(zoofile, c)) {
		fprintf(stderr, "pan(%s): %s\n", panname, zoo_error);
		exit(1);
	    }
	}
    }

    rec_signal = send_signal = 0;
    if (run_time != -1) { alarm(run_time); }

    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    sa.sa_handler = wait_handler;

    sigaction(SIGALRM, &sa, NULL);
    sigaction(SIGINT, &sa, NULL);
    sigaction(SIGTERM, &sa, NULL);
    sigaction(SIGHUP, &sa, NULL);
    sigaction(SIGUSR1, &sa, NULL);	/* ignore fork_in_road */
    sigaction(SIGUSR2, &sa, NULL);	/* stop the scheduler */

    c = 0;			/* in this loop, c is the command index */
    stop = 0;
    exit_stat = 0;
    go_idle = 0;
    while (1) {

	while ((num_active < keep_active) && (starts != 0)) {
	    if (stop || rec_signal || go_idle)
		break;

	    if (!sequential)
		c = lrand48() % coll->cnt;

	    /* find a slot for the child */
	    for (i = 0; i < keep_active; ++i) {
		if (running[i].pgrp == 0)
		    break;
	    }
	    if (i == keep_active) {
		fprintf(stderr, "pan(%s): Aborting: i == keep_active = %d\n",
			panname, i);
		wait_handler(SIGINT);
		exit_stat++;
		break;
	    }

	    cpid = run_child(coll->ary[c], running + i, quiet_mode);
	    if (cpid != -1)
		++num_active;
	    if ((cpid != -1 || sequential) && starts > 0)
		--starts;

	    if (sequential)
		if (++c >= coll->cnt)
		    c = 0;

	} /* while( (num_active < keep_active) && (starts != 0) ) */

	if (starts == 0)
	{ 
		if (!quiet_mode)
			printf("incrementing stop\n"); 
		++stop; 
	}
	else if (starts == -1) //wjh
	{
	   FILE *f = (FILE*)-1;
	   if ((f = fopen(PAN_STOP_FILE, "r")) != 0)
	   {  printf("Got %s Stopping!\n", PAN_STOP_FILE);
		  fclose(f); unlink(PAN_STOP_FILE); stop++; 
	   }
	}

	if (rec_signal) {
	    /* propagate everything except sigusr2 */

	    if (rec_signal == SIGUSR2) {
		if (fork_in_road)
		    ++go_idle;
		else
		    ++stop;
		rec_signal = send_signal = 0;
	    } else {
		if (rec_signal == SIGUSR1)
		    fork_in_road = 0;
		propagate_signal(running, keep_active, orphans);
		if (fork_in_road)
		    ++go_idle;
		else
		    ++stop;
	    }
	}

	err = check_pids(running, &num_active, keep_active, logfile,
			 failcmdfile, orphans, fmt_print, &failcnt, quiet_mode);
	if (Debug & Drunning) {
	    pids_running(running, keep_active);
	    orphans_running(orphans);
	}
	if (err) {
	    if (fork_in_road)
		++go_idle;
	    if (track_exit_stats)
		exit_stat++;
	    if (has_brakes) {
		fprintf(stderr, "pan(%s): All stop!%s\n", panname,
			go_idle ? " (idling)" : "");
		wait_handler(SIGINT);
	    }
	}

	if (stop && (num_active == 0))
	    break;

	if (go_idle && (num_active == 0)) {
	    go_idle = 0;	/* It is idle, now resume scheduling. */
	    wait_handler(0);	/* Reset the signal ratchet. */
	}
    }

    /* Wait for orphaned pgrps */
    while (1) {
	for (orph = orphans; orph != NULL; orph = orph->next) {
	    if (orph->pgrp == 0)
		continue;
	    /* Yes, we have orphaned pgrps */
	    sleep(5);
	    if (!rec_signal) {
		/* force an artificial signal, move us
		 * through the signal ratchet.
		 */
		wait_handler(SIGINT);
	    }
	    propagate_signal(running, keep_active, orphans);
	    if (Debug & Drunning)
		orphans_running(orphans);
	    break;
	}
	if (orph == NULL)
	    break;
    }

    if (zoo_clear(zoofile, getpid())) {
	fprintf(stderr, "pan(%s): %s\n", panname, zoo_error);
	++exit_stat;
    }
    fclose(zoofile);
	if (logfile && fmt_print)
	{
		if (uname(&unamebuf) == -1)
			fprintf(stderr, "ERROR: uname(): %s\n", strerror(errno));
		fprintf(logfile, "\n-----------------------------------------------\n");
		fprintf(logfile, "Total Tests: %d\n", coll->cnt);
		fprintf(logfile, "Total Failures: %d\n", failcnt);
		fprintf(logfile, "Kernel Version: %s\n", unamebuf.release);
		fprintf(logfile, "Machine Architecture: %s\n", unamebuf.machine);
		fprintf(logfile, "Hostname: %s\n\n", unamebuf.nodename);
	}
    if (logfile && (logfile != stdout))
	fclose(logfile);

    exit(exit_stat);
}
Example #14
0
hid_device * HID_API_EXPORT hid_open_path(const char *path)
{
	hid_device *dev = NULL;

	hid_init();

	dev = new_hid_device();

	if (kernel_version == 0) {
		struct utsname name;
		int major, minor, release;
		int ret;
		uname(&name);
		ret = sscanf(name.release, "%d.%d.%d", &major, &minor, &release);
		if (ret == 3) {
			kernel_version = major << 16 | minor << 8 | release;
			//printf("Kernel Version: %d\n", kernel_version);
		}
		else {
			printf("Couldn't sscanf() version string %s\n", name.release);
		}
	}

	/* OPEN HERE */
	dev->device_handle = open(path, O_RDWR);

	/* If we have a good handle, return it. */
	if (dev->device_handle > 0) {

		/* Get the report descriptor */
		int res, desc_size = 0;
		struct hidraw_report_descriptor rpt_desc;

		memset(&rpt_desc, 0x0, sizeof(rpt_desc));

		/* Get Report Descriptor Size */
		res = ioctl(dev->device_handle, HIDIOCGRDESCSIZE, &desc_size);
		if (res < 0)
			perror("HIDIOCGRDESCSIZE");


		/* Get Report Descriptor */
		rpt_desc.size = desc_size;
		res = ioctl(dev->device_handle, HIDIOCGRDESC, &rpt_desc);
		if (res < 0) {
			perror("HIDIOCGRDESC");
		} else {
			/* Determine if this device uses numbered reports. */
			dev->uses_numbered_reports =
				uses_numbered_reports(rpt_desc.value,
				                      rpt_desc.size);
		}

		return dev;
	}
	else {
		/* Unable to open any devices. */
		free(dev);
		return NULL;
	}
}
Example #15
0
int
machine_init(struct statics * statics)
{
	struct oldproc *op,
			   *endbase;
	int			pcnt = 0;
	struct utsname utsname;
	char		tmpbuf[20];

	uname(&utsname);
	irix_ver = (float) atof((const char *) utsname.release);
	strncpy(tmpbuf, utsname.release, 9);
	tmpbuf[9] = '\0';
	sprintf(uname_str, "%s %-.14s %s %s",
			utsname.sysname, utsname.nodename,
			tmpbuf, utsname.machine);

	pagesize = getpagesize();

	if ((kmem = open(KMEM, O_RDONLY)) == -1)
	{
		perror(KMEM);
		return -1;
	}

	if (chdir(_PATH_PROCFSPI))
	{
		/* handy for later on when we're reading it */
		(void) fprintf(stderr, "%s: Unable to chdir to %s\n",
					   myname, _PATH_PROCFSPI);
		return -1;
	}
	if ((procdir = opendir(".")) == NULL)
	{
		(void) fprintf(stderr, "%s: Unable to open %s\n",
					   myname, _PATH_PROCFSPI);
		return -1;
	}

	if ((avenrun_offset = sysmp(MP_KERNADDR, MPKA_AVENRUN)) == -1)
	{
		perror("sysmp(MP_KERNADDR, MPKA_AVENRUN)");
		return -1;
	}

	allocate_proc_tables();

	oldprocs = 2 * nproc;
	endbase = oldbase + oldprocs;
	for (op = oldbase; op < endbase; op++)
	{
		op->oldpid = -1;
	}

	statics->cpustate_names = cpustatenames;
	statics->memory_names = memorynames;
	statics->order_names = ordernames;
	statics->procstate_names = procstatenames;

	return (0);
}
Example #16
0
extern int tracker_send_report(t_addrlist const * laddrs)
{
    t_addr const *     addrl;
    t_elem const *     currl;
    t_addr const *     addrt;
    t_elem const *     currt;
    t_trackpacket      packet;
    struct utsname     utsbuf;
    struct sockaddr_in tempaddr;
    t_laddr_info *     laddr_info;
    char               tempa[64];
    char               tempb[64];

    if (addrlist_get_length(track_servers) > 0)
    {
        std::memset(&packet, 0, sizeof(packet));
        bn_short_nset(&packet.packet_version, (unsigned short)TRACK_VERSION);
        /* packet.port is set below */
        bn_int_nset(&packet.flags, 0);
        std::strncpy((char *)packet.server_location,
                     prefs_get_location(),
                     sizeof(packet.server_location));
        bn_byte_set(&packet.server_location[sizeof(packet.server_location) - 1], '\0');
        std::strncpy((char *)packet.software,
                     PVPGN_SOFTWARE,
                     sizeof(packet.software));
        bn_byte_set(&packet.software[sizeof(packet.software) - 1], '\0');
        std::strncpy((char *)packet.version,
                     PVPGN_VERSION,
                     sizeof(packet.version));
        bn_byte_set(&packet.version[sizeof(packet.version) - 1], '\0');
        std::strncpy((char *)packet.server_desc,
                     prefs_get_description(),
                     sizeof(packet.server_desc));
        bn_byte_set(&packet.server_desc[sizeof(packet.server_desc) - 1], '\0');
        std::strncpy((char *)packet.server_url,
                     prefs_get_url(),
                     sizeof(packet.server_url));
        bn_byte_set(&packet.server_url[sizeof(packet.server_url) - 1], '\0');
        std::strncpy((char *)packet.contact_name,
                     prefs_get_contact_name(),
                     sizeof(packet.contact_name));
        bn_byte_set(&packet.contact_name[sizeof(packet.contact_name) - 1], '\0');
        std::strncpy((char *)packet.contact_email,
                     prefs_get_contact_email(),
                     sizeof(packet.contact_email));
        bn_byte_set(&packet.contact_email[sizeof(packet.contact_email) - 1], '\0');
        bn_int_nset(&packet.users, connlist_login_get_length());
        bn_int_nset(&packet.channels, channellist_get_length());
        bn_int_nset(&packet.games, gamelist_get_length());
        bn_int_nset(&packet.uptime, server_get_uptime());
        bn_int_nset(&packet.total_logins, connlist_total_logins());
        bn_int_nset(&packet.total_games, gamelist_total_games());

        if (uname(&utsbuf) < 0)
        {
            eventlog(eventlog_level_warn, __FUNCTION__, "could not get platform info (uname: %s)", pstrerror(errno));
            std::strncpy((char *)packet.platform, "", sizeof(packet.platform));
        }
        else
        {
            std::strncpy((char *)packet.platform,
                         utsbuf.sysname,
                         sizeof(packet.platform));
            bn_byte_set(&packet.platform[sizeof(packet.platform) - 1], '\0');
        }

        LIST_TRAVERSE_CONST(laddrs, currl)
        {
            addrl = (t_addr*)elem_get_data(currl);

            if (!(laddr_info = (t_laddr_info*)addr_get_data(addrl).p))
            {
                eventlog(eventlog_level_error, __FUNCTION__, "address data is NULL");
                continue;
            }
            if (laddr_info->type != laddr_type_bnet)
                continue; /* don't report IRC, telnet, and other non-game ports */

            bn_short_nset(&packet.port, addr_get_port(addrl));

            LIST_TRAVERSE_CONST(track_servers, currt)
            {
                addrt = (t_addr*)elem_get_data(currt);

                std::memset(&tempaddr, 0, sizeof(tempaddr));
                tempaddr.sin_family = PSOCK_AF_INET;
                tempaddr.sin_port = htons(addr_get_port(addrt));
                tempaddr.sin_addr.s_addr = htonl(addr_get_ip(addrt));

                if (!addr_get_addr_str(addrl, tempa, sizeof(tempa)))
                    std::strcpy(tempa, "x.x.x.x:x");
                if (!addr_get_addr_str(addrt, tempb, sizeof(tempb)))
                    std::strcpy(tempa, "x.x.x.x:x");
                /* eventlog(eventlog_level_debug,__FUNCTION__,"sending tracking info from %s to %s",tempa,tempb); */

                if (psock_sendto(laddr_info->usocket, &packet, sizeof(packet), 0, (struct sockaddr *)&tempaddr, (psock_t_socklen)sizeof(tempaddr)) < 0)
                    eventlog(eventlog_level_warn, __FUNCTION__, "could not send tracking information from %s to %s (psock_sendto: %s)", tempa, tempb, pstrerror(errno));
            }
Example #17
0
int main(int argc, char *argv[])
{
    FILE *procfd;
    int delay = 50;
    char tty[20] = "/dev/";
    struct utsname uname_dummy;
    char arg_dummy;
    int i;

    long j=0;
    iDebug = 5;

    if(argc < 3)
    {
        printf(help,banner,argv[0]);
        exit(0);
    }
    for(arg_dummy=3; arg_dummy < argc; arg_dummy++)
    {
        if(argv[arg_dummy][0] != '-')
        {
            printf("Error: option: %s\n", argv[arg_dummy]);
            exit(1);
        }
        switch(argv[arg_dummy][1])
        {
        case 'c':
            if(argv[arg_dummy+1] == NULL || strlen(argv[arg_dummy+1]) != 3)
                freakout("-c option needs 3 chars");
            led_config[0] = select_mode(argv[arg_dummy+1][0]);
            led_config[1] = select_mode(argv[arg_dummy+1][1]);
            led_config[2] = select_mode(argv[arg_dummy+1][2]);
            arg_dummy++;
            break;
        case 'd':
            if(argv[arg_dummy+1] == NULL)
                freakout("-d option needs an integer");
            delay = atol(argv[arg_dummy+1]);
            arg_dummy++;
            break;
        case 'f':
            options |= OPT_FORK;
            break;
        case 'i':
            options |= OPT_INVERT;
            break;
        case 'a':
            options |= OPT_ALTKBCODE;
            break;
        case 'v':
            if (options & OPT_VERBOSE)
                options |= OPT_VVERBOSE;
            else
                options |= OPT_VERBOSE;
            break;
        case 'D':
            options |= OPT_DEBUG;
            break;
        default:
            printf("Error: option: %s\n",argv[arg_dummy]);
            exit(1);
            break;
        }
    }
//if (options & OPT_VERBOSE)
//	iDebug = 2;
//if (options & OPT_VVERBOSE)
//	iDebug = 3;


    if (options & OPT_DEBUG)
    {
        if ((fOut = fopen(szOutFile, "w")) == NULL)
        {
            status_msg("failed to open output file",1);
        }
        else
        {
            status_msg("starting aifled....",2);
            status_msg("successfully created output file",3);

        }
    }

    // check if forking and verbose
//	if ((options & OPT_VERBOSE) && (options & OPT_FORK))
//		options -= OPT_VERBOSE;
//        if ((options & OPT_VVERBOSE) && (options & OPT_FORK))
//                options -= OPT_VVERBOSE;

    uname(&uname_dummy);

    sprintf(szMsg,"kernel version: %s", uname_dummy.release);
    status_msg(szMsg,3);

    if(strncmp(uname_dummy.release,"2.0",3) == 0)
        options |= OPT_KERNEL_2_0;

// Simmiyy - Extend Kernel family selection
    else if(strncmp(uname_dummy.release,"2.2",3) == 0 ||
            strncmp(uname_dummy.release,"2.4",3) == 0)
        options |= OPT_KERNEL_2_2;
//	else if(strncmp(uname_dummy.release,"2.6",3) == 0)
//		options |= OPT_KERNEL_2_6;

    strcat(tty,argv[1]);

    sprintf(szMsg,"opening tty %s...",tty);
    status_msg(szMsg,2);

    if((ttyfd = open(tty,O_RDWR)) < 0)
    {
        sprintf(szMsg,"unable to open tty %s",tty);
        status_msg(szMsg,1);
        freakout("Unable to open tty.");
    }
    else
    {
        sprintf(szMsg,"successfully opened tty %s",tty);
        status_msg(szMsg,2);
    }

    if(options & OPT_FORK)
        fork_program();
    else
        printf(banner);

//	if (options & OPT_VVERBOSE)
//		printf("running in very verbose mode...\n");
//	else if (options & OPT_VERBOSE)
//		printf("running in verbose mode...\n");

    if (options & OPT_VERBOSE)
    {
        sprintf(szMsg,"monitoring interface %s on tty %s", argv[2], argv[1]);
        status_msg(szMsg,1);

        for (i=0; i<3; i++)
        {
            sprintf(szMsg,"led%d: ", i);
            switch (led_config[i])
            {
            case IF_RX:
                strcat(szMsg,"receive");
                break;
            case IF_TX:
                strcat(szMsg,"transmit");
                break;
            case IF_COLL:
                strcat(szMsg,"collision");
                break;
            case IF_DROP_RX:
                strcat(szMsg,"drop (receive)");
                break;
            case IF_DROP_TX:
                strcat(szMsg,"drop (transmit)");
                break;
            case IF_ERR_TX:
                strcat(szMsg,"error (transmit)");
                break;
            case IF_ERR_RX:
                strcat(szMsg,"error (receive)");
                break;
            case IF_RXTX:
                strcat(szMsg,"activity");
                break;
            case IF_DROP:
                strcat(szMsg,"drop");
                break;
            case IF_ERR:
                strcat(szMsg,"error");
                break;
            case IF_NONE:
                strcat(szMsg,"none");
                break;
            case IF_ALIVE:
                strcat(szMsg,"red interface alive");
                break;
            }
            status_msg(szMsg,1);

        }
    }

    status_msg("SIGINT signal_handler....",3);
    signal(SIGINT,signal_handler);

    status_msg("SIGTERM signal_handler....",3);
    signal(SIGTERM,signal_handler);

    status_msg("update_netproc....",3);
    update_netproc(argv[2]);

    status_msg("memcpy....",3);
    memcpy(&l_if_info,&if_info,sizeof(if_info));
    while(1)
    {
//		if (options & OPT_VVERBOSE)
//		{
//printf("%5d: ",j);
//sprintf(szMsg,"%5d: ",j);
//status_msg(szMsg,2);
//j++;
//			printf("tx:%d rx:%d coll:%d tx_drop:%d rx_drop:%d err_tx:%d err_rx:%d alive:%d\n",
//				if_info[IF_TX],if_info[IF_RX],if_info[IF_COLL],if_info[IF_DROP_TX],
//				if_info[IF_DROP_RX],if_info[IF_ERR_TX],if_info[IF_ERR_RX],if_info[IF_ALIVE]);

        sprintf(szMsg,"tx:%d rx:%d coll:%d tx_drop:%d rx_drop:%d err_tx:%d err_rx:%d alive:%d",
                if_info[IF_TX],if_info[IF_RX],if_info[IF_COLL],if_info[IF_DROP_TX],
                if_info[IF_DROP_RX],if_info[IF_ERR_TX],if_info[IF_ERR_RX],if_info[IF_ALIVE]);
        status_msg(szMsg,2);
//		}

        status_msg("update_netproc....",3);
        update_netproc(argv[2]);

        status_msg("update_leds....",3);
        update_leds(tty);

        status_msg("usleep....",3);
        usleep(delay*1000);

        status_msg("done",3);
    }
    close(ttyfd);
    return 0;
}
Example #18
0
static int do_mount(const char *mnt, char **typep, mode_t rootmode,
		    int fd, const char *opts, const char *dev, char **sourcep,
		    char **mnt_optsp, off_t rootsize)
{
	int res;
	int flags = MS_NOSUID | MS_NODEV;
	char *optbuf;
	char *mnt_opts = NULL;
	const char *s;
	char *d;
	char *fsname = NULL;
	char *subtype = NULL;
	char *source = NULL;
	char *type = NULL;
	int check_empty = 1;
	int blkdev = 0;

	optbuf = (char *) malloc(strlen(opts) + 128);
	if (!optbuf) {
		fprintf(stderr, "%s: failed to allocate memory\n", progname);
		return -1;
	}

	for (s = opts, d = optbuf; *s;) {
		unsigned len;
		const char *fsname_str = "fsname=";
		const char *subtype_str = "subtype=";
		for (len = 0; s[len]; len++) {
			if (s[len] == '\\' && s[len + 1])
				len++;
			else if (s[len] == ',')
				break;
		}
		if (begins_with(s, fsname_str)) {
			if (!get_string_opt(s, len, fsname_str, &fsname))
				goto err;
		} else if (begins_with(s, subtype_str)) {
			if (!get_string_opt(s, len, subtype_str, &subtype))
				goto err;
		} else if (opt_eq(s, len, "blkdev")) {
			if (getuid() != 0) {
				fprintf(stderr,
					"%s: option blkdev is privileged\n",
					progname);
				goto err;
			}
			blkdev = 1;
		} else if (opt_eq(s, len, "nonempty")) {
			check_empty = 0;
		} else if (opt_eq(s, len, "auto_unmount")) {
			auto_unmount = 1;
		} else if (!begins_with(s, "fd=") &&
			   !begins_with(s, "rootmode=") &&
			   !begins_with(s, "user_id=") &&
			   !begins_with(s, "group_id=")) {
			int on;
			int flag;
			int skip_option = 0;
			if (opt_eq(s, len, "large_read")) {
				struct utsname utsname;
				unsigned kmaj, kmin;
				res = uname(&utsname);
				if (res == 0 &&
				    sscanf(utsname.release, "%u.%u",
					   &kmaj, &kmin) == 2 &&
				    (kmaj > 2 || (kmaj == 2 && kmin > 4))) {
					fprintf(stderr, "%s: note: 'large_read' mount option is deprecated for %i.%i kernels\n", progname, kmaj, kmin);
					skip_option = 1;
				}
			}
			if (getuid() != 0 && !user_allow_other &&
			    (opt_eq(s, len, "allow_other") ||
			     opt_eq(s, len, "allow_root"))) {
				fprintf(stderr, "%s: option %.*s only allowed if 'user_allow_other' is set in /etc/fuse.conf\n", progname, len, s);
				goto err;
			}
			if (!skip_option) {
				if (find_mount_flag(s, len, &on, &flag)) {
					if (on)
						flags |= flag;
					else
						flags  &= ~flag;
				} else {
					memcpy(d, s, len);
					d += len;
					*d++ = ',';
				}
			}
		}
		s += len;
		if (*s)
			s++;
	}
	*d = '\0';
	res = get_mnt_opts(flags, optbuf, &mnt_opts);
	if (res == -1)
		goto err;

	sprintf(d, "fd=%i,rootmode=%o,user_id=%u,group_id=%u",
		fd, rootmode, getuid(), getgid());

	if (check_empty &&
	    fuse_mnt_check_empty(progname, mnt, rootmode, rootsize) == -1)
		goto err;

	source = malloc((fsname ? strlen(fsname) : 0) +
			(subtype ? strlen(subtype) : 0) + strlen(dev) + 32);

	type = malloc((subtype ? strlen(subtype) : 0) + 32);
	if (!type || !source) {
		fprintf(stderr, "%s: failed to allocate memory\n", progname);
		goto err;
	}

	if (subtype)
		sprintf(type, "%s.%s", blkdev ? "fuseblk" : "fuse", subtype);
	else
		strcpy(type, blkdev ? "fuseblk" : "fuse");

	if (fsname)
		strcpy(source, fsname);
	else
		strcpy(source, subtype ? subtype : dev);

	res = mount(source, mnt, type, flags, optbuf);
	if (res == -1 && errno == ENODEV && subtype) {
		/* Probably missing subtype support */
		strcpy(type, blkdev ? "fuseblk" : "fuse");
		if (fsname) {
			if (!blkdev)
				sprintf(source, "%s#%s", subtype, fsname);
		} else {
			strcpy(source, type);
		}

		res = mount(source, mnt, type, flags, optbuf);
	}
	if (res == -1 && errno == EINVAL) {
		/* It could be an old version not supporting group_id */
		sprintf(d, "fd=%i,rootmode=%o,user_id=%u",
			fd, rootmode, getuid());
		res = mount(source, mnt, type, flags, optbuf);
	}
	if (res == -1) {
		int errno_save = errno;
		if (blkdev && errno == ENODEV && !fuse_mnt_check_fuseblk())
			fprintf(stderr, "%s: 'fuseblk' support missing\n",
				progname);
		else
			fprintf(stderr, "%s: mount failed: %s\n", progname,
				strerror(errno_save));
		goto err;
	}
	*sourcep = source;
	*typep = type;
	*mnt_optsp = mnt_opts;
	free(fsname);
	free(optbuf);

	return 0;

err:
	free(fsname);
	free(subtype);
	free(source);
	free(type);
	free(mnt_opts);
	free(optbuf);
	return -1;
}
Example #19
0
static uintptr_t
get_rusage_data_via_setrlimit (void)
{
  uintptr_t result;

  struct rlimit orig_limit;

# ifdef __hpux
  /* On HP-UX 11.00, setrlimit() RLIMIT_DATA of does not work: It cannot
     restore the previous limits.
     On HP-UX 11.11, setrlimit() RLIMIT_DATA of does not work: It sometimes
     has no effect on the next sbrk() call.  */
  {
    struct utsname buf;

    if (uname (&buf) == 0
        && strlen (buf.release) >= 5
        && (strcmp (buf.release + strlen (buf.release) - 5, "11.00") == 0
            || strcmp (buf.release + strlen (buf.release) - 5, "11.11") == 0))
      return 0;
  }
# endif

  /* Record the original limit.  */
  if (getrlimit (RLIMIT_DATA, &orig_limit) < 0)
    return 0;

  if (orig_limit.rlim_max != RLIM_INFINITY
      && (orig_limit.rlim_cur == RLIM_INFINITY
          || orig_limit.rlim_cur > orig_limit.rlim_max))
    /* We may not be able to restore the current rlim_cur value.
       So bail out.  */
    return 0;

  {
    /* The granularity is a single page.  */
    const intptr_t pagesize = getpagesize ();

    uintptr_t low_bound = 0;
    uintptr_t high_bound;

    for (;;)
      {
        /* Here we know that the data segment size is >= low_bound.  */
        struct rlimit try_limit;
        uintptr_t try_next = 2 * low_bound + pagesize;

        if (try_next < low_bound)
          /* Overflow.  */
          try_next = ((uintptr_t) (~ 0) / pagesize) * pagesize;

        /* There's no point in trying a value > orig_limit.rlim_max, as
           setrlimit would fail anyway.  */
        if (orig_limit.rlim_max != RLIM_INFINITY
            && orig_limit.rlim_max < try_next)
          try_next = orig_limit.rlim_max;

        /* Avoid endless loop.  */
        if (try_next == low_bound)
          {
            /* try_next could not be increased.  */
            result = low_bound;
            goto done;
          }

        try_limit.rlim_max = orig_limit.rlim_max;
        try_limit.rlim_cur = try_next;
        if (setrlimit (RLIMIT_DATA, &try_limit) == 0)
          {
            /* Allocate a page of memory, to compare the current data segment
               size with try_limit.rlim_cur.  */
            void *new_page = sbrk (pagesize);

            if (new_page != (void *)(-1))
              {
                /* The page could be added successfully.  Free it.  */
                sbrk (- pagesize);
                /* We know that the data segment size is
                   < try_limit.rlim_cur.  */
                high_bound = try_next;
                break;
              }
            else
              {
                /* We know that the data segment size is
                   >= try_limit.rlim_cur.  */
                low_bound = try_next;
              }
          }
        else
          {
            /* Here we expect only EINVAL or (on AIX) EFAULT, not EPERM.  */
            if (! errno_expected ())
              abort ();
            /* We know that the data segment size is
               >= try_limit.rlim_cur.  */
            low_bound = try_next;
          }
      }

    /* Here we know that the data segment size is
       >= low_bound and < high_bound.  */
    while (high_bound - low_bound > pagesize)
      {
        struct rlimit try_limit;
        uintptr_t try_next =
          low_bound + (((high_bound - low_bound) / 2) / pagesize) * pagesize;

        /* Here low_bound <= try_next < high_bound.  */
        try_limit.rlim_max = orig_limit.rlim_max;
        try_limit.rlim_cur = try_next;
        if (setrlimit (RLIMIT_DATA, &try_limit) == 0)
          {
            /* Allocate a page of memory, to compare the current data segment
               size with try_limit.rlim_cur.  */
            void *new_page = sbrk (pagesize);

            if (new_page != (void *)(-1))
              {
                /* The page could be added successfully.  Free it.  */
                sbrk (- pagesize);
                /* We know that the data segment size is
                   < try_limit.rlim_cur.  */
                high_bound = try_next;
              }
            else
              {
                /* We know that the data segment size is
                   >= try_limit.rlim_cur.  */
                low_bound = try_next;
              }
          }
        else
          {
            /* Here we expect only EINVAL or (on AIX) EFAULT, not EPERM.  */
            if (! errno_expected ())
              abort ();
            /* We know that the data segment size is
               >= try_limit.rlim_cur.  */
            low_bound = try_next;
          }
      }

    result = low_bound;
  }

 done:
  /* Restore the original rlim_cur value.  */
  if (setrlimit (RLIMIT_DATA, &orig_limit) < 0)
    abort ();

  return result;
}
Example #20
0
void print_login_issue(const char *issue_file, const char *tty)
{
	FILE *fd;
	int c;
	char buf[256+1];
	const char *outbuf;
	time_t t;
	struct utsname uts;

	time(&t);
	uname(&uts);

	puts("\r");	/* start a new line */

	if ((fd = fopen(issue_file, "r"))) {
		while ((c = fgetc(fd)) != EOF) {
			outbuf = buf;
			buf[0] = c;
			if(c == '\n') {
				buf[1] = '\r';
				buf[2] = 0;
			} else {
				buf[1] = 0;
			}
			if (c == '\\' || c == '%') {
				c = fgetc(fd);
				switch (c) {
					case 's':
						outbuf = uts.sysname;
						break;

					case 'n':
						outbuf = uts.nodename;
						break;

					case 'r':
						outbuf = uts.release;
						break;

					case 'v':
						outbuf = uts.version;
						break;

					case 'm':
						outbuf = uts.machine;
						break;

					case 'D':
					case 'o':
						c = getdomainname(buf, sizeof(buf) - 1);
						buf[c >= 0 ? c : 0] = '\0'; 
						break;

					case 'd':
						strftime(buf, sizeof(buf), fmtstr_d, localtime(&t));
						break;

					case 't':
						strftime(buf, sizeof(buf), fmtstr_t, localtime(&t));
						break;

					case 'h':
						gethostname(buf, sizeof(buf) - 1);
						buf[sizeof(buf) - 1] = '\0';
						break;

					case 'l':
						outbuf = tty;
						break;

					default:
						buf[0] = c;
				}
			}
			fputs(outbuf, stdout);
		}

		fclose(fd);

		fflush(stdout);
	}
}
Example #21
0
LLOSInfo::LLOSInfo() :
	mMajorVer(0), mMinorVer(0), mBuild(0)
{

#if LL_WINDOWS
	OSVERSIONINFOEX osvi;
	BOOL bOsVersionInfoEx;

	// Try calling GetVersionEx using the OSVERSIONINFOEX structure.
	ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
	osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
	if(!(bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *) &osvi)))
	{
		// If OSVERSIONINFOEX doesn't work, try OSVERSIONINFO.
		osvi.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
		if(!GetVersionEx( (OSVERSIONINFO *) &osvi))
			return;
	}
	mMajorVer = osvi.dwMajorVersion;
	mMinorVer = osvi.dwMinorVersion;
	mBuild = osvi.dwBuildNumber;

	switch(osvi.dwPlatformId)
	{
	case VER_PLATFORM_WIN32_NT:
		{
			// Test for the product.
			if(osvi.dwMajorVersion <= 4)
			{
				mOSStringSimple = "Microsoft Windows NT ";
			}
			else if(osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0)
			{
				mOSStringSimple = "Microsoft Windows 2000 ";
			}
			else if(osvi.dwMajorVersion ==5 && osvi.dwMinorVersion == 1)
			{
				mOSStringSimple = "Microsoft Windows XP ";
			}
			else if(osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2)
			{
				 if(osvi.wProductType == VER_NT_WORKSTATION)
					mOSStringSimple = "Microsoft Windows XP x64 Edition ";
				 else
					 mOSStringSimple = "Microsoft Windows Server 2003 ";
			}
			else if(osvi.dwMajorVersion == 6 && osvi.dwMinorVersion == 0)
			{
				 if(osvi.wProductType == VER_NT_WORKSTATION)
					mOSStringSimple = "Microsoft Windows Vista ";
				 else mOSStringSimple = "Microsoft Windows Vista Server ";
			}
			else   // Use the registry on early versions of Windows NT.
			{
				HKEY hKey;
				WCHAR szProductType[80];
				DWORD dwBufLen;
				RegOpenKeyEx( HKEY_LOCAL_MACHINE,
							L"SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
							0, KEY_QUERY_VALUE, &hKey );
				RegQueryValueEx( hKey, L"ProductType", NULL, NULL,
								(LPBYTE) szProductType, &dwBufLen);
				RegCloseKey( hKey );
				if ( lstrcmpi( L"WINNT", szProductType) == 0 )
				{
					mOSStringSimple += "Professional ";
				}
				else if ( lstrcmpi( L"LANMANNT", szProductType) == 0 )
				{
					mOSStringSimple += "Server ";
				}
				else if ( lstrcmpi( L"SERVERNT", szProductType) == 0 )
				{
					mOSStringSimple += "Advanced Server ";
				}
			}

			std::string csdversion = utf16str_to_utf8str(osvi.szCSDVersion);
			// Display version, service pack (if any), and build number.
			std::string tmpstr;
			if(osvi.dwMajorVersion <= 4)
			{
				tmpstr = llformat("version %d.%d %s (Build %d)",
								  osvi.dwMajorVersion,
								  osvi.dwMinorVersion,
								  csdversion.c_str(),
								  (osvi.dwBuildNumber & 0xffff));
			}
			else
			{
				tmpstr = llformat("%s (Build %d)",
								  csdversion.c_str(),
								  (osvi.dwBuildNumber & 0xffff));
			}
			mOSString = mOSStringSimple + tmpstr;
		}
		break;

	case VER_PLATFORM_WIN32_WINDOWS:
		// Test for the Windows 95 product family.
		if(osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 0)
		{
			mOSStringSimple = "Microsoft Windows 95 ";
			if ( osvi.szCSDVersion[1] == 'C' || osvi.szCSDVersion[1] == 'B' )
			{
                mOSStringSimple += "OSR2 ";
			}
		} 
		if(osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 10)
		{
			mOSStringSimple = "Microsoft Windows 98 ";
			if ( osvi.szCSDVersion[1] == 'A' )
			{
                mOSStringSimple += "SE ";
			}
		} 
		if(osvi.dwMajorVersion == 4 && osvi.dwMinorVersion == 90)
		{
			mOSStringSimple = "Microsoft Windows Millennium Edition ";
		}
		mOSString = mOSStringSimple;
		break;
	}
#else
	struct utsname un;
	if(uname(&un) != -1)
	{
		mOSStringSimple.append(un.sysname);
		mOSStringSimple.append(" ");
		mOSStringSimple.append(un.release);

		mOSString = mOSStringSimple;
		mOSString.append(" ");
		mOSString.append(un.version);
		mOSString.append(" ");
		mOSString.append(un.machine);

		// Simplify 'Simple'
		std::string ostype = mOSStringSimple.substr(0, mOSStringSimple.find_first_of(" ", 0));
		if (ostype == "Darwin")
		{
			// Only care about major Darwin versions, truncate at first '.'
			S32 idx1 = mOSStringSimple.find_first_of(".", 0);
			std::string simple = mOSStringSimple.substr(0, idx1);
			if (simple.length() > 0)
				mOSStringSimple = simple;
		}
		else if (ostype == "Linux")
		{
			// Only care about major and minor Linux versions, truncate at second '.'
			S32 idx1 = mOSStringSimple.find_first_of(".", 0);
			S32 idx2 = (idx1 != std::string::npos) ? mOSStringSimple.find_first_of(".", idx1+1) : std::string::npos;
			std::string simple = mOSStringSimple.substr(0, idx2);
			if (simple.length() > 0)
				mOSStringSimple = simple;
		}
	}
	else
	{
		mOSStringSimple.append("Unable to collect OS info");
		mOSString = mOSStringSimple;
	}
#endif

}
Example #22
0
int             TUNTAP_CreateInterface( char* pszTUNDevice,
                                        int   iFlags,
                                        int*  pfd,
                                        char* pszNetDevName )
{
    int fd;                        // File descriptor
#if !defined( OPTION_W32_CTCI )
    struct utsname utsbuf;

    if( uname( &utsbuf ) != 0 )
    {
        WRMSG(HHC00136, "E", "uname()", strerror( errno ) );

        return -1;
    }
#endif

    // Open TUN device
    fd = TUNTAP_Open( pszTUNDevice, O_RDWR | (iFlags & IFF_OSOCK) );

    if( fd < 0 )
    {
        WRMSG(HHC00137, "E", pszTUNDevice, strerror( errno ) );

        return -1;
    }

    *pfd = fd;

#if !defined( OPTION_W32_CTCI )
    if ( strncasecmp( utsbuf.sysname, "linux",  5 ) == 0 )
#endif
    {
        // Linux kernel (builtin tun device) or Windows
        struct hifr hifr;

        memset( &hifr, 0, sizeof( hifr ) );
        hifr.hifr_flags = iFlags & ~(iFlags & IFF_OSOCK) & 0xffff;
        if(*pszNetDevName)
            strcpy( hifr.hifr_name, pszNetDevName );

        if( TUNTAP_SetMode (fd, &hifr, iFlags) < 0 )
        {
            logmsg("nohif %x\n", IFF_NO_HERCIFC & iFlags);
            if (EPERM == errno && (IFF_NO_HERCIFC & iFlags))
                WRMSG(HHC00154, "E", hifr.hifr_name);
            else WRMSG(HHC00138, "E", hifr.hifr_name, strerror( errno ) );
            return -1;
        }

        strcpy( pszNetDevName, hifr.hifr_name );
    }
#if !defined( OPTION_W32_CTCI )
    else
    {
        // Other OS: Simply use basename of the device
        // Notes: (JAP) This is problematic at best. Until we have a
        //        clean FreeBSD compile from the base tree I can't
        //        spend a lot of time on this... so it will remain.
        //        My best guess is that this will cause other functions
        //        to fail miserably but I have no way to test it.
        // This should work on OS X with Christoph Pfisterer's TUN driver,
        //        since it does set the device name to the basename of the
        //        file. -- JRM
        char *p = strrchr( pszTUNDevice, '/' );

        if( p )
            strncpy( pszNetDevName, ++p, IFNAMSIZ );
        else
        {
            WRMSG(HHC00139, "E", pszTUNDevice );
            return -1;
        }
    }
#endif

    return 0;
}   // End of function  TUNTAP_CreateInterface()
Example #23
0
int main(void) {
    int i;
    struct utsname uts;
    
    uname(&uts);
    
    printf(
"%% Generated with " __FILE__ " on a system running %s %s\n"
"%% Note that constants may be specific to this OS and version\n"
"\n"
"-module(posix_errno).\n"
"-export([atom_to_errno/1,\n"
"         errno_to_atom/1,\n"
"         string/1])."
"\n"
"\n", uts.sysname, uts.release);
    
    /* atom_to_errno/1 */
    qsort(errors, nerrors, sizeof(errors[0]), cmp_name);
    for(i = 0; i < nerrors; i++) {
        printf("atom_to_errno(%s) -> %d;\n",
               strtolower(errors[i].name), errors[i].number);
    }
    printf("atom_to_errno(X) ->\n"
           "    erlang:error({unknown_posix_errno_atom, X}).\n");
    printf("\n");

    /* errno_to_atom/1 */
    qsort(errors, nerrors, sizeof(errors[0]), cmp_number);
    for(i = 0; i < nerrors; i++) {
        int dup = 0;
            
        /* take care of duplicates, eg EAGAIN and EWOULDBLOCK has same errno */
        if(i > 0 && errors[i-1].number == errors[i].number) {
            if(!dup)
                printf(" %%");
            printf(" %s", strtolower(errors[i].name));
            dup = 1;
        } else  {
            if(dup || i != 0)
                printf("\n");
            printf("errno_to_atom(%d) -> %s;",
                   errors[i].number, strtolower(errors[i].name));
            dup = 0;
        }
    }
    printf("\n");
    printf("errno_to_atom(X) ->\n"
           "    erlang:error({unknown_posix_errno, X}).\n");
    printf("\n");
    
    /* string/1 */
    qsort(errors, nerrors, sizeof(errors[0]), cmp_name);
    for(i = 0; i < nerrors; i++) {
        printf("string(%s) -> \"%s\";\n",
               strtolower(errors[i].name), strerror(errors[i].number));
    }
    printf("string(X) when is_integer(X) ->\n");
    printf("    string(errno_to_atom(X));\n");
    printf("string(X) ->\n"
           "    erlang:error({unknown_posix_errno_atom, X}).\n");

    return 0;
}
Example #24
0
/*
 * This function builds a list of dependency rules from /lib/modules/`uname -r`\modules.dep.
 * It then fills every modules and aliases with their default options, found by parsing
 * modprobe.conf (or modules.conf, or conf.modules).
 */
static struct dep_t *build_dep ( void )
{
	int fd;
	struct utsname un;
	struct dep_t *first = 0;
	struct dep_t *current = 0;
	char buffer[2048];
	char *filename;
	int continuation_line = 0;
	int k_version;

	k_version = 0;
	if ( uname ( &un ))
		bb_error_msg_and_die("can't determine kernel version");

	if (un.release[0] == '2') {
		k_version = un.release[2] - '0';
	}

	filename = bb_xasprintf("/lib/modules/%s/modules.dep", un.release );
	fd = open ( filename, O_RDONLY );
	if (ENABLE_FEATURE_CLEAN_UP)
		free(filename);
	if (fd < 0) {
		/* Ok, that didn't work.  Fall back to looking in /lib/modules */
		if (( fd = open ( "/lib/modules/modules.dep", O_RDONLY )) < 0 ) {
			return 0;
		}
	}

	while ( reads ( fd, buffer, sizeof( buffer ))) {
		int l = strlen ( buffer );
		char *p = 0;

		while ( l > 0 && isspace ( buffer [l-1] )) {
			buffer [l-1] = 0;
			l--;
		}

		if ( l == 0 ) {
			continuation_line = 0;
			continue;
		}

		/* Is this a new module dep description? */
		if ( !continuation_line ) {
			/* find the dep beginning */
			char *col = strchr ( buffer, ':' );
			char *dot = col;

			if ( col ) {
				/* This line is a dep description */
				char *mods;
				char *modpath;
				char *mod;

				/* Find the beginning of the module file name */
				*col = 0;
				mods = strrchr ( buffer, '/' );

				if ( !mods )
					mods = buffer; /* no path for this module */
				else
					mods++; /* there was a path for this module... */

				/* find the path of the module */
				modpath = strchr ( buffer, '/' ); /* ... and this is the path */
				if ( !modpath )
					modpath = buffer; /* module with no path */
				/* find the end of the module name in the file name */
				if ( ENABLE_FEATURE_2_6_MODULES &&
				     (k_version > 4) && ( *(col-3) == '.' ) &&
				     ( *(col-2) == 'k' ) && ( *(col-1) == 'o' ) )
					dot = col - 3;
				else
					if (( *(col-2) == '.' ) && ( *(col-1) == 'o' ))
						dot = col - 2;

				mod = bb_xstrndup ( mods, dot - mods );

				/* enqueue new module */
				if ( !current ) {
					first = current = (struct dep_t *) xmalloc ( sizeof ( struct dep_t ));
				}
				else {
					current-> m_next = (struct dep_t *) xmalloc ( sizeof ( struct dep_t ));
					current = current-> m_next;
				}
				current-> m_name  = mod;
				current-> m_path  = bb_xstrdup(modpath);
				current-> m_options = NULL;
				current-> m_isalias = 0;
				current-> m_depcnt  = 0;
				current-> m_deparr  = 0;
				current-> m_next    = 0;

				p = col + 1;
			}
			else
				/* this line is not a dep description */
				p = 0;
		}
		else
			/* It's a dep description continuation */
			p = buffer;

		while ( p && *p && isblank(*p))
			p++;

		/* p points to the first dependable module; if NULL, no dependable module */
		if ( p && *p ) {
			char *end = &buffer [l-1];
			char *deps;
			char *dep;
			char *next;
			int ext = 0;

			while ( isblank ( *end ) || ( *end == '\\' ))
				end--;

			do
			{
				/* search the end of the dependency */
				next = strchr (p, ' ' );
				if (next)
				{
					*next = 0;
					next--;
				}
				else
					next = end;

				/* find the beginning of the module file name */
				deps = strrchr ( p, '/' );

				if ( !deps || ( deps < p )) {
					deps = p;

					while ( isblank ( *deps ))
						deps++;
				}
				else
					deps++;

				/* find the end of the module name in the file name */
				if ( ENABLE_FEATURE_2_6_MODULES &&
				     (k_version > 4) && ( *(next-2) == '.' ) &&
				     ( *(next-1) == 'k' )  && ( *next == 'o' ) )
					ext = 3;
				else
					if (( *(next-1) == '.' ) && ( *next == 'o' ))
						ext = 2;

				/* Cope with blank lines */
				if ((next-deps-ext+1) <= 0)
					continue;
				dep = bb_xstrndup ( deps, next - deps - ext + 1 );

				/* Add the new dependable module name */
				current-> m_depcnt++;
				current-> m_deparr = (char **) xrealloc ( current-> m_deparr,
						sizeof ( char *) * current-> m_depcnt );
				current-> m_deparr [current-> m_depcnt - 1] = dep;

				p = next + 2;
			} while (next < end);
		}

		/* is there other dependable module(s) ? */
		if ( buffer [l-1] == '\\' )
			continuation_line = 1;
		else
			continuation_line = 0;
	}
	close ( fd );

	/*
	 * First parse system-specific options and aliases
	 * as they take precedence over the kernel ones.
	 */
	if (!ENABLE_FEATURE_2_6_MODULES
			|| ( fd = open ( "/etc/modprobe.conf", O_RDONLY )) < 0 )
		if (( fd = open ( "/etc/modules.conf", O_RDONLY )) < 0 )
			fd = open ( "/etc/conf.modules", O_RDONLY );

	if (fd >= 0) {
		include_conf (&first, &current, buffer, sizeof(buffer), fd);
		close(fd);
	}

	/* Only 2.6 has a modules.alias file */
	if (ENABLE_FEATURE_2_6_MODULES) {
		/* Parse kernel-declared aliases */
		filename = bb_xasprintf("/lib/modules/%s/modules.alias", un.release);
		if ((fd = open ( filename, O_RDONLY )) < 0) {
			/* Ok, that didn't work.  Fall back to looking in /lib/modules */
			fd = open ( "/lib/modules/modules.alias", O_RDONLY );
		}
		if (ENABLE_FEATURE_CLEAN_UP)
			free(filename);

		if (fd >= 0) {
			include_conf (&first, &current, buffer, sizeof(buffer), fd);
			close(fd);
		}
	}

	return first;
}
Example #25
0
File: main.c Project: Ga-vin/MINIX3
/*-
 * main --
 *	The main function, for obvious reasons. Initializes variables
 *	and a few modules, then parses the arguments give it in the
 *	environment and on the command line. Reads the system makefile
 *	followed by either Makefile, makefile or the file given by the
 *	-f argument. Sets the .MAKEFLAGS PMake variable based on all the
 *	flags it has received by then uses either the Make or the Compat
 *	module to create the initial list of targets.
 *
 * Results:
 *	If -q was given, exits -1 if anything was out-of-date. Else it exits
 *	0.
 *
 * Side Effects:
 *	The program exits when done. Targets are created. etc. etc. etc.
 */
int
main(int argc, char **argv)
{
	Lst targs;	/* target nodes to create -- passed to Make_Init */
	Boolean outOfDate = FALSE; 	/* FALSE if all targets up to date */
	struct stat sb, sa;
	char *p1, *path, *pwd;
	char mdpath[MAXPATHLEN];
    	const char *machine = getenv("MACHINE");
	const char *machine_arch = getenv("MACHINE_ARCH");
	char *syspath = getenv("MAKESYSPATH");
	Lst sysMkPath;			/* Path of sys.mk */
	char *cp = NULL, *start;
					/* avoid faults on read-only strings */
	static char defsyspath[] = _PATH_DEFSYSPATH;
	char found_path[MAXPATHLEN + 1];	/* for searching for sys.mk */
	struct timeval rightnow;		/* to initialize random seed */
#ifdef MAKE_NATIVE
	struct utsname utsname;
#endif

	/* default to writing debug to stderr */
	debug_file = stderr;

#ifdef SIGINFO
	(void)bmake_signal(SIGINFO, siginfo);
#endif
	/*
	 * Set the seed to produce a different random sequence
	 * on each program execution.
	 */
	gettimeofday(&rightnow, NULL);
	srandom(rightnow.tv_sec + rightnow.tv_usec);
	
	if ((progname = strrchr(argv[0], '/')) != NULL)
		progname++;
	else
		progname = argv[0];
#if defined(RLIMIT_NOFILE) && !defined(__minix)
	/*
	 * get rid of resource limit on file descriptors
	 */
	{
		struct rlimit rl;
		if (getrlimit(RLIMIT_NOFILE, &rl) != -1 &&
		    rl.rlim_cur != rl.rlim_max) {
			rl.rlim_cur = rl.rlim_max;
			(void)setrlimit(RLIMIT_NOFILE, &rl);
		}
	}
#endif

	/*
	 * Get the name of this type of MACHINE from utsname
	 * so we can share an executable for similar machines.
	 * (i.e. m68k: amiga hp300, mac68k, sun3, ...)
	 *
	 * Note that both MACHINE and MACHINE_ARCH are decided at
	 * run-time.
	 */
	if (!machine) {
#ifdef MAKE_NATIVE
	    if (uname(&utsname) == -1) {
		(void)fprintf(stderr, "%s: uname failed (%s).\n", progname,
		    strerror(errno));
		exit(2);
	    }
	    machine = utsname.machine;
#else
#ifdef MAKE_MACHINE
	    machine = MAKE_MACHINE;
#else
	    machine = "unknown";
#endif
#endif
	}

	if (!machine_arch) {
#ifndef MACHINE_ARCH
#ifdef MAKE_MACHINE_ARCH
            machine_arch = MAKE_MACHINE_ARCH;
#else
	    machine_arch = "unknown";
#endif
#else
	    machine_arch = MACHINE_ARCH;
#endif
	}

	myPid = getpid();		/* remember this for vFork() */

	/*
	 * Just in case MAKEOBJDIR wants us to do something tricky.
	 */
	Var_Init();		/* Initialize the lists of variables for
				 * parsing arguments */
	Var_Set("MACHINE", machine, VAR_GLOBAL, 0);
	Var_Set("MACHINE_ARCH", machine_arch, VAR_GLOBAL, 0);
#ifdef MAKE_VERSION
	Var_Set("MAKE_VERSION", MAKE_VERSION, VAR_GLOBAL, 0);
#endif
	Var_Set(".newline", "\n", VAR_GLOBAL, 0); /* handy for :@ loops */
	/*
	 * This is the traditional preference for makefiles.
	 */
#ifndef MAKEFILE_PREFERENCE_LIST
# define MAKEFILE_PREFERENCE_LIST "makefile Makefile"
#endif
	Var_Set(MAKEFILE_PREFERENCE, MAKEFILE_PREFERENCE_LIST,
		VAR_GLOBAL, 0);
	Var_Set(MAKE_DEPENDFILE, ".depend", VAR_GLOBAL, 0);

	create = Lst_Init(FALSE);
	makefiles = Lst_Init(FALSE);
	printVars = FALSE;
	variables = Lst_Init(FALSE);
	beSilent = FALSE;		/* Print commands as executed */
	ignoreErrors = FALSE;		/* Pay attention to non-zero returns */
	noExecute = FALSE;		/* Execute all commands */
	noRecursiveExecute = FALSE;	/* Execute all .MAKE targets */
	keepgoing = FALSE;		/* Stop on error */
	allPrecious = FALSE;		/* Remove targets when interrupted */
	queryFlag = FALSE;		/* This is not just a check-run */
	noBuiltins = FALSE;		/* Read the built-in rules */
	touchFlag = FALSE;		/* Actually update targets */
	debug = 0;			/* No debug verbosity, please. */
	jobsRunning = FALSE;

	maxJobs = DEFMAXLOCAL;		/* Set default local max concurrency */
	maxJobTokens = maxJobs;
	compatMake = FALSE;		/* No compat mode */
	ignorePWD = FALSE;

	/*
	 * Initialize the parsing, directory and variable modules to prepare
	 * for the reading of inclusion paths and variable settings on the
	 * command line
	 */

	/*
	 * Initialize various variables.
	 *	MAKE also gets this name, for compatibility
	 *	.MAKEFLAGS gets set to the empty string just in case.
	 *	MFLAGS also gets initialized empty, for compatibility.
	 */
	Parse_Init();
	if (argv[0][0] == '/' || strchr(argv[0], '/') == NULL) {
	    /*
	     * Leave alone if it is an absolute path, or if it does
	     * not contain a '/' in which case we need to find it in
	     * the path, like execvp(3) and the shells do.
	     */
	    p1 = argv[0];
	} else {
	    /*
	     * A relative path, canonicalize it.
	     */
	    p1 = realpath(argv[0], mdpath);
	    if (!p1 || *p1 != '/' || stat(p1, &sb) < 0) {
		p1 = argv[0];		/* realpath failed */
	    }
	}
	Var_Set("MAKE", p1, VAR_GLOBAL, 0);
	Var_Set(".MAKE", p1, VAR_GLOBAL, 0);
	Var_Set(MAKEFLAGS, "", VAR_GLOBAL, 0);
	Var_Set(MAKEOVERRIDES, "", VAR_GLOBAL, 0);
	Var_Set("MFLAGS", "", VAR_GLOBAL, 0);
	Var_Set(".ALLTARGETS", "", VAR_GLOBAL, 0);

	/*
	 * Set some other useful macros
	 */
	{
	    char tmp[64];
	    const char *ep;

	    if (!(ep = getenv(MAKE_LEVEL))) {
		ep = "0";
	    }
	    Var_Set(MAKE_LEVEL, ep, VAR_GLOBAL, 0);
	    snprintf(tmp, sizeof(tmp), "%u", myPid);
	    Var_Set(".MAKE.PID", tmp, VAR_GLOBAL, 0);
	    snprintf(tmp, sizeof(tmp), "%u", getppid());
	    Var_Set(".MAKE.PPID", tmp, VAR_GLOBAL, 0);
	}
	Job_SetPrefix();

	/*
	 * First snag any flags out of the MAKE environment variable.
	 * (Note this is *not* MAKEFLAGS since /bin/make uses that and it's
	 * in a different format).
	 */
#ifdef POSIX
	Main_ParseArgLine(getenv("MAKEFLAGS"));
#else
	Main_ParseArgLine(getenv("MAKE"));
#endif

	/*
	 * Find where we are (now).
	 * We take care of PWD for the automounter below...
	 */
	if (getcwd(curdir, MAXPATHLEN) == NULL) {
		(void)fprintf(stderr, "%s: getcwd: %s.\n",
		    progname, strerror(errno));
		exit(2);
	}

	MainParseArgs(argc, argv);

	/*
	 * Verify that cwd is sane.
	 */
	if (stat(curdir, &sa) == -1) {
	    (void)fprintf(stderr, "%s: %s: %s.\n",
		 progname, curdir, strerror(errno));
	    exit(2);
	}

	/*
	 * All this code is so that we know where we are when we start up
	 * on a different machine with pmake.
	 * Overriding getcwd() with $PWD totally breaks MAKEOBJDIRPREFIX
	 * since the value of curdir can vary depending on how we got
	 * here.  Ie sitting at a shell prompt (shell that provides $PWD)
	 * or via subdir.mk in which case its likely a shell which does
	 * not provide it.
	 * So, to stop it breaking this case only, we ignore PWD if
	 * MAKEOBJDIRPREFIX is set or MAKEOBJDIR contains a transform.
	 */
	if (!ignorePWD &&
	    (pwd = getenv("PWD")) != NULL &&
	    getenv("MAKEOBJDIRPREFIX") == NULL) {
		const char *makeobjdir = getenv("MAKEOBJDIR");

		if (makeobjdir == NULL || !strchr(makeobjdir, '$')) {
			if (stat(pwd, &sb) == 0 && sa.st_ino == sb.st_ino &&
			    sa.st_dev == sb.st_dev)
				(void)strncpy(curdir, pwd, MAXPATHLEN);
		}
	}
	Var_Set(".CURDIR", curdir, VAR_GLOBAL, 0);

	/*
	 * Find the .OBJDIR.  If MAKEOBJDIRPREFIX, or failing that,
	 * MAKEOBJDIR is set in the environment, try only that value
	 * and fall back to .CURDIR if it does not exist.
	 *
	 * Otherwise, try _PATH_OBJDIR.MACHINE, _PATH_OBJDIR, and
	 * finally _PATH_OBJDIRPREFIX`pwd`, in that order.  If none
	 * of these paths exist, just use .CURDIR.
	 */
	Dir_Init(curdir);
	(void)Main_SetObjdir(curdir);

	if ((path = getenv("MAKEOBJDIRPREFIX")) != NULL) {
		(void)snprintf(mdpath, MAXPATHLEN, "%s%s", path, curdir);
		(void)Main_SetObjdir(mdpath);
	} else if ((path = getenv("MAKEOBJDIR")) != NULL) {
		(void)Main_SetObjdir(path);
	} else {
		(void)snprintf(mdpath, MAXPATHLEN, "%s.%s", _PATH_OBJDIR, machine);
		if (!Main_SetObjdir(mdpath) && !Main_SetObjdir(_PATH_OBJDIR)) {
			(void)snprintf(mdpath, MAXPATHLEN, "%s%s", 
					_PATH_OBJDIRPREFIX, curdir);
			(void)Main_SetObjdir(mdpath);
		}
	}

	/*
	 * Be compatible if user did not specify -j and did not explicitly
	 * turned compatibility on
	 */
	if (!compatMake && !forceJobs) {
		compatMake = TRUE;
	}
	
	/*
	 * Initialize archive, target and suffix modules in preparation for
	 * parsing the makefile(s)
	 */
	Arch_Init();
	Targ_Init();
	Suff_Init();
	Trace_Init(tracefile);

	DEFAULT = NULL;
	(void)time(&now);

	Trace_Log(MAKESTART, NULL);
	
	/*
	 * Set up the .TARGETS variable to contain the list of targets to be
	 * created. If none specified, make the variable empty -- the parser
	 * will fill the thing in with the default or .MAIN target.
	 */
	if (!Lst_IsEmpty(create)) {
		LstNode ln;

		for (ln = Lst_First(create); ln != NULL;
		    ln = Lst_Succ(ln)) {
			char *name = (char *)Lst_Datum(ln);

			Var_Append(".TARGETS", name, VAR_GLOBAL);
		}
	} else
		Var_Set(".TARGETS", "", VAR_GLOBAL, 0);


	/*
	 * If no user-supplied system path was given (through the -m option)
	 * add the directories from the DEFSYSPATH (more than one may be given
	 * as dir1:...:dirn) to the system include path.
	 */
	if (syspath == NULL || *syspath == '\0')
		syspath = defsyspath;
	else
		syspath = bmake_strdup(syspath);

	for (start = syspath; *start != '\0'; start = cp) {
		for (cp = start; *cp != '\0' && *cp != ':'; cp++)
			continue;
		if (*cp == ':') {
			*cp++ = '\0';
		}
		/* look for magic parent directory search string */
		if (strncmp(".../", start, 4) != 0) {
			(void)Dir_AddDir(defIncPath, start);
		} else {
			if (Dir_FindHereOrAbove(curdir, start+4, 
			    found_path, sizeof(found_path))) {
				(void)Dir_AddDir(defIncPath, found_path);
			}
		}
	}
	if (syspath != defsyspath)
		free(syspath);

	/*
	 * Read in the built-in rules first, followed by the specified
	 * makefile, if it was (makefile != NULL), or the default
	 * makefile and Makefile, in that order, if it wasn't.
	 */
	if (!noBuiltins) {
		LstNode ln;

		sysMkPath = Lst_Init(FALSE);
		Dir_Expand(_PATH_DEFSYSMK,
			   Lst_IsEmpty(sysIncPath) ? defIncPath : sysIncPath,
			   sysMkPath);
		if (Lst_IsEmpty(sysMkPath))
			Fatal("%s: no system rules (%s).", progname,
			    _PATH_DEFSYSMK);
		ln = Lst_Find(sysMkPath, NULL, ReadMakefile);
		if (ln == NULL)
			Fatal("%s: cannot open %s.", progname,
			    (char *)Lst_Datum(ln));
	}

	if (!Lst_IsEmpty(makefiles)) {
		LstNode ln;

		ln = Lst_Find(makefiles, NULL, ReadAllMakefiles);
		if (ln != NULL)
			Fatal("%s: cannot open %s.", progname, 
			    (char *)Lst_Datum(ln));
	} else {
	    p1 = Var_Subst(NULL, "${" MAKEFILE_PREFERENCE "}",
		VAR_CMD, 0);
	    if (p1) {
		(void)str2Lst_Append(makefiles, p1, NULL);
		(void)Lst_Find(makefiles, NULL, ReadMakefile);
		free(p1);
	    }
	}

	/* In particular suppress .depend for '-r -V .OBJDIR -f /dev/null' */
	if (!noBuiltins || !printVars) {
	    makeDependfile = Var_Subst(NULL, "${.MAKE.DEPENDFILE:T}",
		VAR_CMD, 0);
	    doing_depend = TRUE;
	    (void)ReadMakefile(makeDependfile, NULL);
	    doing_depend = FALSE;
	}

	MakeMode(NULL);

	Var_Append("MFLAGS", Var_Value(MAKEFLAGS, VAR_GLOBAL, &p1), VAR_GLOBAL);
	if (p1)
	    free(p1);

	if (!compatMake)
	    Job_ServerStart(maxJobTokens, jp_0, jp_1);
	if (DEBUG(JOB))
	    fprintf(debug_file, "job_pipe %d %d, maxjobs %d, tokens %d, compat %d\n",
		jp_0, jp_1, maxJobs, maxJobTokens, compatMake);

	Main_ExportMAKEFLAGS(TRUE);	/* initial export */

	Check_Cwd_av(0, NULL, 0);	/* initialize it */
	

	/*
	 * For compatibility, look at the directories in the VPATH variable
	 * and add them to the search path, if the variable is defined. The
	 * variable's value is in the same format as the PATH envariable, i.e.
	 * <directory>:<directory>:<directory>...
	 */
	if (Var_Exists("VPATH", VAR_CMD)) {
		char *vpath, savec;
		/*
		 * GCC stores string constants in read-only memory, but
		 * Var_Subst will want to write this thing, so store it
		 * in an array
		 */
		static char VPATH[] = "${VPATH}";

		vpath = Var_Subst(NULL, VPATH, VAR_CMD, FALSE);
		path = vpath;
		do {
			/* skip to end of directory */
			for (cp = path; *cp != ':' && *cp != '\0'; cp++)
				continue;
			/* Save terminator character so know when to stop */
			savec = *cp;
			*cp = '\0';
			/* Add directory to search path */
			(void)Dir_AddDir(dirSearchPath, path);
			*cp = savec;
			path = cp + 1;
		} while (savec == ':');
		free(vpath);
	}

	/*
	 * Now that all search paths have been read for suffixes et al, it's
	 * time to add the default search path to their lists...
	 */
	Suff_DoPaths();

	/*
	 * Propagate attributes through :: dependency lists.
	 */
	Targ_Propagate();

	/* print the initial graph, if the user requested it */
	if (DEBUG(GRAPH1))
		Targ_PrintGraph(1);

	/* print the values of any variables requested by the user */
	if (printVars) {
		LstNode ln;

		for (ln = Lst_First(variables); ln != NULL;
		    ln = Lst_Succ(ln)) {
			char *var = (char *)Lst_Datum(ln);
			char *value;
			
			if (strchr(var, '$')) {
				value = p1 = Var_Subst(NULL, var, VAR_GLOBAL, 0);
			} else {
				value = Var_Value(var, VAR_GLOBAL, &p1);
			}
			printf("%s\n", value ? value : "");
			if (p1)
				free(p1);
		}
	} else {
		/*
		 * Have now read the entire graph and need to make a list of
		 * targets to create. If none was given on the command line,
		 * we consult the parsing module to find the main target(s)
		 * to create.
		 */
		if (Lst_IsEmpty(create))
			targs = Parse_MainName();
		else
			targs = Targ_FindList(create, TARG_CREATE);

		if (!compatMake) {
			/*
			 * Initialize job module before traversing the graph
			 * now that any .BEGIN and .END targets have been read.
			 * This is done only if the -q flag wasn't given
			 * (to prevent the .BEGIN from being executed should
			 * it exist).
			 */
			if (!queryFlag) {
				Job_Init();
				jobsRunning = TRUE;
			}

			/* Traverse the graph, checking on all the targets */
			outOfDate = Make_Run(targs);
		} else {
			/*
			 * Compat_Init will take care of creating all the
			 * targets as well as initializing the module.
			 */
			Compat_Run(targs);
		}
	}

#ifdef CLEANUP
	Lst_Destroy(targs, NULL);
	Lst_Destroy(variables, NULL);
	Lst_Destroy(makefiles, NULL);
	Lst_Destroy(create, (FreeProc *)free);
#endif

	/* print the graph now it's been processed if the user requested it */
	if (DEBUG(GRAPH2))
		Targ_PrintGraph(2);

	Trace_Log(MAKEEND, 0);

	Suff_End();
        Targ_End();
	Arch_End();
	Var_End();
	Parse_End();
	Dir_End();
	Job_End();
	Trace_End();

	return outOfDate ? 1 : 0;
}
Example #26
0
static void
xf86PrintBanner(void)
{
#if PRE_RELEASE
  xf86ErrorFVerb(0, "\n"
    "This is a pre-release version of the X server from " XVENDORNAME ".\n"
    "It is not supported in any way.\n"
    "Bugs may be filed in the bugzilla at http://bugs.freedesktop.org/.\n"
    "Select the \"xorg\" product for bugs you find in this release.\n"
    "Before reporting bugs in pre-release versions please check the\n"
    "latest version in the X.Org Foundation git repository.\n"
    "See http://wiki.x.org/wiki/GitPage for git access instructions.\n");
#endif
  xf86ErrorFVerb(0, "\nX.Org X Server %d.%d.%d",
	 XORG_VERSION_MAJOR,
	 XORG_VERSION_MINOR,
	 XORG_VERSION_PATCH);
#if XORG_VERSION_SNAP > 0
  xf86ErrorFVerb(0, ".%d", XORG_VERSION_SNAP);
#endif

#if XORG_VERSION_SNAP >= 900
  /* When the minor number is 99, that signifies that the we are making
   * a release candidate for a major version.  (X.0.0)
   * When the patch number is 99, that signifies that the we are making
   * a release candidate for a minor version.  (X.Y.0)
   * When the patch number is < 99, then we are making a release
   * candidate for the next point release.  (X.Y.Z)
   */
#if XORG_VERSION_MINOR >= 99
  xf86ErrorFVerb(0, " (%d.0.0 RC %d)", XORG_VERSION_MAJOR+1,
                 XORG_VERSION_SNAP - 900);
#elif XORG_VERSION_PATCH == 99
  xf86ErrorFVerb(0, " (%d.%d.0 RC %d)", XORG_VERSION_MAJOR,
                 XORG_VERSION_MINOR + 1, XORG_VERSION_SNAP - 900);
#else
  xf86ErrorFVerb(0, " (%d.%d.%d RC %d)", XORG_VERSION_MAJOR,
                 XORG_VERSION_MINOR, XORG_VERSION_PATCH + 1,
                 XORG_VERSION_SNAP - 900);
#endif
#endif

#ifdef XORG_CUSTOM_VERSION
  xf86ErrorFVerb(0, " (%s)", XORG_CUSTOM_VERSION);
#endif
#ifndef XORG_DATE
# define XORG_DATE "Unknown"
#endif
  xf86ErrorFVerb(0, "\nRelease Date: %s\n", XORG_DATE);
  xf86ErrorFVerb(0, "X Protocol Version %d, Revision %d\n",
         X_PROTOCOL, X_PROTOCOL_REVISION);
  xf86ErrorFVerb(0, "Build Operating System: %s %s\n", OSNAME, OSVENDOR);
#ifdef HAS_UTSNAME
  {
    struct utsname name;

    /* Linux & BSD state that 0 is success, SysV (including Solaris, HP-UX,
       and Irix) and Single Unix Spec 3 just say that non-negative is success.
       All agree that failure is represented by a negative number.
     */
    if (uname(&name) >= 0) {
      xf86ErrorFVerb(0, "Current Operating System: %s %s %s %s %s\n",
	name.sysname, name.nodename, name.release, name.version, name.machine);
#ifdef linux
      do {
	  char buf[80];
	  int fd = open("/proc/cmdline", O_RDONLY);
	  if (fd != -1) {
	    xf86ErrorFVerb(0, "Kernel command line: ");
	    memset(buf, 0, 80);
	    while (read(fd, buf, 80) > 0) {
		xf86ErrorFVerb(0, "%.80s", buf);
		memset(buf, 0, 80);
	    }
	    close(fd);
	  } 
      } while (0);
#endif
    }
  }
#endif
#if defined(BUILD_DATE) && (BUILD_DATE > 19000000)
  {
    struct tm t;
    char buf[100];

    memset(&t, 0, sizeof(t));
    memset(buf, 0, sizeof(buf));
    t.tm_mday = BUILD_DATE % 100;
    t.tm_mon = (BUILD_DATE / 100) % 100 - 1;
    t.tm_year = BUILD_DATE / 10000 - 1900;
#if defined(BUILD_TIME)
    t.tm_sec = BUILD_TIME % 100;
    t.tm_min = (BUILD_TIME / 100) % 100;
    t.tm_hour = (BUILD_TIME / 10000) % 100;
    if (strftime(buf, sizeof(buf), "%d %B %Y  %I:%M:%S%p", &t))
       xf86ErrorFVerb(0, "Build Date: %s\n", buf);
#else
    if (strftime(buf, sizeof(buf), "%d %B %Y", &t))
       xf86ErrorFVerb(0, "Build Date: %s\n", buf);
#endif
  }
#endif
#if defined(BUILDERSTRING)
  xf86ErrorFVerb(0, "%s \n", BUILDERSTRING);
#endif
  xf86ErrorFVerb(0, "Current version of pixman: %s\n",
                 pixman_version_string());
  xf86ErrorFVerb(0, "\tBefore reporting problems, check "
                 ""__VENDORDWEBSUPPORT__"\n"
                 "\tto make sure that you have the latest version.\n");
}
Example #27
0
papi_status_t
lpsched_printer_configuration_to_attributes(service_t *svc, printer_t *p,
	char *dest)
{
	PRINTER *tmp;
	char buf[BUFSIZ+1];
	struct utsname sysname;
	char **allowed = NULL, **denied = NULL;

	if ((svc == NULL) || (p == NULL) || (dest == NULL))
		return (PAPI_BAD_ARGUMENT);

	/* get the configuration DB data */
	if ((tmp = getprinter(dest)) == NULL) {
		detailed_error(svc,
			gettext("unable to read configuration data"));
		return (PAPI_DEVICE_ERROR);
	}

	/* name */
	papiAttributeListAddLPString(&p->attributes, PAPI_ATTR_REPLACE,
				"printer-name", tmp->name);
	if (tmp->name != NULL) {
		char uri[BUFSIZ];

		snprintf(uri, sizeof (uri), "lpsched://localhost/printers/%s",
				tmp->name);
		papiAttributeListAddString(&p->attributes, PAPI_ATTR_REPLACE,
				"printer-uri-supported", uri);
	}

	/* banner */
	if ((tmp->banner & BAN_OPTIONAL) == BAN_OPTIONAL)
		papiAttributeListAddString(&p->attributes, PAPI_ATTR_APPEND,
				"job-sheets-supported", "optional");
	else if (tmp->banner & BAN_NEVER)
		papiAttributeListAddString(&p->attributes, PAPI_ATTR_APPEND,
				"job-sheets-supported", "none");
	else if (tmp->banner & BAN_ALWAYS)
		papiAttributeListAddString(&p->attributes, PAPI_ATTR_APPEND,
				"job-sheets-supported", "standard");

	/* input_types */
	if (tmp->input_types != NULL) {
		int i;

		for (i = 0; tmp->input_types[i] != NULL; i++)
			papiAttributeListAddLPString(&p->attributes,
				PAPI_ATTR_APPEND, "document-format-supported",
				lp_type_to_mime_type(tmp->input_types[i]));
	}

	/* description */
	papiAttributeListAddLPString(&p->attributes, PAPI_ATTR_REPLACE,
			"printer-info", tmp->description);

	/* add lpsched specific attributes */
	papiAttributeListAddLPString(&p->attributes, PAPI_ATTR_REPLACE,
				"device-uri", tmp->device);
	papiAttributeListAddLPString(&p->attributes, PAPI_ATTR_REPLACE,
				"lpsched-dial-info", tmp->dial_info);
	papiAttributeListAddLPString(&p->attributes, PAPI_ATTR_REPLACE,
				"lpsched-fault-recovery", tmp->fault_rec);
	papiAttributeListAddLPString(&p->attributes, PAPI_ATTR_REPLACE,
				"lpsched-interface-script", tmp->interface);
	papiAttributeListAddLPString(&p->attributes, PAPI_ATTR_REPLACE,
				"lpsched-data-rate", tmp->speed);
	papiAttributeListAddLPString(&p->attributes, PAPI_ATTR_REPLACE,
				"lpsched-stty", tmp->stty);
	papiAttributeListAddBoolean(&p->attributes, PAPI_ATTR_REPLACE,
				"lpsched-login-term", tmp->login);
	papiAttributeListAddBoolean(&p->attributes, PAPI_ATTR_REPLACE,
				"lpsched-daisy", tmp->daisy);
	papiAttributeListAddLPStrings(&p->attributes, PAPI_ATTR_REPLACE,
				"lpsched-charsets", tmp->char_sets);
#ifdef CAN_DO_MODULES
	papiAttributeListAddLPStrings(&p->attributes, PAPI_ATTR_REPLACE,
				"lpsched-modules", tmp->modules);
#endif /* CAN_DO_MODULES */
	papiAttributeListAddLPStrings(&p->attributes, PAPI_ATTR_REPLACE,
				"lpsched-options", tmp->options);
	papiAttributeListAddLPStrings(&p->attributes, PAPI_ATTR_REPLACE,
				"lpsched-printer-type", tmp->printer_types);
	if (tmp->fault_alert.shcmd != NULL) {
		papiAttributeListAddLPString(&p->attributes, PAPI_ATTR_REPLACE,
				"lpsched-fault-alert-command",
				tmp->fault_alert.shcmd);
		papiAttributeListAddInteger(&p->attributes, PAPI_ATTR_REPLACE,
				"lpsched-fault-alert-threshold",
				tmp->fault_alert.Q);
		papiAttributeListAddInteger(&p->attributes, PAPI_ATTR_REPLACE,
				"lpsched-fault-alert-interval",
				tmp->fault_alert.W);
	}
	papiAttributeListAddInteger(&p->attributes, PAPI_ATTR_REPLACE,
				"lpsched-cpi-value", tmp->cpi.val);
	papiAttributeListAddInteger(&p->attributes, PAPI_ATTR_REPLACE,
				"lpsched-cpi-unit", tmp->cpi.sc);
	papiAttributeListAddInteger(&p->attributes, PAPI_ATTR_REPLACE,
				"lpsched-lpi-value", tmp->lpi.val);
	papiAttributeListAddInteger(&p->attributes, PAPI_ATTR_REPLACE,
				"lpsched-lpi-unit", tmp->lpi.sc);
	papiAttributeListAddInteger(&p->attributes, PAPI_ATTR_REPLACE,
				"lpsched-plen-value", tmp->plen.val);
	papiAttributeListAddInteger(&p->attributes, PAPI_ATTR_REPLACE,
				"lpsched-plen-unit", tmp->plen.sc);
	papiAttributeListAddInteger(&p->attributes, PAPI_ATTR_REPLACE,
				"lpsched-pwid-value", tmp->pwid.val);
	papiAttributeListAddInteger(&p->attributes, PAPI_ATTR_REPLACE,
				"lpsched-pwid-unit", tmp->pwid.sc);

	/* allow/deny list */
	load_userprinter_access(dest, &allowed, &denied);
	papiAttributeListAddLPStrings(&p->attributes, PAPI_ATTR_REPLACE,
				"requesting-user-name-allowed", allowed);
	papiAttributeListAddLPStrings(&p->attributes, PAPI_ATTR_REPLACE,
				"requesting-user-name-denied", denied);

#ifdef LP_USE_PAPI_ATTR
	if (tmp->ppd != NULL) {
		int fd;
		struct stat sbuf;

		/* construct the two URIs for the printer's PPD file */
		if (uname(&sysname) < 0) {
			/* failed to get systen name */
			sysname.nodename[0] = 0;
		}
		snprintf(buf, sizeof (buf), "file://%s%s/ppd/%s.ppd",
			sysname.nodename, ETCDIR, tmp->name);
		papiAttributeListAddString(&p->attributes, PAPI_ATTR_REPLACE,
			"ppd-file-uri", buf);

		snprintf(buf, sizeof (buf), "file://%s%s",
			sysname.nodename, tmp->ppd);
		papiAttributeListAddString(&p->attributes, PAPI_ATTR_REPLACE,
			"lpsched-printer-configure-ppd-uri", buf);
		papiAttributeListAddString(&p->attributes, PAPI_ATTR_REPLACE,
			"lpsched-ppd-source-path", tmp->ppd);

		snprintf(buf, sizeof (buf), "%s/ppd/%s.ppd", ETCDIR, tmp->name);

		/*
		 * We don't return error on any of the error conditions, we just
		 * silently return without adding the attribute.
		 */
		PPDFileToAttributesList(&p->attributes, buf);
	}
#endif

	freeprinter(tmp);

	return (PAPI_OK);
}
Example #28
0
CAMLprim value unix_gethostname(value unit)
{
  struct utsname un;
  uname(&un);
  return copy_string(un.nodename);
}
Example #29
0
void
init_system_mib(void)
{

#ifdef HAVE_UNAME
    struct utsname  utsName;

    uname(&utsName);
    snprintf(version_descr, sizeof(version_descr),
            "%s %s %s %s %s", utsName.sysname,
            utsName.nodename, utsName.release, utsName.version,
            utsName.machine);
    version_descr[ sizeof(version_descr)-1 ] = 0;
#else
#if HAVE_EXECV
    struct extensible extmp;

    /*
     * set default values of system stuff 
     */
    if (asprintf(&extmp.command, "%s -a", UNAMEPROG) < 0)
        extmp.command = NULL;
    /*
     * setup defaults 
     */
    extmp.type = EXECPROC;
    extmp.next = NULL;
    exec_command(&extmp);
    strlcpy(version_descr, extmp.output, sizeof(version_descr));
    if (strlen(version_descr) >= 1)
        version_descr[strlen(version_descr) - 1] = 0; /* chomp new line */
#else
#if (defined (WIN32) && defined (HAVE_WIN32_PLATFORM_SDK)) || defined (mingw32)
    windowsOSVersionString(version_descr, sizeof(version_descr));
#else
    strcpy(version_descr, "unknown");
#endif
#endif
#endif

#ifdef HAVE_GETHOSTNAME
    gethostname(sysName, sizeof(sysName));
#else
#ifdef HAVE_UNAME
    strlcpy(sysName, utsName.nodename, sizeof(sysName));
#else
#if defined (HAVE_EXECV) && !defined (mingw32)
    if (asprintf(&extmp.command, "%s -n", UNAMEPROG) < 0)
        extmp.command = NULL;
    /*
     * setup defaults 
     */
    extmp.type = EXECPROC;
    extmp.next = NULL;
    exec_command(&extmp);
    strlcpy(sysName, extmp.output, sizeof(sysName));
    if (strlen(sysName) >= 1)
        sysName[strlen(sysName) - 1] = 0; /* chomp new line */
#else
    strcpy(sysName, "unknown");
#endif                          /* HAVE_EXECV */
#endif                          /* HAVE_UNAME */
#endif                          /* HAVE_GETHOSTNAME */

#if (defined (WIN32) && defined (HAVE_WIN32_PLATFORM_SDK)) || defined (mingw32)
    {
      HKEY hKey;
      /* Default sysContact is the registered windows user */
      if (RegOpenKeyEx(HKEY_LOCAL_MACHINE,
                       "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", 0,
                       KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS) {
          char registeredOwner[256] = "";
          DWORD registeredOwnerSz = 256;
          if (RegQueryValueEx(hKey, "RegisteredOwner", NULL, NULL,
                              (LPBYTE)registeredOwner,
                              &registeredOwnerSz) == ERROR_SUCCESS) {
              strlcpy(sysContact, registeredOwner, sizeof(sysContact));
          }
          RegCloseKey(hKey);
      }
    }
#endif

    /* default sysObjectID */
    memcpy(sysObjectID, version_sysoid, version_sysoid_len * sizeof(oid));
    sysObjectIDByteLength = version_sysoid_len * sizeof(oid);

    {
        const oid sysDescr_oid[] = { 1, 3, 6, 1, 2, 1, 1, 1 };
        static netsnmp_watcher_info sysDescr_winfo;
        netsnmp_register_watched_scalar(
            netsnmp_create_handler_registration(
                "mibII/sysDescr", NULL, sysDescr_oid, OID_LENGTH(sysDescr_oid),
                HANDLER_CAN_RONLY),
            netsnmp_init_watcher_info(&sysDescr_winfo, version_descr, 0,
				      ASN_OCTET_STR, WATCHER_SIZE_STRLEN));
    }
    {
        const oid sysObjectID_oid[] = { 1, 3, 6, 1, 2, 1, 1, 2 };
        static netsnmp_watcher_info sysObjectID_winfo;
        netsnmp_register_watched_scalar(
            netsnmp_create_handler_registration(
                "mibII/sysObjectID", NULL,
                sysObjectID_oid, OID_LENGTH(sysObjectID_oid),
                HANDLER_CAN_RONLY),
            netsnmp_init_watcher_info6(
		&sysObjectID_winfo, sysObjectID, 0, ASN_OBJECT_ID,
                WATCHER_MAX_SIZE | WATCHER_SIZE_IS_PTR,
                MAX_OID_LEN, &sysObjectIDByteLength));
    }
    {
        const oid sysUpTime_oid[] = { 1, 3, 6, 1, 2, 1, 1, 3 };
        netsnmp_register_scalar(
            netsnmp_create_handler_registration(
                "mibII/sysUpTime", handle_sysUpTime,
                sysUpTime_oid, OID_LENGTH(sysUpTime_oid),
                HANDLER_CAN_RONLY));
    }
    {
        const oid sysContact_oid[] = { 1, 3, 6, 1, 2, 1, 1, 4 };
        static netsnmp_watcher_info sysContact_winfo;
#ifndef NETSNMP_NO_WRITE_SUPPORT
        netsnmp_register_watched_scalar(
            netsnmp_create_update_handler_registration(
                "mibII/sysContact", sysContact_oid, OID_LENGTH(sysContact_oid), 
                HANDLER_CAN_RWRITE, &sysContactSet),
            netsnmp_init_watcher_info(
                &sysContact_winfo, sysContact, SYS_STRING_LEN - 1,
                ASN_OCTET_STR, WATCHER_MAX_SIZE | WATCHER_SIZE_STRLEN));
#else  /* !NETSNMP_NO_WRITE_SUPPORT */
        netsnmp_register_watched_scalar(
            netsnmp_create_update_handler_registration(
                "mibII/sysContact", sysContact_oid, OID_LENGTH(sysContact_oid),
                HANDLER_CAN_RONLY, &sysContactSet),
            netsnmp_init_watcher_info(
                &sysContact_winfo, sysContact, SYS_STRING_LEN - 1,
                ASN_OCTET_STR, WATCHER_MAX_SIZE | WATCHER_SIZE_STRLEN));
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
    }
    {
        const oid sysName_oid[] = { 1, 3, 6, 1, 2, 1, 1, 5 };
        static netsnmp_watcher_info sysName_winfo;
#ifndef NETSNMP_NO_WRITE_SUPPORT
        netsnmp_register_watched_scalar(
            netsnmp_create_update_handler_registration(
                "mibII/sysName", sysName_oid, OID_LENGTH(sysName_oid),
                HANDLER_CAN_RWRITE, &sysNameSet),
            netsnmp_init_watcher_info(
                &sysName_winfo, sysName, SYS_STRING_LEN - 1, ASN_OCTET_STR,
                WATCHER_MAX_SIZE | WATCHER_SIZE_STRLEN));
#else  /* !NETSNMP_NO_WRITE_SUPPORT */
        netsnmp_register_watched_scalar(
            netsnmp_create_update_handler_registration(
                "mibII/sysName", sysName_oid, OID_LENGTH(sysName_oid),
                HANDLER_CAN_RONLY, &sysNameSet),
            netsnmp_init_watcher_info(
                &sysName_winfo, sysName, SYS_STRING_LEN - 1, ASN_OCTET_STR,
                WATCHER_MAX_SIZE | WATCHER_SIZE_STRLEN));
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
    }
    {
        const oid sysLocation_oid[] = { 1, 3, 6, 1, 2, 1, 1, 6 };
        static netsnmp_watcher_info sysLocation_winfo;
#ifndef NETSNMP_NO_WRITE_SUPPORT
        netsnmp_register_watched_scalar(
            netsnmp_create_update_handler_registration(
                "mibII/sysLocation", sysLocation_oid,
                OID_LENGTH(sysLocation_oid),
                HANDLER_CAN_RWRITE, &sysLocationSet),
            netsnmp_init_watcher_info(
		&sysLocation_winfo, sysLocation, SYS_STRING_LEN - 1,
		ASN_OCTET_STR, WATCHER_MAX_SIZE | WATCHER_SIZE_STRLEN));
#else  /* !NETSNMP_NO_WRITE_SUPPORT */
        netsnmp_register_watched_scalar(
            netsnmp_create_update_handler_registration(
                "mibII/sysLocation", sysLocation_oid,
                OID_LENGTH(sysLocation_oid),
                HANDLER_CAN_RONLY, &sysLocationSet),
            netsnmp_init_watcher_info(
		&sysLocation_winfo, sysLocation, SYS_STRING_LEN - 1,
		ASN_OCTET_STR, WATCHER_MAX_SIZE | WATCHER_SIZE_STRLEN));
#endif /* !NETSNMP_NO_WRITE_SUPPORT */
    }
    {
        const oid sysServices_oid[] = { 1, 3, 6, 1, 2, 1, 1, 7 };
        netsnmp_register_read_only_int_scalar(
            "mibII/sysServices", sysServices_oid, OID_LENGTH(sysServices_oid),
            &sysServices, handle_sysServices);
    }
    if (++system_module_count == 3)
        REGISTER_SYSOR_ENTRY(system_module_oid,
                             "The MIB module for SNMPv2 entities");

    sysContactSet = sysLocationSet = sysNameSet = 0;

    /*
     * register our config handlers 
     */
    snmpd_register_config_handler("sysdescr",
                                  system_parse_config_sysdescr, NULL,
                                  "description");
    snmpd_register_config_handler("syslocation",
                                  system_parse_config_sysloc, NULL,
                                  "location");
    snmpd_register_config_handler("syscontact", system_parse_config_syscon,
                                  NULL, "contact-name");
    snmpd_register_config_handler("sysname", system_parse_config_sysname,
                                  NULL, "node-name");
    snmpd_register_config_handler("psyslocation",
                                  system_parse_config_sysloc, NULL, NULL);
    snmpd_register_config_handler("psyscontact",
                                  system_parse_config_syscon, NULL, NULL);
    snmpd_register_config_handler("psysname", system_parse_config_sysname,
                                  NULL, NULL);
    snmpd_register_config_handler("sysservices",
                                  system_parse_config_sysServices, NULL,
                                  "NUMBER");
    snmpd_register_config_handler("sysobjectid",
                                  system_parse_config_sysObjectID, NULL,
                                  "OID");
    snmp_register_callback(SNMP_CALLBACK_LIBRARY, SNMP_CALLBACK_STORE_DATA,
                           system_store, NULL);
}
Example #30
0
/*
 * Returns the number of bytes in a partition
 */
blkid_loff_t blkid_get_dev_size(int fd)
{
	unsigned long long size64;
	blkid_loff_t high, low;

#ifdef DKIOCGETBLOCKCOUNT	/* For Apple Darwin */
	if (ioctl(fd, DKIOCGETBLOCKCOUNT, &size64) >= 0) {
		if (sizeof(blkid_loff_t) < sizeof(unsigned long long) &&
		    (size64 << 9) > 0xFFFFFFFF)
			return 0; /* EFBIG */
		return (blkid_loff_t)size64 << 9;
	}
#endif

#ifdef BLKGETSIZE64
	{
		int valid_blkgetsize64 = 1;
#ifdef __linux__
		struct		utsname ut;

		if ((uname(&ut) == 0) &&
		    ((ut.release[0] == '2') && (ut.release[1] == '.') &&
		     (ut.release[2] < '6') && (ut.release[3] == '.')))
			valid_blkgetsize64 = 0;
#endif
		if (valid_blkgetsize64 &&
		    ioctl(fd, BLKGETSIZE64, &size64) >= 0) {
			if (sizeof(blkid_loff_t) < sizeof(unsigned long long) &&
			    (size64 > 0xFFFFFFFF))
				return 0; /* EFBIG */
			return size64;
		}
	}
#endif /* BLKGETSIZE64 */

#ifdef BLKGETSIZE
	{
		unsigned long size;

		if (ioctl(fd, BLKGETSIZE, &size) >= 0)
			return (blkid_loff_t)size << 9;
	}
#endif

/* tested on FreeBSD 6.1-RELEASE i386 */
#ifdef DIOCGMEDIASIZE
	if (ioctl(fd, DIOCGMEDIASIZE, &size64) >= 0)
		return (off_t)size64;
#endif /* DIOCGMEDIASIZE */

#ifdef FDGETPRM
	{
		struct floppy_struct this_floppy;

		if (ioctl(fd, FDGETPRM, &this_floppy) >= 0)
			return (blkid_loff_t)this_floppy.size << 9;
	}
#endif
#ifdef HAVE_SYS_DISKLABEL_H
	{
		int part = -1;
		struct disklabel lab;
		struct partition *pp;
		char ch;
		struct stat st;

		/*
		 * This code works for FreeBSD 4.11 i386, except for the full
		 * device (such as /dev/ad0). It doesn't work properly for
		 * newer FreeBSD though. FreeBSD >= 5.0 should be covered by
		 * the DIOCGMEDIASIZE above however.
		 *
		 * Note that FreeBSD >= 4.0 has disk devices as unbuffered (raw,
		 * character) devices, so we need to check for S_ISCHR, too.
		 */
		if (fstat(fd, &st) >= 0 &&
		    (S_ISBLK(st.st_mode) || S_ISCHR(st.st_mode)))
			part = st.st_rdev & 7;

		if (part >= 0 && (ioctl(fd, DIOCGDINFO, (char *)&lab) >= 0)) {
			pp = &lab.d_partitions[part];
			if (pp->p_size)
				return pp->p_size << 9;
		}
	}
#endif /* HAVE_SYS_DISKLABEL_H */
	{
#if defined(HAVE_FSTAT64) && !defined(__OSX_AVAILABLE_BUT_DEPRECATED)
		struct stat64   st;
		if (fstat64(fd, &st) == 0)
#else
		struct stat	st;
		if (fstat(fd, &st) == 0)
#endif
			if (S_ISREG(st.st_mode))
				return st.st_size;
	}

	/*
	 * OK, we couldn't figure it out by using a specialized ioctl,
	 * which is generally the best way.  So do binary search to
	 * find the size of the partition.
	 */
	low = 0;
	for (high = 1024; valid_offset(fd, high); high *= 2)
		low = high;
	while (low < high - 1) {
		const blkid_loff_t mid = (low + high) / 2;

		if (valid_offset(fd, mid))
			low = mid;
		else
			high = mid;
	}
	return low + 1;
}