示例#1
0
文件: mutex.c 项目: Dimillian/wine
static struct mutex *create_mutex( struct directory *root, const struct unicode_str *name,
                                   unsigned int attr, int owned, const struct security_descriptor *sd )
{
    struct mutex *mutex;

    if ((mutex = create_named_object_dir( root, name, attr, &mutex_ops )))
    {
        if (get_error() != STATUS_OBJECT_NAME_EXISTS)
        {
            /* initialize it if it didn't already exist */
            mutex->count = 0;
            mutex->owner = NULL;
            mutex->abandoned = 0;
            if (owned) do_grab( mutex, current );
            if (sd) default_set_sd( &mutex->obj, sd, OWNER_SECURITY_INFORMATION|
                                                     GROUP_SECURITY_INFORMATION|
                                                     DACL_SECURITY_INFORMATION|
                                                     SACL_SECURITY_INFORMATION );
        }
    }
    return mutex;
}
示例#2
0
文件: device.c 项目: DeltaYang/wine
static struct device *create_device( struct directory *root, const struct unicode_str *name,
                                     struct device_manager *manager, unsigned int attr )
{
    struct device *device;

    if ((device = create_named_object_dir( root, name, attr, &device_ops )))
    {
        if (get_error() != STATUS_OBJECT_NAME_EXISTS)
        {
            /* initialize it if it didn't already exist */
            device->manager = manager;
            list_add_tail( &manager->devices, &device->entry );
            list_init( &device->requests );
            if (!(device->fd = alloc_pseudo_fd( &device_fd_ops, &device->obj, 0 )))
            {
                release_object( device );
                device = NULL;
            }
        }
    }
    return device;
}
示例#3
0
void	tu_file::copy_to ( membuf *dst )
// Copy remaining contents of *this into *dst.
{
	static const int BUFSIZE = 4096;

	while ( get_eof() == false )
	{
		// Make room at the end of dst.
		dst->resize ( dst->size() + BUFSIZE );
		int bytes_read = read_bytes ( ( ( char * ) dst->data() ) + dst->size() - BUFSIZE, BUFSIZE );

		if ( bytes_read < BUFSIZE )
		{
			// Didn't use everything we allocated; trim the unused bytes.
			dst->resize ( dst->size() - ( BUFSIZE - bytes_read ) );
		}

		if ( get_error() )
		{
			break;
		}
	}
}
示例#4
0
文件: socket.cpp 项目: MoLAoS/Mandate
void Socket::handleError(const char *caller) const {
	std::stringstream msg;
	int errCode = get_error();
	msg << "Socket Error in : " << caller << "() [Error code: " << errCode << "]\n";

#if defined(WIN32)
	LPVOID errMsg;
	DWORD msgRes = FormatMessage(
		FORMAT_MESSAGE_ALLOCATE_BUFFER  | FORMAT_MESSAGE_FROM_SYSTEM,
		NULL, errCode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&errMsg, 0, NULL
	);
	if (msgRes) {
		msg << "\n" << (LPTSTR)errMsg;
		LocalFree((HLOCAL)errMsg);
	} else {
		msg << "\nFormatMessage() call failed. :~( [Error code: " << GetLastError() << "]";
	}
#else
	msg << strerror(errCode);
#endif
	cout << msg.str() << endl;
	throw SocketException(msg.str());
}
示例#5
0
文件: symlink.c 项目: qqzhang/uk-1.0
struct symlink *create_symlink( struct directory *root, const struct unicode_str *name,
                                unsigned int attr, const struct unicode_str *target )
{
    struct symlink *symlink;

    if (!target->len)
    {
        set_error( STATUS_INVALID_PARAMETER );
        return NULL;
    }
    if ((symlink = create_named_object_dir( root, name, attr, &symlink_ops )) &&
        (get_error() != STATUS_OBJECT_NAME_EXISTS))
    {
        if ((symlink->target = memdup( target->str, target->len )))
            symlink->len = target->len;
        else
        {
            release_object( symlink );
            symlink = NULL;
        }
    }
    return symlink;
}
示例#6
0
文件: socket.cpp 项目: MoLAoS/Mandate
void ClientSocket::connect(const Ip &ip, int port) {
	sockaddr_in addr;
	memset(&addr, 0, sizeof(addr));

	addr.sin_family = AF_INET;
	addr.sin_addr.s_addr = inet_addr(ip.getString().c_str());
	addr.sin_port = htons(port);

	int res = ::connect(sock, reinterpret_cast<const sockaddr*>(&addr), sizeof(addr));
	if (res == SOCKET_ERROR) {
		int errCode = get_error();
		if (errCode != WOULD_BLOCK) {
			handleError(__FUNCTION__);
		} else {

			// TODO
			// wait a bit, check writable, try again
			cout << "::connect() error, WOULD_BLOCK.\n";

		}
	} else {
		setNoDelay();
	}
}
示例#7
0
文件: error.c 项目: leto/389-ds
/*
 * Format and output a call to the JavaScript alert() function.
 * The caller must ensure a JavaScript context.
 */
NSAPI_PUBLIC void output_alert(int type, char *info, char *details, int wait)
{
    char *wrapped=NULL;
    int err;

    if(type >= MAX_ERROR)
        type=DEFAULT_ERROR;

    wrapped=alert_word_wrap(details, WORD_WRAP_WIDTH, "\\n");

    if(!info) info="";
    fprintf(stdout, (wait) ? "confirm(\"" : "alert(\"");
    fprintf(stdout, "%s:%s\\n%s", error_headers[type], info, wrapped);
    if(type==FILE_ERROR || type==SYSTEM_ERROR)  {
        err = get_error();
        if(err != 0)
            fprintf(stdout,
                        "\\n\\nThe system returned error number %d, "
                        "which is %s.", err, verbose_error());
    }
    fprintf(stdout, "\");");

    FREE(wrapped);
}
示例#8
0
文件: PathMTU.c 项目: e110c0/unisono
uint32_t probe_mtu(unsigned int mtu, unsigned int *new_mtu) {
	unsigned int retry = 0;
	uint32_t error;
	int ret;
	char buf[max_mtu];
	memset(buf, 0, sizeof(buf));
	while (retry < 10) {
#ifdef DEBUG
		printf("probe_mtu retry %d\n", retry);
#endif
		ret = sendto(sockfd, buf, mtu - headerlen, 0, target, target_len);
		error = get_error(new_mtu);
#ifdef DEBUG
		printf("probe_mtu error %d\n", error);
#endif
		if (error != 0) {
			if (error != EMSGSIZE && error != ECONNREFUSED) {
				++retry;
				continue;
			} else {
				return error;
			}
		}
		data_wait();
		if (recv(sockfd, buf, sizeof(buf), MSG_DONTWAIT) > 0) {
#ifdef DEBUG
			printf("probe_mtu got response -> active port -> change port");
#endif
			set_port(target, base_port + retry);
		}
		++retry;
		continue;
	}
	// return the last error
	return error;
}
示例#9
0
/**
 * call-seq:
 *    hdfs.open(path, mode='r', options={}) -> file
 *
 * Opens a file using the supplied mode and options.  If the file cannot be
 * opened, raises a CouldNotOpenError; otherwise, returns a HDFS::File
 * object corresponding to the file.
 *
 * mode can contain any combination of the following characters:
 *
 * * *'a'*: Opens file for append access
 * * *'r'*: Opens file for read access
 * * *'w'*: Opens file for write access
 *
 * options can have the following keys:
 *
 * * *buffer_size*: size in bytes of buffer to use for file accesses
 *   (default: default buffer size as configured by HDFS)
 * * *replication*: the number of nodes this file should be replicated against
 *   (default: default replication as configured by HDFS)
 * * *block_size*: the HDFS block size in bytes to use for this file
 *   (default: default block size as configured by HDFS)
 */
VALUE HDFS_File_System_open(int argc, VALUE* argv, VALUE self) {
  FSData* data = get_FSData(self);
  VALUE path, mode, options;
  int flags = 0;
  rb_scan_args(argc, argv, "12", &path, &mode, &options);
  options = NIL_P(options) ? rb_hash_new() : options;
  // Sets file open mode if one is provided by the user.
  if (!NIL_P(mode)) {
    VALUE mode_lowercase = rb_funcall(mode, rb_intern("downcase"), 0);
    if (strstr("r", StringValuePtr(mode_lowercase)) != NULL) {
      flags |= O_RDONLY;
    } 
    if (strstr("w", StringValuePtr(mode_lowercase)) != NULL) {
      flags |= O_WRONLY;
    } 
    if (strstr("a", StringValuePtr(mode_lowercase)) != NULL) {
      flags |= O_APPEND;
    }
  } else {
    // Takes the default value of read-only mode.
    flags = O_RDONLY;
  }
  VALUE r_buffer_size = rb_hash_aref(options, rb_eval_string(":buffer_size"));
  VALUE r_replication = rb_hash_aref(options, rb_eval_string(":replication"));
  VALUE r_block_size = rb_hash_aref(options, rb_eval_string(":block_size"));
  hdfsFile file = hdfsOpenFile(data->fs, StringValuePtr(path), flags,
      RTEST(r_buffer_size) ? NUM2INT(r_buffer_size) : 0,
      RTEST(r_replication) ? NUM2INT(r_replication) : 0,
      RTEST(r_block_size) ? NUM2INT(r_block_size) : 0);
  if (file == NULL) {
    rb_raise(e_could_not_open, "Could not open file %s: %s", StringValuePtr(path),
        get_error(errno));
    return Qnil;
  }
  return new_HDFS_File(path, &file, &data->fs);
}
示例#10
0
/**
 * call-seq:
 *    hdfs.get_hosts(path, start, length) -> retval
 *
 * Returns the hostnames of the DataNodes which serve the portion of the file
 * between the provided start and length bytes.  Raises a DFSException if this
 * fails.
 */
VALUE HDFS_File_System_get_hosts(VALUE self, VALUE path, VALUE start,
    VALUE length) {
  FSData* data = get_FSData(self);
  char*** hosts = hdfsGetHosts(data->fs, StringValuePtr(path), NUM2LONG(start),
      NUM2LONG(length));
  if (hosts == NULL) {
    rb_raise(e_dfs_exception,
        "Error while retrieving hosts at path: %s, start: %s, length: %lu: %s",
        StringValuePtr(path), StringValuePtr(start), NUM2LONG(length),
        get_error(errno));
    return Qnil;
  }
  // Builds a Ruby Array object out of the hosts reported by HDFS.
  VALUE hosts_array = rb_ary_new();
  size_t i, j;
  for (i = 0; hosts[i]; i++) {
    VALUE cur_block_hosts = rb_ary_new();
    for (j = 0; hosts[i][j]; j++) {
      rb_ary_push(cur_block_hosts, rb_str_new2(hosts[i][j]));
    }
    rb_ary_push(hosts_array, cur_block_hosts);
  }
  return hosts_array;
}
示例#11
0
/**
 * call-seq:
 *    hdfs.mv(from_path, to_path, to_fs=nil) -> retval
 *
 * Moves the file at HDFS location from_path to HDFS location to_path.  If
 * to_fs is specified, moves to this HDFS over the current HDFS.  If
 * successful, returns true; otherwise, returns false.
 */
VALUE HDFS_File_System_mv(int argc, VALUE* argv, VALUE self) {
  FSData* data = get_FSData(self);
  VALUE from_path, to_path, to_fs;
  rb_scan_args(argc, argv, "21", &from_path, &to_path, &to_fs);
  hdfsFS destFS = data->fs;
  // If no to_fs is supplied, moves to the current file system.
  if (!NIL_P(to_fs)) {
    if (CLASS_OF(to_fs) == c_file_system) {
      FSData* destFSData = NULL;
      Data_Get_Struct(to_fs, FSData, destFSData);
      destFS = destFSData->fs;
    } else {
      rb_raise(rb_eArgError, "to_fs must be of type Hadoop::DFS::FileSystem");
      return Qnil;
    }
  }
  if (hdfsMove(data->fs, StringValuePtr(from_path), destFS,
          StringValuePtr(to_path)) == -1) {
    rb_raise(e_dfs_exception, "Error while moving path %s to path %s: %s",
        StringValuePtr(from_path), StringValuePtr(to_path), get_error(errno));
    return Qnil;
  }
  return Qtrue;
}
示例#12
0
IOReturn TemperatureSensor::OnKeyRead(const char* key, char* data) {
	if(!set_card(key[2]-'0')){
		char buf[80];
		printf("Error: %s\n", get_error(buf, 80));
		return kIOReturnSuccess;
	}
	switch(key[3]){
		case 'D':
			if(nv_card->caps & (GPU_TEMP_MONITORING)){
				data[0]=nv_card->get_gpu_temp(nv_card->sensor);
				data[1]=0;
				return kIOReturnSuccess;
			}
			break;
		case 'H':
			if(nv_card->caps & (BOARD_TEMP_MONITORING)) {
				data[0]=nv_card->get_board_temp(nv_card->sensor);
				data[1]=0;
				return kIOReturnSuccess;
			}
	}
	printf("Error: temperature monitoring isn't supported on your videocard.\n");
	return kIOReturnSuccess;
}
示例#13
0
文件: error.c 项目: nhst/trema
/*
 * Reason of the failed type error.
 *
 * @return [Number] the value of attribute error code.
 */
static VALUE
error_code( VALUE self ) {
  struct ofp_error_msg *error = get_error( self );
  return UINT2NUM( ntohs( error->code ) );
}
示例#14
0
文件: error.c 项目: nhst/trema
/*
 * Transaction ids, message sequence numbers matching requests to replies.
 *
 * @return [Number] the value of attribute transaction id.
 */
static VALUE
error_transaction_id( VALUE self ) {
  struct ofp_error_msg *error = get_error( self );
  uint32_t xid = ntohl( error->header.xid );
  return UINT2NUM( xid );
}
示例#15
0
int main(int argc, const char **argv) {
  int i, rv;
  char *user = NULL;
  pkcs11_handle_t *ph;
  struct configuration_st *configuration;
  cert_object_t **certs;
  int cert_count;
  unsigned int slot_num = 0;


  /* first of all check whether debugging should be enabled */
  for (i = 0; i < argc; i++)
    if (strcmp("debug", argv[i]) == 0) {
      set_debug_level(1);
    }

  /* call configure routines */
  configuration = pk_configure(argc - 1, argv + 1);
  if (!configuration ) {
	DBG("Error setting configuration parameters");
	return 1;
  }

  if ((configuration->slot_description != NULL && configuration->slot_num != -1) || (configuration->slot_description == NULL && configuration->slot_num == -1)) {
	ERR("Error setting configuration parameters");
	return 1;
  }

  /* init openssl */
  rv = crypto_init(&configuration->policy);
  if (rv != 0) {
    DBG("Couldn't initialize crypto module ");
    return 1;
  }

  /* load pkcs #11 module */
  DBG("loading pkcs #11 module...");
  rv = load_pkcs11_module(configuration->pkcs11_modulepath, &ph);
  if (rv != 0) {
    DBG1("load_pkcs11_module() failed: %s", get_error());
    return 1;
  }

  /* initialise pkcs #11 module */
  DBG("initialising pkcs #11 module...");
  rv = init_pkcs11_module(ph,configuration->support_threads);
  if (rv != 0) {
    release_pkcs11_module(ph);
    DBG1("init_pkcs11_module() failed: %s", get_error());
    return 1;
  }

  /* open pkcs #11 session */
  if (configuration->slot_description != NULL) {
    rv = find_slot_by_slotlabel(ph,configuration->slot_description, &slot_num);
  } else {
    rv = find_slot_by_number(ph,configuration->slot_num, &slot_num);
  }
  if (rv != 0) {
    release_pkcs11_module(ph);
    DBG("no token available");
    return 1;
  }
  rv = open_pkcs11_session(ph, slot_num);
  if (rv != 0) {
    release_pkcs11_module(ph);
    DBG1("open_pkcs11_session() failed: %s", get_error());
    return 1;
  }

#ifdef HAVE_NSS
  /* not really needed, but... */
  rv = pkcs11_pass_login(ph,configuration->nullok);
  if (rv != 0) {
    DBG1("pkcs11_pass_login() failed: %s", get_error());
    return 2;
  }
#endif

  /* get certificate list */
  certs = get_certificate_list(ph, &cert_count);
  if (certs == NULL) {
    close_pkcs11_session(ph);
    release_pkcs11_module(ph);
    DBG1("get_certificate_list() failed: %s", get_error());
    return 3;
  }

  /* load mapper modules */
  load_mappers(configuration->ctx);

  /* find a valid and matching certificates */
  DBG1("Found '%d' certificate(s)", cert_count);
  for (i = 0; i < cert_count; i++) {
    X509 *x509 = get_X509_certificate(certs[i]);
    if (x509 != NULL) {
      DBG1("verifying the certificate #%d", i + 1);
      /* verify certificate (date, signature, CRL, ...) */
      rv = verify_certificate(x509,&configuration->policy);
      if (rv < 0) {
        close_pkcs11_session(ph);
        release_pkcs11_module(ph);
        unload_mappers();
        DBG1("verify_certificate() failed: %s", get_error());
        return 1;
      } else if (rv != 1) {
        DBG1("verify_certificate() failed: %s", get_error());
        continue;
      }

      DBG("Trying to deduce login from certificate");
      user=find_user(x509);
      if (!user) {
          DBG2("find_user() failed for certificate #%d: %s", i + 1, get_error());
	  continue;	/* with next certificate */
      } else {
          DBG1("Certificate is valid and maps to user %s",user);
	  printf("%s\n",user);
          break;
      }
    }
  }

  unload_mappers(); /* no longer needed */

  /* close pkcs #11 session */
  rv = close_pkcs11_session(ph);
  if (rv != 0) {
    release_pkcs11_module(ph);
    DBG1("close_pkcs11_session() failed: %s", get_error());
    return 1;
  }

  /* release pkcs #11 module */
  DBG("releasing pkcs #11 module...");
  release_pkcs11_module(ph);

  DBG("Process completed");
  return (!user)? 1:0;
}
示例#16
0
PAM_EXTERN int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc, const char **argv)
{
  int i, rv;
  const char *user = NULL;
  char *password;
  unsigned int slot_num = 0;
  int is_a_screen_saver = 0;
  struct configuration_st *configuration;
  int pkcs11_pam_fail = PAM_AUTHINFO_UNAVAIL;

  pkcs11_handle_t *ph;
  cert_object_t *chosen_cert = NULL;
  cert_object_t **cert_list;
  int ncert;
  unsigned char random_value[128];
  unsigned char *signature;
  unsigned long signature_length;
  /* enough space to hold an issuer DN */
  char env_temp[256] = "";
  char **issuer, **serial;
  const char *login_token_name = NULL;

  pam_prompt(pamh, PAM_TEXT_INFO , NULL, _("Smartcard authentication starts"));

  /* first of all check whether debugging should be enabled */
  for (i = 0; i < argc; i++)
    if (strcmp("debug", argv[i]) == 0) {
      set_debug_level(1);
    }

  /* call configure routines */
  configuration = pk_configure(argc,argv);
  if (!configuration ) {
	ERR("Error setting configuration parameters");
	return PAM_AUTHINFO_UNAVAIL;
  }

  /* Either slot_description or slot_num, but not both, needs to be used */
  if ((configuration->slot_description != NULL && configuration->slot_num != -1) || (configuration->slot_description == NULL && configuration->slot_num == -1)) {
	ERR("Error setting configuration parameters");
	return PAM_AUTHINFO_UNAVAIL;
  }

  /* fail if we are using a remote server
   * local login: DISPLAY=:0
   * XDMCP login: DISPLAY=host:0 */
  {
	  char *display = getenv("DISPLAY");

	  if (display)
	  {
		  if (strncmp(display, "localhost:", 10) != 0 && (display[0] != ':')
			  && (display[0] != '\0')) {
			  ERR1("Remote login (from %s) is not (yet) supported", display);
			  pam_syslog(pamh, LOG_ERR,
				  "Remote login (from %s) is not (yet) supported", display);
			  return PAM_AUTHINFO_UNAVAIL;
		  }
	  }
  }

#ifdef ENABLE_NLS
  setlocale(LC_ALL, "");
  bindtextdomain(PACKAGE, "/usr/share/locale");
  textdomain(PACKAGE);
#endif

  /* init openssl */
  rv = crypto_init(&configuration->policy);
  if (rv != 0) {
    ERR("Failed to initialize crypto");
    if (!configuration->quiet)
      pam_syslog(pamh,LOG_ERR, "Failed to initialize crypto");
    return PAM_AUTHINFO_UNAVAIL;
  }


  /*
   * card_only means:
   *  1) always get the userid from the certificate.
   *  2) don't prompt for the user name if the card is present.
   *  3) if the token is present, then we must use the cardAuth mechanism.
   *
   * wait_for_card means:
   *  1) nothing if card_only isn't set
   *  2) if logged in, block in pam conversation until the token used for login
   *     is inserted
   *  3) if not logged in, block until a token that could be used for logging in
   *     is inserted
   * right now, logged in means PKC11_LOGIN_TOKEN_NAME is set,
   * but we could something else later (like set some per-user state in
   * a pam session module keyed off uid)
   */
  if (configuration->card_only) {
	char *service;
	if (configuration->screen_savers) {
	    DBG("Is it a screen saver?");
		pam_get_item(pamh, PAM_SERVICE, &service);
	    for (i=0; configuration->screen_savers[i]; i++) {
		if (strcmp(configuration->screen_savers[i], service) == 0) {
		    is_a_screen_saver = 1;
		    break;
		}
	    }
	}

	pkcs11_pam_fail = PAM_CRED_INSUFFICIENT;

	/* look to see if username is already set */
	pam_get_item(pamh, PAM_USER, &user);
	if (user) {
	    DBG1("explicit username = [%s]", user);
	}
  } else {
	rv = pam_get_item(pamh, PAM_USER, &user);
	if (rv != PAM_SUCCESS || user == NULL || user[0] == '\0') {
	  pam_prompt(pamh, PAM_TEXT_INFO, NULL,
		  _("Please insert your %s or enter your username."),
		  _(configuration->token_type));
	  /* get user name */
	  rv = pam_get_user(pamh, &user, NULL);

	  if (rv != PAM_SUCCESS) {
		pam_syslog(pamh, LOG_ERR,
			"pam_get_user() failed %s", pam_strerror(pamh, rv));
		return PAM_USER_UNKNOWN;
	  }
	}
	DBG1("username = [%s]", user);
  }
  login_token_name = getenv("PKCS11_LOGIN_TOKEN_NAME");

  /* if we are using a screen saver, and we didn't log in using the smart card
   * drop to the next pam module.  */
  if (is_a_screen_saver && !login_token_name) {
    return PAM_IGNORE;
  }

  /* load pkcs #11 module */
  DBG("loading pkcs #11 module...");
  rv = load_pkcs11_module(configuration->pkcs11_modulepath, &ph);
  if (rv != 0) {
    ERR2("load_pkcs11_module() failed loading %s: %s",
		configuration->pkcs11_modulepath, get_error());
    if (!configuration->quiet) {
		pam_syslog(pamh, LOG_ERR, "load_pkcs11_module() failed loading %s: %s",
			configuration->pkcs11_modulepath, get_error());
		pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2302: PKCS#11 module failed loading"));
		sleep(configuration->err_display_time);
	}
    return PAM_AUTHINFO_UNAVAIL;
  }

  /* initialise pkcs #11 module */
  DBG("initialising pkcs #11 module...");
  rv = init_pkcs11_module(ph,configuration->support_threads);
  if (rv != 0) {
    release_pkcs11_module(ph);
    ERR1("init_pkcs11_module() failed: %s", get_error());
    if (!configuration->quiet) {
		pam_syslog(pamh, LOG_ERR, "init_pkcs11_module() failed: %s", get_error());
		pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2304: PKCS#11 module could not be initialized"));
		sleep(configuration->err_display_time);
	}
    return PAM_AUTHINFO_UNAVAIL;
  }

  /* open pkcs #11 session */
  if (configuration->slot_description != NULL) {
    rv = find_slot_by_slotlabel_and_tokenlabel(ph,
      configuration->slot_description, login_token_name, &slot_num);
  } else if (configuration->slot_num != -1) {
    rv = find_slot_by_number_and_label(ph, configuration->slot_num,
                                     login_token_name, &slot_num);
  }

  if (rv != 0) {
    ERR("no suitable token available");
    if (!configuration->quiet) {
		pam_syslog(pamh, LOG_ERR, "no suitable token available");
		pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2306: No suitable token available"));
		sleep(configuration->err_display_time);
	}

    if (!configuration->card_only) {
      release_pkcs11_module(ph);
      return PAM_AUTHINFO_UNAVAIL;
    }

    /* we must have a smart card, either because we've configured it as such,
     * or because we used one to log in */
    if (login_token_name || configuration->wait_for_card) {
      if (login_token_name) {
        pam_prompt(pamh, PAM_TEXT_INFO, NULL,
			_("Please insert your smart card called \"%.32s\"."),
			login_token_name);
      } else {
        pam_prompt(pamh, PAM_TEXT_INFO, NULL,
                 _("Please insert your smart card."));
      }

      if (configuration->slot_description != NULL) {
	rv = wait_for_token_by_slotlabel(ph, configuration->slot_description,
          login_token_name, &slot_num);
      } else if (configuration->slot_num != -1) {
        rv = wait_for_token(ph, configuration->slot_num,
                          login_token_name, &slot_num);
      }

      if (rv != 0) {
        release_pkcs11_module(ph);
        return pkcs11_pam_fail;
      }
    } else if (user) {
		if (!configuration->quiet) {
			pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2308: No smartcard found"));
			sleep(configuration->err_display_time);
		}

      /* we have a user and no smart card, go to the next pam module */
      release_pkcs11_module(ph);
      return PAM_AUTHINFO_UNAVAIL;
    } else {
      /* we haven't prompted for the user yet, get the user and see if
       * the smart card has been inserted in the mean time */
      pam_prompt(pamh, PAM_TEXT_INFO, NULL,
	    _("Please insert your %s or enter your username."),
		_(configuration->token_type));
      rv = pam_get_user(pamh, &user, NULL);

      /* check one last time for the smart card before bouncing to the next
       * module */
      if (configuration->slot_description != NULL) {
	rv = find_slot_by_slotlabel(ph, configuration->slot_description,
	  &slot_num);
      } else if (configuration->slot_num != -1) {
        rv = find_slot_by_number(ph, configuration->slot_num, &slot_num);
      }

      if (rv != 0) {
        /* user gave us a user id and no smart card go to next module */
		if (!configuration->quiet) {
			pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2310: No smartcard found"));
			sleep(configuration->err_display_time);
		}

        release_pkcs11_module(ph);
        return PAM_AUTHINFO_UNAVAIL;
      }
    }
  } else {
      pam_prompt(pamh, PAM_TEXT_INFO, NULL,
		  _("%s found."), _(configuration->token_type));
  }
  rv = open_pkcs11_session(ph, slot_num);
  if (rv != 0) {
    ERR1("open_pkcs11_session() failed: %s", get_error());
    if (!configuration->quiet) {
		pam_syslog(pamh, LOG_ERR, "open_pkcs11_session() failed: %s", get_error());
		pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2312: open PKCS#11 session failed"));
		sleep(configuration->err_display_time);
	}
    release_pkcs11_module(ph);
    return pkcs11_pam_fail;
  }

  rv = get_slot_login_required(ph);
  if (rv == -1) {
    ERR1("get_slot_login_required() failed: %s", get_error());
    if (!configuration->quiet) {
		pam_syslog(pamh, LOG_ERR, "get_slot_login_required() failed: %s", get_error());
		pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2314: Slot login failed"));
		sleep(configuration->err_display_time);
	}
    release_pkcs11_module(ph);
    return pkcs11_pam_fail;
  } else if (rv) {
    /* get password */
	pam_prompt(pamh, PAM_TEXT_INFO, NULL,
		_("Welcome %.32s!"), get_slot_tokenlabel(ph));

	/* no CKF_PROTECTED_AUTHENTICATION_PATH */
	rv = get_slot_protected_authentication_path(ph);
	if ((-1 == rv) || (0 == rv))
	{
		char password_prompt[128];

		snprintf(password_prompt,  sizeof(password_prompt), _("%s PIN: "), _(configuration->token_type));
		if (configuration->use_first_pass) {
			rv = pam_get_pwd(pamh, &password, NULL, PAM_AUTHTOK, 0);
		} else if (configuration->try_first_pass) {
			rv = pam_get_pwd(pamh, &password, password_prompt, PAM_AUTHTOK,
					PAM_AUTHTOK);
		} else {
			rv = pam_get_pwd(pamh, &password, password_prompt, 0, PAM_AUTHTOK);
		}
		if (rv != PAM_SUCCESS) {
			if (!configuration->quiet) {
				pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2316: password could not be read"));
				sleep(configuration->err_display_time);
			}
			release_pkcs11_module(ph);
			pam_syslog(pamh, LOG_ERR,
					"pam_get_pwd() failed: %s", pam_strerror(pamh, rv));
			return pkcs11_pam_fail;
		}
#ifdef DEBUG_SHOW_PASSWORD
		DBG1("password = [%s]", password);
#endif

		/* check password length */
		if (!configuration->nullok && strlen(password) == 0) {
			release_pkcs11_module(ph);
			memset(password, 0, strlen(password));
			free(password);
			pam_syslog(pamh, LOG_ERR,
					"password length is zero but the 'nullok' argument was not defined.");
			if (!configuration->quiet) {
				pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2318: Empty smartcard PIN not allowed."));
				sleep(configuration->err_display_time);
			}
			return PAM_AUTH_ERR;
		}
	}
	else
	{
		pam_prompt(pamh, PAM_TEXT_INFO, NULL,
			_("Enter your %s PIN on the pinpad"), _(configuration->token_type));
		/* use pin pad */
		password = NULL;
	}

    /* call pkcs#11 login to ensure that the user is the real owner of the card
     * we need to do thise before get_certificate_list because some tokens
     * can not read their certificates until the token is authenticated */
    rv = pkcs11_login(ph, password);
    /* erase and free in-memory password data asap */
	if (password)
	{
		memset(password, 0, strlen(password));
		free(password);
	}
    if (rv != 0) {
      ERR1("open_pkcs11_login() failed: %s", get_error());
		if (!configuration->quiet) {
			pam_syslog(pamh, LOG_ERR, "open_pkcs11_login() failed: %s", get_error());
			pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2320: Wrong smartcard PIN"));
			sleep(configuration->err_display_time);
		}
      goto auth_failed_nopw;
    }
  }

  cert_list = get_certificate_list(ph, &ncert);
  if (rv<0) {
    ERR1("get_certificate_list() failed: %s", get_error());
    if (!configuration->quiet) {
		pam_syslog(pamh, LOG_ERR, "get_certificate_list() failed: %s", get_error());
		pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2322: No certificate found"));
		sleep(configuration->err_display_time);
	}
    goto auth_failed_nopw;
  }

  /* load mapper modules */
  load_mappers(configuration->ctx);

  /* find a valid and matching certificates */
  for (i = 0; i < ncert; i++) {
    X509 *x509 = (X509 *)get_X509_certificate(cert_list[i]);
    if (!x509 ) continue; /* sanity check */
    DBG1("verifying the certificate #%d", i + 1);
	if (!configuration->quiet) {
		pam_prompt(pamh, PAM_TEXT_INFO, NULL, _("verifying certificate"));
	}

      /* verify certificate (date, signature, CRL, ...) */
      rv = verify_certificate(x509,&configuration->policy);
      if (rv < 0) {
        ERR1("verify_certificate() failed: %s", get_error());
        if (!configuration->quiet) {
          pam_syslog(pamh, LOG_ERR,
                   "verify_certificate() failed: %s", get_error());
			switch (rv) {
				case -2: // X509_V_ERR_CERT_HAS_EXPIRED:
					pam_prompt(pamh, PAM_ERROR_MSG , NULL,
						_("Error 2324: Certificate has expired"));
					break;
				case -3: // X509_V_ERR_CERT_NOT_YET_VALID:
					pam_prompt(pamh, PAM_ERROR_MSG , NULL,
						_("Error 2326: Certificate not yet valid"));
					break;
				case -4: // X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
					pam_prompt(pamh, PAM_ERROR_MSG , NULL,
						_("Error 2328: Certificate signature invalid"));
					break;
				default:
					pam_prompt(pamh, PAM_ERROR_MSG , NULL,
						_("Error 2330: Certificate invalid"));
					break;
			}
			sleep(configuration->err_display_time);
		}
        continue; /* try next certificate */
      } else if (rv != 1) {
        ERR1("verify_certificate() failed: %s", get_error());
        continue; /* try next certificate */
      }

    /* CA and CRL verified, now check/find user */

    if ( is_spaced_str(user) ) {
      /*
	if provided user is null or empty extract and set user
	name from certificate
      */
	DBG("Empty login: try to deduce from certificate");
	user=find_user(x509);
	if (!user) {
          ERR2("find_user() failed: %s on cert #%d", get_error(),i+1);
          if (!configuration->quiet)
            pam_syslog(pamh, LOG_ERR,
                     "find_user() failed: %s on cert #%d",get_error(),i+1);
	  continue; /* try on next certificate */
	} else {
          DBG1("certificate is valid and matches user %s",user);
	  /* try to set up PAM user entry with evaluated value */
	  rv = pam_set_item(pamh, PAM_USER,(const void *)user);
	  if (rv != PAM_SUCCESS) {
	    ERR1("pam_set_item() failed %s", pam_strerror(pamh, rv));
            if (!configuration->quiet) {
				pam_syslog(pamh, LOG_ERR,
                       "pam_set_item() failed %s", pam_strerror(pamh, rv));
				pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2332: setting PAM userentry failed"));
				sleep(configuration->err_display_time);
			}
	    goto auth_failed_nopw;
	}
          chosen_cert = cert_list[i];
          break; /* end loop, as find user success */
      }
    } else {
      /* User provided:
         check whether the certificate matches the user */
        rv = match_user(x509, user);
        if (rv < 0) { /* match error; abort and return */
          ERR1("match_user() failed: %s", get_error());
			if (!configuration->quiet) {
				pam_syslog(pamh, LOG_ERR, "match_user() failed: %s", get_error());
				pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2334: No matching user"));
				sleep(configuration->err_display_time);
			}
	  goto auth_failed_nopw;
        } else if (rv == 0) { /* match didn't success */
          DBG("certificate is valid but does not match the user");
	  continue; /* try next certificate */
        } else { /* match success */
          DBG("certificate is valid and matches the user");
          chosen_cert = cert_list[i];
          break;
      }
    } /* if is_spaced string */
  } /* for (i=0; i<ncerts; i++) */

  /* now myCert points to our found certificate or null if no user found */
  if (!chosen_cert) {
    ERR("no valid certificate which meets all requirements found");
		if (!configuration->quiet) {
			pam_syslog(pamh, LOG_ERR,
				"no valid certificate which meets all requirements found");
		pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2336: No matching certificate found"));
		sleep(configuration->err_display_time);
	}
    goto auth_failed_nopw;
  }


  /* if signature check is enforced, generate random data, sign and verify */
  if (configuration->policy.signature_policy) {
		pam_prompt(pamh, PAM_TEXT_INFO, NULL, _("Checking signature"));


#ifdef notdef
    rv = get_private_key(ph);
    if (rv != 0) {
      ERR1("get_private_key() failed: %s", get_error());
      if (!configuration->quiet)
        pam_syslog(pamh, LOG_ERR,
                 "get_private_key() failed: %s", get_error());
      goto auth_failed_nopw;
    }
#endif

    /* read random value */
    rv = get_random_value(random_value, sizeof(random_value));
    if (rv != 0) {
      ERR1("get_random_value() failed: %s", get_error());
		if (!configuration->quiet){
			pam_syslog(pamh, LOG_ERR, "get_random_value() failed: %s", get_error());
			pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2338: Getting random value failed"));
			sleep(configuration->err_display_time);
		}
      goto auth_failed_nopw;
    }

    /* sign random value */
    signature = NULL;
    rv = sign_value(ph, chosen_cert, random_value, sizeof(random_value),
		    &signature, &signature_length);
    if (rv != 0) {
      ERR1("sign_value() failed: %s", get_error());
		if (!configuration->quiet) {
			pam_syslog(pamh, LOG_ERR, "sign_value() failed: %s", get_error());
			pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2340: Signing failed"));
			sleep(configuration->err_display_time);
		}
      goto auth_failed_nopw;
    }

    /* verify the signature */
    DBG("verifying signature...");
    rv = verify_signature((X509 *)get_X509_certificate(chosen_cert),
             random_value, sizeof(random_value), signature, signature_length);
    if (signature != NULL) {
      free(signature);
    }
    if (rv != 0) {
      close_pkcs11_session(ph);
      release_pkcs11_module(ph);
      ERR1("verify_signature() failed: %s", get_error());
		if (!configuration->quiet) {
			pam_syslog(pamh, LOG_ERR, "verify_signature() failed: %s", get_error());
			pam_prompt(pamh, PAM_ERROR_MSG , NULL, _("Error 2342: Verifying signature failed"));
			sleep(configuration->err_display_time);
		}
      return PAM_AUTH_ERR;
    }

  } else {
      DBG("Skipping signature check");
  }

  /*
   * fill in the environment variables.
   */
  snprintf(env_temp, sizeof(env_temp) - 1,
	   "PKCS11_LOGIN_TOKEN_NAME=%.*s",
	   (int)((sizeof(env_temp) - 1) - strlen("PKCS11_LOGIN_TOKEN_NAME=")),
	   get_slot_tokenlabel(ph));
  rv = pam_putenv(pamh, env_temp);

  if (rv != PAM_SUCCESS) {
    ERR1("could not put token name in environment: %s",
         pam_strerror(pamh, rv));
    if (!configuration->quiet)
      pam_syslog(pamh, LOG_ERR, "could not put token name in environment: %s",
           pam_strerror(pamh, rv));
  }

  issuer = cert_info((X509 *)get_X509_certificate(chosen_cert), CERT_ISSUER,
                     ALGORITHM_NULL);
  if (issuer) {
    snprintf(env_temp, sizeof(env_temp) - 1,
	   "PKCS11_LOGIN_CERT_ISSUER=%.*s",
	   (int)((sizeof(env_temp) - 1) - strlen("PKCS11_LOGIN_CERT_ISSUER=")),
	   issuer[0]);
    rv = pam_putenv(pamh, env_temp);
  } else {
    ERR("couldn't get certificate issuer.");
    if (!configuration->quiet)
      pam_syslog(pamh, LOG_ERR, "couldn't get certificate issuer.");
  }

  if (rv != PAM_SUCCESS) {
    ERR1("could not put cert issuer in environment: %s",
         pam_strerror(pamh, rv));
    if (!configuration->quiet)
      pam_syslog(pamh, LOG_ERR, "could not put cert issuer in environment: %s",
           pam_strerror(pamh, rv));
  }

  serial = cert_info((X509 *)get_X509_certificate(chosen_cert), CERT_SERIAL,
                     ALGORITHM_NULL);
  if (serial) {
    snprintf(env_temp, sizeof(env_temp) - 1,
	   "PKCS11_LOGIN_CERT_SERIAL=%.*s",
	   (int)((sizeof(env_temp) - 1) - strlen("PKCS11_LOGIN_CERT_SERIAL=")),
	   serial[0]);
    rv = pam_putenv(pamh, env_temp);
  } else {
    ERR("couldn't get certificate serial number.");
    if (!configuration->quiet)
      pam_syslog(pamh, LOG_ERR, "couldn't get certificate serial number.");
  }

  if (rv != PAM_SUCCESS) {
    ERR1("could not put cert serial in environment: %s",
         pam_strerror(pamh, rv));
    if (!configuration->quiet)
      pam_syslog(pamh, LOG_ERR, "could not put cert serial in environment: %s",
           pam_strerror(pamh, rv));
  }

  /* unload mapper modules */
  unload_mappers();

  /* close pkcs #11 session */
  rv = close_pkcs11_session(ph);
  if (rv != 0) {
    release_pkcs11_module(ph);
    ERR1("close_pkcs11_session() failed: %s", get_error());
		if (!configuration->quiet) {
			pam_syslog(pamh, LOG_ERR, "close_pkcs11_module() failed: %s", get_error());
			pam_prompt(pamh, PAM_ERROR_MSG , NULL, ("Error 2344: Closing PKCS#11 session failed"));
			sleep(configuration->err_display_time);
		}
    return pkcs11_pam_fail;
  }

  /* release pkcs #11 module */
  DBG("releasing pkcs #11 module...");
  release_pkcs11_module(ph);

  DBG("authentication succeeded");
  return PAM_SUCCESS;

    /* quick and dirty fail exit point */
    memset(password, 0, strlen(password));
    free(password); /* erase and free in-memory password data */

auth_failed_nopw:
    unload_mappers();
    close_pkcs11_session(ph);
    release_pkcs11_module(ph);
    return pkcs11_pam_fail;
}
示例#17
0
文件: syscall.c 项目: masatake/strace
static long
ptrace_getregset(pid_t pid)
{
# ifdef ARCH_IOVEC_FOR_GETREGSET
	/* variable iovec */
	ARCH_IOVEC_FOR_GETREGSET.iov_len = sizeof(ARCH_REGS_FOR_GETREGSET);
	return ptrace(PTRACE_GETREGSET, pid, NT_PRSTATUS,
		      &ARCH_IOVEC_FOR_GETREGSET);
# else
	/* constant iovec */
	static struct iovec io = {
		.iov_base = &ARCH_REGS_FOR_GETREGSET,
		.iov_len = sizeof(ARCH_REGS_FOR_GETREGSET)
	};
	return ptrace(PTRACE_GETREGSET, pid, NT_PRSTATUS, &io);

# endif
}

# ifndef HAVE_GETREGS_OLD
#  define ptrace_setregset_or_setregs ptrace_setregset
static int
ptrace_setregset(pid_t pid)
{
#  ifdef ARCH_IOVEC_FOR_GETREGSET
	/* variable iovec */
	return ptrace(PTRACE_SETREGSET, pid, NT_PRSTATUS,
		      &ARCH_IOVEC_FOR_GETREGSET);
#  else
	/* constant iovec */
	static struct iovec io = {
		.iov_base = &ARCH_REGS_FOR_GETREGSET,
		.iov_len = sizeof(ARCH_REGS_FOR_GETREGSET)
	};
	return ptrace(PTRACE_SETREGSET, pid, NT_PRSTATUS, &io);
#  endif
}
# endif /* !HAVE_GETREGS_OLD */

#elif defined ARCH_REGS_FOR_GETREGS

# define ptrace_getregset_or_getregs ptrace_getregs
static long
ptrace_getregs(pid_t pid)
{
# if defined SPARC || defined SPARC64
	/* SPARC systems have the meaning of data and addr reversed */
	return ptrace(PTRACE_GETREGS, pid, (void *) &ARCH_REGS_FOR_GETREGS, 0);
# else
	return ptrace(PTRACE_GETREGS, pid, NULL, &ARCH_REGS_FOR_GETREGS);
# endif
}

# ifndef HAVE_GETREGS_OLD
#  define ptrace_setregset_or_setregs ptrace_setregs
static int
ptrace_setregs(pid_t pid)
{
#  if defined SPARC || defined SPARC64
	/* SPARC systems have the meaning of data and addr reversed */
	return ptrace(PTRACE_SETREGS, pid, (void *) &ARCH_REGS_FOR_GETREGS, 0);
#  else
	return ptrace(PTRACE_SETREGS, pid, NULL, &ARCH_REGS_FOR_GETREGS);
#  endif
}
# endif /* !HAVE_GETREGS_OLD */

#endif /* ARCH_REGS_FOR_GETREGSET || ARCH_REGS_FOR_GETREGS */

static void
get_regs(pid_t pid)
{
#undef USE_GET_SYSCALL_RESULT_REGS
#ifdef ptrace_getregset_or_getregs

	if (get_regs_error != -1)
		return;

# ifdef HAVE_GETREGS_OLD
	/*
	 * Try PTRACE_GETREGSET/PTRACE_GETREGS first,
	 * fallback to getregs_old.
	 */
	static int use_getregs_old;
	if (use_getregs_old < 0) {
		get_regs_error = ptrace_getregset_or_getregs(pid);
		return;
	} else if (use_getregs_old == 0) {
		get_regs_error = ptrace_getregset_or_getregs(pid);
		if (get_regs_error >= 0) {
			use_getregs_old = -1;
			return;
		}
		if (errno == EPERM || errno == ESRCH)
			return;
		use_getregs_old = 1;
	}
	get_regs_error = getregs_old(pid);
# else /* !HAVE_GETREGS_OLD */
	/* Assume that PTRACE_GETREGSET/PTRACE_GETREGS works. */
	get_regs_error = ptrace_getregset_or_getregs(pid);
# endif /* !HAVE_GETREGS_OLD */

#else /* !ptrace_getregset_or_getregs */

# define USE_GET_SYSCALL_RESULT_REGS 1
# warning get_regs is not implemented for this architecture yet
	get_regs_error = 0;

#endif /* !ptrace_getregset_or_getregs */
}

#ifdef ptrace_setregset_or_setregs
static int
set_regs(pid_t pid)
{
	return ptrace_setregset_or_setregs(pid);
}
#endif /* ptrace_setregset_or_setregs */

struct sysent_buf {
	struct tcb *tcp;
	struct_sysent ent;
	char buf[sizeof("syscall_%lu") + sizeof(kernel_ulong_t) * 3];
};

static void
free_sysent_buf(void *ptr)
{
	struct sysent_buf *s = ptr;
	s->tcp->s_prev_ent = s->tcp->s_ent = NULL;
	free(ptr);
}

/*
 * Returns:
 * 0: "ignore this ptrace stop", syscall_entering_decode() should return a "bail
 *    out silently" code.
 * 1: ok, continue in syscall_entering_decode().
 * other: error, syscall_entering_decode() should print error indicator
 *    ("????" etc) and return an appropriate code.
 */
int
get_scno(struct tcb *tcp)
{
	get_regs(tcp->pid);

	if (get_regs_error)
		return -1;

	int rc = arch_get_scno(tcp);
	if (rc != 1)
		return rc;

	if (scno_is_valid(tcp->scno)) {
		tcp->s_ent = &sysent[tcp->scno];
		tcp->qual_flg = qual_flags(tcp->scno);
	} else {
		struct sysent_buf *s = xcalloc(1, sizeof(*s));

		s->tcp = tcp;
		s->ent.nargs = MAX_ARGS;
		s->ent.sen = SEN_printargs;
		s->ent.sys_func = printargs;
		s->ent.sys_name = s->buf;
		sprintf(s->buf, "syscall_%" PRI_klu, shuffle_scno(tcp->scno));

		tcp->s_ent = &s->ent;
		tcp->qual_flg = QUAL_RAW | DEFAULT_QUAL_FLAGS;

		set_tcb_priv_data(tcp, s, free_sysent_buf);

		if (debug_flag)
			error_msg("pid %d invalid syscall %" PRI_kld,
				  tcp->pid, tcp->scno);
	}
	return 1;
}

#ifdef USE_GET_SYSCALL_RESULT_REGS
static int get_syscall_result_regs(struct tcb *);
#endif

/* Returns:
 * 1: ok, continue in syscall_exiting_trace().
 * -1: error, syscall_exiting_trace() should print error indicator
 *    ("????" etc) and bail out.
 */
static int
get_syscall_result(struct tcb *tcp)
{
#ifdef USE_GET_SYSCALL_RESULT_REGS
	if (get_syscall_result_regs(tcp))
		return -1;
#endif
	tcp->u_error = 0;
	get_error(tcp, !(tcp->s_ent->sys_flags & SYSCALL_NEVER_FAILS));

	return 1;
}

#include "get_scno.c"
#include "set_scno.c"
#include "get_syscall_args.c"
#ifdef USE_GET_SYSCALL_RESULT_REGS
# include "get_syscall_result.c"
#endif
#include "get_error.c"
#include "set_error.c"
#ifdef HAVE_GETREGS_OLD
# include "getregs_old.c"
#endif

const char *
syscall_name(kernel_ulong_t scno)
{
#if defined X32_PERSONALITY_NUMBER && defined __X32_SYSCALL_BIT
	if (current_personality == X32_PERSONALITY_NUMBER)
		scno &= ~__X32_SYSCALL_BIT;
#endif
	return scno_is_valid(scno) ? sysent[scno].sys_name : NULL;
}
示例#18
0
static PyObject *
LDAPEntry_rename(LDAPEntry *self, PyObject *args, PyObject *kwds) {
	int rc;
	char *newparent_str, *newrdn_str, *olddn_str;
	PyObject *newdn, *newparent, *newrdn;
	PyObject *tmp;
	char *kwlist[] = {"newdn", NULL};

	/* Client must be set. */
	if (self->client == NULL) {
		PyErr_SetString(PyExc_AttributeError, "LDAPClient is not set.");
		return NULL;
	}
	/* Client must be connected. */
	if (!self->client->connected) {
		PyObject *ldaperror = get_error("NotConnected");
		PyErr_SetString(ldaperror, "Client has to connect to the server first.");
		Py_DECREF(ldaperror);
		return NULL;
	}

	if (!PyArg_ParseTupleAndKeywords(args, kwds, "O", kwlist, &newdn)) {
		PyErr_SetString(PyExc_AttributeError, "Wrong parameter.");
		return NULL;
	}

	/* Save old dn string. */
	tmp = PyObject_Str(self->dn);
	olddn_str = PyObject2char(tmp);
	Py_DECREF(tmp);
	if (olddn_str == NULL) return NULL;

	/* Validate and set new LDAP DN. */
	if (LDAPEntry_setDN(self, newdn, NULL) != 0) return NULL;

	/* Get rdn and parent strings. */
	newrdn = PyObject_CallMethod(self->dn, "get_rdn", "(i)", 0);
	newparent = PyObject_CallMethod(self->dn, "get_ancestors", NULL);
	if (newrdn == NULL || newparent == NULL) return NULL;

	newrdn_str = PyObject2char(newrdn);
	newparent_str = PyObject2char(newparent);
	Py_DECREF(newrdn);
	Py_DECREF(newparent);

	rc = ldap_rename_s(self->client->ld, olddn_str, newrdn_str, newparent_str, 1, NULL, NULL);
	if (rc != LDAP_SUCCESS) {
		//TODO Proper errors
		PyObject *ldaperror = get_error("LDAPError");
		PyErr_SetString(ldaperror, ldap_err2string(rc));
		Py_DECREF(ldaperror);
		free(olddn_str);
		free(newrdn_str);
		free(newparent_str);
		return NULL;
	}
	free(olddn_str);
	free(newrdn_str);
	free(newparent_str);
	return Py_None;
}
示例#19
0
static long
get_regset(pid_t pid)
{
# ifdef ARCH_IOVEC_FOR_GETREGSET
	/* variable iovec */
	ARCH_IOVEC_FOR_GETREGSET.iov_len = sizeof(ARCH_REGS_FOR_GETREGSET);
	return ptrace(PTRACE_GETREGSET, pid, NT_PRSTATUS,
		      &ARCH_IOVEC_FOR_GETREGSET);
# else
	/* constant iovec */
	static struct iovec io = {
		.iov_base = &ARCH_REGS_FOR_GETREGSET,
		.iov_len = sizeof(ARCH_REGS_FOR_GETREGSET)
	};
	return ptrace(PTRACE_GETREGSET, pid, NT_PRSTATUS, &io);

# endif
}
#endif /* ARCH_REGS_FOR_GETREGSET */

void
get_regs(pid_t pid)
{
#ifdef ARCH_REGS_FOR_GETREGSET
# ifdef X86_64
	/* Try PTRACE_GETREGSET first, fallback to PTRACE_GETREGS. */
	static int getregset_support;

	if (getregset_support >= 0) {
		get_regs_error = get_regset(pid);
		if (getregset_support > 0)
			return;
		if (get_regs_error >= 0) {
			getregset_support = 1;
			return;
		}
		if (errno == EPERM || errno == ESRCH)
			return;
		getregset_support = -1;
	}
	getregs_old(pid);
# else /* !X86_64 */
	/* Assume that PTRACE_GETREGSET works. */
	get_regs_error = get_regset(pid);
# endif
#elif defined ARCH_REGS_FOR_GETREGS
# if defined SPARC || defined SPARC64
	/* SPARC systems have the meaning of data and addr reversed */
	get_regs_error = ptrace(PTRACE_GETREGS, pid, (char *)&ARCH_REGS_FOR_GETREGS, 0);
# elif defined POWERPC
	static bool old_kernel = 0;
	if (old_kernel)
		goto old;
	get_regs_error = ptrace(PTRACE_GETREGS, pid, NULL, &ARCH_REGS_FOR_GETREGS);
	if (get_regs_error && errno == EIO) {
		old_kernel = 1;
 old:
		get_regs_error = getregs_old(pid);
	}
# else
	/* Assume that PTRACE_GETREGS works. */
	get_regs_error = ptrace(PTRACE_GETREGS, pid, NULL, &ARCH_REGS_FOR_GETREGS);
# endif

#else /* !ARCH_REGS_FOR_GETREGSET && !ARCH_REGS_FOR_GETREGS */
#  warning get_regs is not implemented for this architecture yet
	get_regs_error = 0;
#endif
}

/* Returns:
 * 0: "ignore this ptrace stop", bail out of trace_syscall_entering() silently.
 * 1: ok, continue in trace_syscall_entering().
 * other: error, trace_syscall_entering() should print error indicator
 *    ("????" etc) and bail out.
 */
int
get_scno(struct tcb *tcp)
{
	if (get_regs_error)
		return -1;

	long scno = 0;

#include "get_scno.c"

	tcp->scno = scno;
	if (SCNO_IS_VALID(tcp->scno)) {
		tcp->s_ent = &sysent[scno];
		tcp->qual_flg = qual_flags[scno];
	} else {
		static const struct_sysent unknown = {
			.nargs = MAX_ARGS,
			.sys_flags = 0,
			.sys_func = printargs,
			.sys_name = "system call",
		};
		tcp->s_ent = &unknown;
		tcp->qual_flg = UNDEFINED_SCNO | QUAL_RAW | DEFAULT_QUAL_FLAGS;
		if (debug_flag)
			fprintf(stderr, "pid %d invalid syscall %ld\n",
				tcp->pid, scno);
	}
	return 1;
}

/* Return -1 on error or 1 on success (never 0!) */
static int
get_syscall_args(struct tcb *tcp)
{
#include "get_syscall_args.c"
	return 1;
}

static void
get_error(struct tcb *tcp)
{
	const bool check_errno = !(tcp->s_ent->sys_flags & SYSCALL_NEVER_FAILS);
	tcp->u_error = 0;

#include "get_error.c"
}

/* Returns:
 * 1: ok, continue in trace_syscall_exiting().
 * -1: error, trace_syscall_exiting() should print error indicator
 *    ("????" etc) and bail out.
 */
static int
get_syscall_result(struct tcb *tcp)
{
#if defined ARCH_REGS_FOR_GETREGSET || defined ARCH_REGS_FOR_GETREGS
	/* already done by get_regs */
#else
# include "get_syscall_result.c"
#endif
	get_error(tcp);
	return 1;
}
示例#20
0
int main(int argc, const char **argv) {
  int i, rv;
  pkcs11_handle_t *ph;
  struct configuration_st *configuration;
  unsigned int slot_num = 0;
  cert_object_t **certs;
  int cert_count;

  /* first of all check whether debugging should be enabled */
  for (i = 0; i < argc; i++)
    if (strcmp("debug", argv[i]) == 0) {
      set_debug_level(1);
    }

  /* call configure routines */
  configuration = pk_configure(argc - 1, argv + 1);
  if (!configuration ) {
	ERR("Error setting configuration parameters");
	return 1;
  }

  if ((configuration->slot_description != NULL && configuration->slot_num != -1) || (configuration->slot_description == NULL && configuration->slot_num == -1)) {
	ERR("Error setting configuration parameters");
	return 1;
  }

  /* init openssl */
  rv = crypto_init(&configuration->policy);
  if (rv != 0) {
    DBG1("crypto_init() failed: %s", get_error());
    return 1;
  }

  /* load pkcs #11 module */
  DBG("loading pkcs #11 module...");
  rv = load_pkcs11_module(configuration->pkcs11_modulepath, &ph);
  if (rv != 0) {
    ERR2("load_pkcs11_module(%s) failed: %s", configuration->pkcs11_modulepath,
      get_error());
    return 1;
  }

  /* initialise pkcs #11 module */
  DBG("initialising pkcs #11 module...");
  rv = init_pkcs11_module(ph,configuration->support_threads);
  if (rv != 0) {
    release_pkcs11_module(ph);
    DBG1("init_pkcs11_module() failed: %s", get_error());
    return 1;
  }

  /* open pkcs #11 session */
  if (configuration->slot_description != NULL) {
    rv = find_slot_by_slotlabel(ph, configuration->slot_description, &slot_num);
  } else {
    rv = find_slot_by_number(ph, configuration->slot_num, &slot_num);
  }

  if (rv != 0) {
    release_pkcs11_module(ph);
    DBG("no token available");
    return 1;
  }

  rv = open_pkcs11_session(ph, slot_num);
  if (rv != 0) {
    release_pkcs11_module(ph);
    ERR1("open_pkcs11_session() failed: %s", get_error());
    return 1;
  }

  /* not really needed, but.... */
  rv = pkcs11_pass_login(ph,configuration->nullok);
  if (rv != 0) {
    ERR1("pkcs11_pass_login() failed: %s", get_error());
    return 2;
  }

  /* get certificate list (cert space is owned by ph) */
  certs = get_certificate_list(ph, &cert_count);
  if (certs == NULL) {
    close_pkcs11_session(ph);
    release_pkcs11_module(ph);
    ERR1("get_certificates() failed: %s", get_error());
    return 3;
  }

  /* load mapper modules */
  load_mappers(configuration->ctx);

  /* find valid certificates and look for contents */
  DBG1("Found '%d' certificate(s)", cert_count);
  for (i = 0; i < cert_count; i++) {
    X509 *x509 = get_X509_certificate(certs[i]);
    if (x509 != NULL) {
      DBG1("verifying the certificate #%d", i + 1);
      /* verify certificate (date, signature, CRL, ...) */
      rv = verify_certificate(x509, &configuration->policy);
      if (rv < 0) {
        close_pkcs11_session(ph);
        release_pkcs11_module(ph);
	unload_mappers();
        ERR1("verify_certificate() failed: %s", get_error());
        return 1;
      } else if (rv != 1) {
        ERR1("verify_certificate() failed: %s", get_error());
        continue;
      }

      DBG1("Inspecting certificate #%d",i+1);
      inspect_certificate(x509);
    }
  }

  /* unload mappers */
  unload_mappers();

  /* close pkcs #11 session */
  rv = close_pkcs11_session(ph);
  if (rv != 0) {
    release_pkcs11_module(ph);
    ERR1("close_pkcs11_session() failed: %s", get_error());
    return 1;
  }

  /* release pkcs #11 module */
  DBG("releasing pkcs #11 module...");
  release_pkcs11_module(ph);

  DBG("Process completed");
  return 0;
}
示例#21
0
void DL_pts::init(DL_geo* _g, DL_point* _p, DL_surface* _surf) {
  DL_point ptmp;
  DL_vector vtmp;
  
  if (_g==_surf->get_geo()) {
    DL_dsystem->get_companion()->Msg("Error: pts::init: the surface and the point should lie in different objects!\n pts constraint not initialised\n");
    return;
  }
    
  if (_g) g_is_dyna=_g->is_dyna();
  else g_is_dyna=FALSE;
  if (_surf->get_geo()) sg_is_dyna=_surf->get_geo()->is_dyna();
  else sg_is_dyna=FALSE;
  if (!(g_is_dyna || sg_is_dyna)) {
    DL_dsystem->get_companion()->Msg("Error: pts::init: either the point or the surface should belong to a dyna\n pts-constraint not initialised\n");
    return;
  }

  // get the initial surface-parameters
  if (_g) _g->to_world(_p,&ptmp);
  else ptmp.assign(_p);
  if (!_surf->closeto(&ptmp,s,t)) {
    DL_dsystem->get_companion()->Msg("Error: pts::init: initial surface position (%f,%f) is out of bounds\n pts-constraint not initialised\n",s,t);
    return;
  }
  olds=s; oldt=t;

  // set up the local coordinate system:
  
  st_inbounds=_surf->pos(s,t,&sstl);

  if (sg_is_dyna) {
    sf=s; tf=t;
    sstf.assign(&sstl);
  }

  if (_surf->get_geo()) {
    _surf->deriv0(s,t,&vtmp);
    (_surf->get_geo())->to_world(&vtmp,&x);
  }
  else _surf->deriv0(s,t,&x);
  xxinv=1.0/x.inprod(&x);
  
  if (_surf->get_geo()) {
    _surf->deriv1(s,t,&vtmp);
    (_surf->get_geo())->to_world(&vtmp,&y);
  }
  else _surf->deriv1(s,t,&y);
  yyinv=1.0/y.inprod(&y);
  
  // make sure y is perpendicular to x:
  {
    DL_vector vtmp;
    x.times(-x.inprod(&y)*xxinv,&vtmp);
    y.plusis(&vtmp);
  }
  x.crossprod(&y,&n);
  n.normalize();

  dcdp.setrow(0,&n);
  dfdR.setcolumn(0,&n);

  surf=_surf;
  g=_g;
  p.assign(_p);

  if (!g_is_dyna) {
    if (g) {
      g->new_toworld(&p,&pgw);
      g->get_newvelocity(&p,&dpgw);
    }
    else {
      pgw.assign(&p);
      dpgw.init(0,0,0);
    }
  }
 
  // check if the constraint is initially valid
  DL_largevector lv(1);
  get_error(&lv);
  
  if (!st_inbounds) {
    DL_dsystem->get_companion()->Msg("Error: pts::init: initial surface parameters (%f,%f) out of bounds\n pts-constraint not initialised\n",s,t);
    return;
  }
  
  if (lv.get(0)>DL_constraints->max_error) {
    DL_dsystem->get_companion()->Msg("Warning: initially invalid pts-constraint\n  Error: %f\n Initial surface parameters: (%f,%f)\n", lv.get(0), s, t);
  }

  // ok: we're in business:
  
  DL_constraint::init();
  F->makezero(); oldF->makezero();
}
示例#22
0
int
posix_spawn(
	pid_t *pidp,
	const char *path,
	const posix_spawn_file_actions_t *file_actions,
	const posix_spawnattr_t *attrp,
	char *const argv[],
	char *const envp[])
{
	spawn_attr_t *sap = attrp? attrp->__spawn_attrp : NULL;
	file_attr_t *fap = file_actions? file_actions->__file_attrp : NULL;
	void *dirbuf = NULL;
	int error;		/* this will be set by the child */
	pid_t pid;

	if (attrp != NULL && sap == NULL)
		return (EINVAL);

	if (fap != NULL && fap->fa_need_dirbuf) {
		/*
		 * Preallocate the buffer for the call to getdents64() in
		 * spawn_closefrom() since we can't do it in the vfork() child.
		 */
		if ((dirbuf = lmalloc(DIRBUF)) == NULL)
			return (ENOMEM);
	}

	switch (pid = vforkx(forkflags(sap))) {
	case 0:			/* child */
		break;
	case -1:		/* parent, failure */
		if (dirbuf)
			lfree(dirbuf, DIRBUF);
		return (errno);
	default:		/* parent, success */
		/*
		 * We don't get here until the child exec()s or exit()s
		 */
		if (pidp != NULL && get_error(&error) == 0)
			*pidp = pid;
		if (dirbuf)
			lfree(dirbuf, DIRBUF);
		return (get_error(&error));
	}

	if (sap != NULL)
		if (set_error(&error, perform_flag_actions(sap)) != 0)
			_exit(_EVAPORATE);

	if (fap != NULL)
		if (set_error(&error, perform_file_actions(fap, dirbuf)) != 0)
			_exit(_EVAPORATE);

	(void) set_error(&error, 0);
	(void) execve(path, argv, envp);
	if (sap != NULL && (sap->sa_psflags & POSIX_SPAWN_NOEXECERR_NP))
		_exit(127);
	(void) set_error(&error, errno);
	_exit(_EVAPORATE);
	return (0);	/* not reached */
}
示例#23
0
int main(int argc, char *argv[])
{
	int result = 0;
	ref_t val, answer, assoc, name;
	FILE *input_fl = stdin, *output_fl = stdout;
	clock_t start_time, end_time;
	
#define FREE_AND_RETURN(x) {result = x; goto free_and_return;}

	if (parse_command_line(argc, argv, cmd_opt_decls) == -1)
	{
		printf("%s\n\n", get_error());
		print_usage();
		FREE_AND_RETURN(1);
	}

	if (help_flag)
	{
		print_usage();
		FREE_AND_RETURN(0);
	}

	if (input_fname)
	{
		input_fl = fopen(input_fname, "r");
		if (input_fl == 0)
		{
			printf("Could not open input file %s\n", input_fname);
			FREE_AND_RETURN(1);
		}
	}

	if (output_fname)
	{
		output_fl = fopen(output_fname, "w");
		if (output_fl == 0)
		{
			printf("Could not open output file %s\n", output_fname);
			FREE_AND_RETURN(1);
		}
	}

	if (trace_file_fname)
	{
		trace_fl = fopen(trace_file_fname, "w");
		if (trace_fl == 0)
		{
			printf("Could not open trace file %s\n", trace_file_fname);
			FREE_AND_RETURN(1);
		}
	}

	assoc = make_stack(nil());
	register_gc_root(assoc);
	stack_enter(assoc);

	name = make_symbol("t", 0);
	stack_let(assoc, name, name);
	release_ref(&name);
	
	register_core_lib(assoc);

	REG_FN(exit, assoc);
	REG_FN(trace, assoc);
	REG_FN(profile, assoc);
	REG_NAMED_FN("no-trace", slfe_no_trace, assoc);
	REG_NAMED_FN("dump-stack", slfe_dump_stack, assoc);

	if (trace_fl)
		set_trace_file(trace_fl);

	start_time = clock();

	finished = 0;
	while (! finished)
	{
		if (input_fl == stdin)
			printf("> ");

		val = read(input_fl);
		answer = eval(val, assoc);
		release_ref(&val);
		if (!quiet_flag)
		{
			println(answer, output_fl);
			fflush(output_fl);
		}
		release_ref(&answer);
		collect_garbage();
	}

	stack_enter(nil());
	unregister_gc_root(assoc);
	release_ref(&assoc);

	collect_garbage();

	end_time = clock();

	if (trace_fl)
		fprintf(trace_fl, "Total time taken: %f seconds\n", (float)(end_time - start_time) / (float)CLOCKS_PER_SEC);

#undef FREE_AND_RETURN

free_and_return:
	if (trace_fl && stats_flag)
		fprintf(trace_fl, "Total symbol evals: %d; total stack switches: %d\n", symbol_eval_count, stack_switch_count);

	if (input_fl != stdin) fclose(input_fl);
	if (output_fl != stdout) fclose(output_fl);
	if (trace_fl) fclose(trace_fl);

	if (input_fname) X_FREE(input_fname);
	if (output_fname) X_FREE(output_fname);
	if (trace_file_fname) X_FREE(trace_file_fname);

	return result;
}
示例#24
0
文件: mapping.c 项目: ccpgames/wine
static struct object *create_mapping( struct object *root, const struct unicode_str *name,
                                      unsigned int attr, mem_size_t size, unsigned int flags,
                                      obj_handle_t handle, unsigned int file_access,
                                      const struct security_descriptor *sd )
{
    struct mapping *mapping;
    struct file *file;
    struct fd *fd;
    int unix_fd;
    struct stat st;

    if (!page_mask) page_mask = sysconf( _SC_PAGESIZE ) - 1;

    if (!(mapping = create_named_object( root, &mapping_ops, name, attr, sd )))
        return NULL;
    if (get_error() == STATUS_OBJECT_NAME_EXISTS)
        return &mapping->obj;  /* Nothing else to do */

    mapping->size        = size;
    mapping->fd          = NULL;
    mapping->shared      = NULL;
    mapping->committed   = NULL;

    if (!(mapping->flags = get_mapping_flags( handle, flags ))) goto error;

    if (handle)
    {
        const unsigned int sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
        unsigned int mapping_access = FILE_MAPPING_ACCESS;

        if (!(file = get_file_obj( current->process, handle, file_access ))) goto error;
        fd = get_obj_fd( (struct object *)file );

        /* file sharing rules for mappings are different so we use magic the access rights */
        if (flags & SEC_IMAGE) mapping_access |= FILE_MAPPING_IMAGE;
        else if (file_access & FILE_WRITE_DATA) mapping_access |= FILE_MAPPING_WRITE;

        if (!(mapping->fd = get_fd_object_for_mapping( fd, mapping_access, sharing )))
        {
            mapping->fd = dup_fd_object( fd, mapping_access, sharing, FILE_SYNCHRONOUS_IO_NONALERT );
            if (mapping->fd) set_fd_user( mapping->fd, &mapping_fd_ops, NULL );
        }
        release_object( file );
        release_object( fd );
        if (!mapping->fd) goto error;

        if ((unix_fd = get_unix_fd( mapping->fd )) == -1) goto error;
        if (fstat( unix_fd, &st ) == -1)
        {
            file_set_error();
            goto error;
        }
        if (flags & SEC_IMAGE)
        {
            unsigned int err = get_image_params( mapping, st.st_size, unix_fd );
            if (!err) return &mapping->obj;
            set_error( err );
            goto error;
        }
        if (!mapping->size)
        {
            if (!(mapping->size = st.st_size))
            {
                set_error( STATUS_MAPPED_FILE_SIZE_ZERO );
                goto error;
            }
        }
        else if (st.st_size < mapping->size)
        {
            if (!(file_access & FILE_WRITE_DATA))
            {
                set_error( STATUS_SECTION_TOO_BIG );
                goto error;
            }
            if (!grow_file( unix_fd, mapping->size )) goto error;
        }
    }
    else  /* Anonymous mapping (no associated file) */
    {
        if (!mapping->size)
        {
            set_error( STATUS_INVALID_PARAMETER );
            goto error;
        }
        if ((flags & SEC_RESERVE) && !(mapping->committed = create_ranges())) goto error;
        mapping->size = (mapping->size + page_mask) & ~((mem_size_t)page_mask);
        if ((unix_fd = create_temp_file( mapping->size )) == -1) goto error;
        if (!(mapping->fd = create_anonymous_fd( &mapping_fd_ops, unix_fd, &mapping->obj,
                                                 FILE_SYNCHRONOUS_IO_NONALERT ))) goto error;
        allow_fd_caching( mapping->fd );
    }
    return &mapping->obj;

 error:
    release_object( mapping );
    return NULL;
}
示例#25
0
文件: synexp.c 项目: Pitel/IFJ2007
/**
 * Expression analyser
 *
 * @param stream Stream for loading next token
 * @param token Current token
 * @param symtab Symbol table (AVL root)
 * @param cons_counter number for original naming of item in symbol table
 */
Tnode_ptr syntax_synexp(FILE *stream, Tlex_token *token,
			Tnode_ptr *symtab, size_t *cons_counter,
			Tthree_adr **ta)
{
    assert(stream != NULL);
    assert(token != NULL);
    assert(symtab != NULL);
    assert(cons_counter != NULL);

    size_t precedence_table[][SYN_TABLE_SIZE] = {
//	   1 ,  2 ,  3 ,  4 ,  5 ,  6 ,  7 ,  8 ,  9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17 , 18 , 19 , 20 , 21 , 22 , 23 , 24 , 25 , 26
/*1*/	{ P_E, P_E, P_E, P_E, P_M, P_M, P_M, P_M, P_M, P_E, P_M, P_E, P_E, P_M, P_M, P_M, P_M, P_M, P_M, P_E, P_M, P_E, P_E, P_E, P_E, P_E } ,
/*2*/	{ P_E, P_E, P_E, P_E, P_M, P_M, P_M, P_M, P_M, P_E, P_M, P_E, P_E, P_M, P_M, P_M, P_M, P_M, P_M, P_E, P_M, P_E, P_E, P_E, P_E, P_E } ,
/*3*/	{ P_E, P_E, P_E, P_E, P_M, P_M, P_M, P_M, P_M, P_E, P_M, P_E, P_E, P_M, P_M, P_M, P_M, P_M, P_M, P_E, P_M, P_E, P_E, P_E, P_E, P_E } ,
/*4*/	{ P_E, P_E, P_E, P_E, P_M, P_M, P_M, P_M, P_M, P_E, P_M, P_E, P_E, P_M, P_M, P_M, P_M, P_M, P_M, P_E, P_M, P_E, P_E, P_E, P_E, P_E } ,
/*5*/	{ P_L, P_L, P_L, P_L, P_M, P_M, P_L, P_L, P_L, P_E, P_M, P_E, P_E, P_M, P_M, P_M, P_M, P_M, P_M, P_L, P_M, P_E, P_E, P_E, P_E, P_E } ,
/*6*/	{ P_L, P_L, P_L, P_L, P_M, P_M, P_L, P_L, P_L, P_E, P_M, P_E, P_E, P_M, P_M, P_M, P_M, P_M, P_M, P_L, P_M, P_E, P_E, P_E, P_E, P_E } ,
/*7*/	{ P_L, P_L, P_L, P_L, P_M, P_M, P_M, P_M, P_L, P_E, P_M, P_E, P_E, P_M, P_M, P_M, P_M, P_M, P_M, P_L, P_M, P_E, P_E, P_E, P_E, P_E } ,
/*8*/	{ P_L, P_L, P_L, P_L, P_M, P_M, P_M, P_M, P_L, P_E, P_M, P_E, P_E, P_M, P_M, P_M, P_M, P_M, P_M, P_L, P_M, P_E, P_E, P_E, P_E, P_E } ,
/*9*/	{ P_L, P_L, P_L, P_L, P_M, P_M, P_M, P_M, P_L, P_E, P_M, P_E, P_E, P_M, P_M, P_M, P_M, P_M, P_M, P_L, P_M, P_E, P_E, P_E, P_E, P_E } ,
/*10*/	{ P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E } ,
/*11*/	{ P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_E, P_Q, P_E, P_E, P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_E, P_E, P_E, P_E, P_E, P_E } ,
/*12*/	{ P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E } ,
/*13*/	{ P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E } ,
/*14*/	{ P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_E, P_M, P_E, P_E, P_M, P_M, P_L, P_L, P_L, P_L, P_L, P_M, P_E, P_E, P_E, P_E, P_E } ,
/*15*/	{ P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_E, P_M, P_E, P_E, P_M, P_M, P_L, P_L, P_L, P_L, P_L, P_M, P_E, P_E, P_E, P_E, P_E } ,
/*16*/	{ P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_E, P_M, P_E, P_E, P_M, P_M, P_M, P_M, P_M, P_M, P_L, P_M, P_E, P_E, P_E, P_E, P_E } ,
/*17*/	{ P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_E, P_M, P_E, P_E, P_M, P_M, P_M, P_M, P_M, P_M, P_L, P_M, P_E, P_E, P_E, P_E, P_E } ,
/*18*/	{ P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_E, P_M, P_E, P_E, P_M, P_M, P_M, P_M, P_M, P_M, P_L, P_M, P_E, P_E, P_E, P_E, P_E } ,
/*19*/	{ P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_E, P_M, P_E, P_E, P_M, P_M, P_M, P_M, P_M, P_M, P_L, P_M, P_E, P_E, P_E, P_E, P_E } ,
/*20*/	{ P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_E, P_E, P_E, P_E, P_L, P_L, P_L, P_L, P_L, P_L, P_L, P_EQ,P_E, P_E, P_E, P_E, P_E } ,
/*21*/	{ P_E, P_E, P_E, P_E, P_M, P_M, P_M, P_M, P_M, P_E, P_M, P_E, P_E, P_M, P_M, P_M, P_M, P_M, P_M, P_E, P_M, P_E, P_E, P_E, P_E, P_E } ,
/*22*/	{ P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E } ,
/*23*/	{ P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E } ,
/*24*/	{ P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E } ,
/*25*/	{ P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E } ,
/*26*/	{ P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E, P_E } ,
    };

    Tstack stack;
    stack_init(&stack);
    Tstack_syntax *stack_data = NULL;
    char *cons_name_tmp;
    Tnode_ptr operand1 = NULL;
    Tnode_ptr operand2 = NULL;
    Tdata_union value_tmp;
    Tnode_ptr SearchSymbol = NULL;
    Tnode_ptr Result = NULL;
    size_t type_tmp = 0;
    size_t type_tmp2 = 0;

    stack_data = malloc(sizeof(*stack_data));
    if (stack_data == NULL) {
	error(ERROR_NO_MEMORY);
	return NULL;
    }
    str_init(&stack_data->stoken.lexeme);
    str_strcatCh(&stack_data->stoken.lexeme, '$');
    stack_data->stoken.token_type = TOKEN_DOLAR;
    stack_data->symtab_ptr = NULL;
    stack_push(&stack, (void *) &stack_data);
    do {
	if (stack_data->stoken.token_type == TOKEN_SYNEXP_E) {	// jump over TOKEN_SYNTAX_E
	    stack_lookatnext(&stack, (void *) &stack_data);
	}
	switch (precedence_table
		[(size_t) stack_data->stoken.token_type -
		 1][(size_t) token->token_type - 1]) {
	    case P_EQ:
		stack_data = malloc(sizeof(*stack_data));
		if (stack_data == NULL) {	// TODO: Cleanup stack, test it
		    error(ERROR_NO_MEMORY);
		    syn_free_stack(&stack, stack_data);
		    return NULL;
		}
		stack_data->stoken.lexeme = token->lexeme;
		stack_data->stoken.token_type = token->token_type;
		stack_push(&stack, (void *) &stack_data);
		lex(stream, token);
		if (get_error()) {
		    syn_free_stack(&stack, stack_data);
		    return NULL;
		}
		break;
	    case P_L:		// Copy and push
		stack_data = malloc(sizeof(*stack_data));
		if (stack_data == NULL) {	// TODO: Cleanup stack, test it
		    error(ERROR_NO_MEMORY);
		    syn_free_stack(&stack, stack_data);
		    return NULL;
		}
		stack_data->stoken.lexeme = token->lexeme;
		stack_data->stoken.token_type = token->token_type;
		stack_push(&stack, (void *) &stack_data);
		lex(stream, token);
		if (get_error()) {
		    syn_free_stack(&stack, stack_data);
		    return NULL;
		}
		break;
	    case P_M:
		stack_top(&stack, (void *) &stack_data);
		SearchSymbol = NULL;
		switch (stack_data->stoken.token_type) {
		    case TOKEN_SYMBOL:
			SearchSymbol = NULL;
			avl_search_node(*symtab,
					stack_data->stoken.lexeme.data,
					&SearchSymbol);
			if (SearchSymbol == NULL) {
			    error(ERROR_SEMANTIC);
			    syn_free_stack(&stack, stack_data);
			    return NULL;
			} else {
			    str_free(&(stack_data)->stoken.lexeme);
			    stack_pop(&stack);
			    stack_data->stoken.token_type = TOKEN_SYNEXP_E;
			    stack_data->symtab_ptr = SearchSymbol;
			    stack_push(&stack, (void *) &stack_data);
			}
			break;
		    case TOKEN_INT:
			cons_name_tmp = syn_next_cons_name(cons_counter);
			Tdata_union integer;
			integer.i =
			    (int) strtol(stack_data->stoken.lexeme.data,
					 NULL, 10);
			avl_insert(symtab, cons_name_tmp, SYMBOL_INT,
				   &integer);
			avl_search_node(*symtab, cons_name_tmp,
					&SearchSymbol);
			str_free(&(stack_data)->stoken.lexeme);
			stack_pop(&stack);
			stack_data->stoken.token_type = TOKEN_SYNEXP_E;
			stack_data->symtab_ptr = SearchSymbol;
			stack_push(&stack, (void *) &stack_data);
			break;
		    case TOKEN_DOUBLE:
			cons_name_tmp = syn_next_cons_name(cons_counter);
			Tdata_union Double;
			Double.d =
			    strtod(stack_data->stoken.lexeme.data, NULL);
			avl_insert(symtab, cons_name_tmp, SYMBOL_DOUBLE,
				   &Double);
			avl_search_node(*symtab, cons_name_tmp,
					&SearchSymbol);
			str_free(&(stack_data)->stoken.lexeme);
			stack_pop(&stack);
			stack_data->stoken.token_type = TOKEN_SYNEXP_E;
			stack_data->symtab_ptr = SearchSymbol;
			stack_push(&stack, (void *) &stack_data);
			break;
		    case TOKEN_STRING:
			cons_name_tmp = syn_next_cons_name(cons_counter);
			Tdata_union String;
			str_init(&String.s);
			str_strcatStr(&String.s,
				      &(stack_data->stoken.lexeme));
			avl_insert(symtab, cons_name_tmp, SYMBOL_STRING,
				   &String);
			avl_search_node(*symtab, cons_name_tmp,
					&SearchSymbol);
			str_free(&(stack_data)->stoken.lexeme);
			stack_pop(&stack);
			stack_data->stoken.token_type = TOKEN_SYNEXP_E;
			stack_data->symtab_ptr = SearchSymbol;
			stack_push(&stack, (void *) &stack_data);
			break;
		    case TOKEN_R_BRACKET:
			str_free(&(stack_data)->stoken.lexeme);
			free(stack_data);
			stack_pop(&stack);
			stack_top(&stack, (void *) &stack_data);
			if (stack_data->stoken.token_type ==
			    TOKEN_SYNEXP_E) {
			    operand1 = stack_data->symtab_ptr;
			    free(stack_data);
			    stack_pop(&stack);
			    stack_top(&stack, (void *) &stack_data);
			    if (stack_data->stoken.token_type ==
				TOKEN_L_BRACKET) {
				str_free(&(stack_data)->stoken.lexeme);
				stack_pop(&stack);
				stack_data->stoken.token_type =
				    TOKEN_SYNEXP_E;
				stack_data->symtab_ptr = operand1;
				stack_push(&stack, (void *) &stack_data);
			    } else {	// otestovat
				error(ERROR_SYNTAX);
				syn_free_stack(&stack, stack_data);
				return NULL;
			    }
			} else {	// otestovat
			    error(ERROR_SYNTAX);
			    syn_free_stack(&stack, stack_data);
			    return NULL;
			}
			break;
		    case TOKEN_SYNEXP_E:
			operand2 = stack_data->symtab_ptr;
			free(stack_data);
			stack_pop(&stack);
			stack_top(&stack, (void *) &stack_data);
			switch (stack_data->stoken.token_type) {
			    case TOKEN_DIVIDE:
				str_free(&(stack_data)->stoken.lexeme);
				free(stack_data);
				stack_pop(&stack);
				stack_top(&stack, (void *) &stack_data);
				if (stack_data->stoken.token_type ==
				    TOKEN_SYNEXP_E) {
				    operand1 = stack_data->symtab_ptr;
				    cons_name_tmp =
					syn_next_cons_name(cons_counter);
				    switch (operand1->type) {
					case TOKEN_INT:
					case TOKEN_DOUBLE:
					    if (operand2->type !=
						TOKEN_STRING) {
						value_tmp.d = 0;
						type_tmp = SYMBOL_DOUBLE;
					    } else {
						error(ERROR_SEMANTIC);
						free(cons_name_tmp);
						syn_free_stack(&stack,
							       stack_data);
						return NULL;
					    }
					    break;
					case TOKEN_STRING:
					    error(ERROR_SEMANTIC);
					    free(cons_name_tmp);
					    syn_free_stack(&stack,
							   stack_data);
					    return NULL;
					    break;
					default:
					    break;
				    }
				    stack_pop(&stack);
				    stack_data->stoken.token_type =
					TOKEN_SYNEXP_E;
				    avl_insert(symtab, cons_name_tmp,
					       type_tmp, &value_tmp);
				    avl_search_node(*symtab, cons_name_tmp,
						    &SearchSymbol);
				    stack_data->symtab_ptr = SearchSymbol;
				    if (SearchSymbol == NULL) {
					error(ERROR_SYNTAX);
					syn_free_stack(&stack, stack_data);
					return NULL;
				    }
				    ta_insert_last(TA_DIV, &operand1,
						   &operand2,
						   &SearchSymbol, ta);
				    stack_push(&stack,
					       (void *) &stack_data);
				    if (get_error()) {
					syn_free_stack(&stack, stack_data);
					return NULL;
				    }
				} else {
				    error(ERROR_SYNTAX);
				    syn_free_stack(&stack, stack_data);
				    return NULL;
				}
				break;
			    case TOKEN_EQUAL:
			    case TOKEN_NOT_EQUAL:
			    case TOKEN_LESS:
			    case TOKEN_LESS_EQUAL:
			    case TOKEN_MORE:
			    case TOKEN_MORE_EQUAL:
				type_tmp2 = stack_data->stoken.token_type;
				str_free(&(stack_data)->stoken.lexeme);
				free(stack_data);
				stack_pop(&stack);
				stack_top(&stack, (void *) &stack_data);
				if (stack_data->stoken.token_type ==
				    TOKEN_SYNEXP_E) {
				    operand1 = stack_data->symtab_ptr;
				    cons_name_tmp =
					syn_next_cons_name(cons_counter);
				    switch (operand1->type) {
					case TOKEN_INT:
					    if (operand2->type !=
						SYMBOL_STRING) {
						value_tmp.i = -1;
						type_tmp = SYMBOL_INT;
					    } else {
						error(ERROR_SEMANTIC);
						free(cons_name_tmp);
						syn_free_stack(&stack,
							       stack_data);
						return NULL;
					    }
					    break;
					case TOKEN_DOUBLE:
					    if (operand2->type !=
						SYMBOL_STRING) {
						value_tmp.i = -1;
						type_tmp = SYMBOL_INT;
					    } else {
						error(ERROR_SEMANTIC);
						free(cons_name_tmp);
						syn_free_stack(&stack,
							       stack_data);
						return NULL;
					    }
					    break;
					case TOKEN_STRING:
					    if (operand2->type ==
						SYMBOL_STRING) {
						value_tmp.i = -1;
						type_tmp = SYMBOL_INT;
					    } else {
						error(ERROR_SEMANTIC);
						free(cons_name_tmp);
						syn_free_stack(&stack,
							       stack_data);
						return NULL;
					    }
					    break;
					default:
					    break;
				    }
				    stack_pop(&stack);
				    stack_data->stoken.token_type =
					TOKEN_SYNEXP_E;
				    avl_insert(symtab, cons_name_tmp,
					       type_tmp, &value_tmp);
				    avl_search_node(*symtab, cons_name_tmp,
						    &SearchSymbol);
				    stack_data->symtab_ptr = SearchSymbol;
				    if (SearchSymbol == NULL) {
					error(ERROR_SYNTAX);
					syn_free_stack(&stack, stack_data);
					return NULL;
				    }
				    switch (type_tmp2) {
					case TOKEN_EQUAL:
					    ta_insert_last(TA_EQUAL,
							   &operand1,
							   &operand2,
							   &SearchSymbol,
							   ta);
					    break;
					case TOKEN_NOT_EQUAL:
					    ta_insert_last(TA_NOT_EQUAL,
							   &operand1,
							   &operand2,
							   &SearchSymbol,
							   ta);
					    break;
					case TOKEN_LESS:
					    ta_insert_last(TA_LESS,
							   &operand1,
							   &operand2,
							   &SearchSymbol,
							   ta);
					    break;
					case TOKEN_LESS_EQUAL:
					    ta_insert_last(TA_LESS_EQUAL,
							   &operand1,
							   &operand2,
							   &SearchSymbol,
							   ta);
					    break;
					case TOKEN_MORE:
					    ta_insert_last(TA_MORE,
							   &operand1,
							   &operand2,
							   &SearchSymbol,
							   ta);
					    break;
					case TOKEN_MORE_EQUAL:
					    ta_insert_last(TA_MORE_EQUAL,
							   &operand1,
							   &operand2,
							   &SearchSymbol,
							   ta);
					    break;
				    }
				    stack_push(&stack,
					       (void *) &stack_data);
				} else {
				    error(ERROR_SYNTAX);
				    syn_free_stack(&stack, stack_data);
				    return NULL;
				}
				break;
			    case TOKEN_MINUS:
				str_free(&(stack_data)->stoken.lexeme);
				free(stack_data);
				stack_pop(&stack);
				stack_top(&stack, (void *) &stack_data);
				if (stack_data->stoken.token_type ==
				    TOKEN_SYNEXP_E) {
				    operand1 = stack_data->symtab_ptr;
				    cons_name_tmp =
					syn_next_cons_name(cons_counter);
				    switch (operand1->type) {
					case TOKEN_INT:
					    if (operand2->type ==
						TOKEN_INT) {
						value_tmp.i = 0;
						type_tmp = SYMBOL_INT;
					    } else if (operand2->type ==
						       TOKEN_DOUBLE) {
						value_tmp.d = 0;
						type_tmp = SYMBOL_DOUBLE;
					    } else {
						error(ERROR_SEMANTIC);
						free(cons_name_tmp);
						syn_free_stack(&stack,
							       stack_data);
						return NULL;
					    }
					    break;
					case TOKEN_DOUBLE:
					    if (operand2->type !=
						TOKEN_STRING) {
						value_tmp.d = 0;
						type_tmp = SYMBOL_DOUBLE;
					    } else {
						error(ERROR_SEMANTIC);
						free(cons_name_tmp);
						syn_free_stack(&stack,
							       stack_data);
						return NULL;
					    }
					    break;
					case TOKEN_STRING:
					    error(ERROR_SEMANTIC);
					    free(cons_name_tmp);
					    syn_free_stack(&stack,
							   stack_data);
					    return NULL;
					    break;
					default:
					    break;
				    }
				    stack_pop(&stack);
				    stack_data->stoken.token_type =
					TOKEN_SYNEXP_E;
				    avl_insert(symtab, cons_name_tmp,
					       type_tmp, &value_tmp);
				    avl_search_node(*symtab, cons_name_tmp,
						    &SearchSymbol);
				    stack_data->symtab_ptr = SearchSymbol;
				    if (SearchSymbol == NULL) {
					error(ERROR_SYNTAX);
					syn_free_stack(&stack, stack_data);
					return NULL;
				    }
				    ta_insert_last(TA_SUB, &operand1,
						   &operand2,
						   &SearchSymbol, ta);
				    stack_push(&stack,
					       (void *) &stack_data);
				} else {
				    error(ERROR_SYNTAX);
				    syn_free_stack(&stack, stack_data);
				    return NULL;
				}
				break;
			    case TOKEN_MULTIPLY:
				str_free(&(stack_data)->stoken.lexeme);
				free(stack_data);
				stack_pop(&stack);
				stack_top(&stack, (void *) &stack_data);
				if (stack_data->stoken.token_type ==
				    TOKEN_SYNEXP_E) {
				    operand1 = stack_data->symtab_ptr;
				    cons_name_tmp =
					syn_next_cons_name(cons_counter);
				    switch (operand1->type) {
					case TOKEN_INT:
					    if (operand2->type ==
						TOKEN_INT) {
						value_tmp.i = 0;
						type_tmp = SYMBOL_INT;
					    } else if (operand2->type ==
						       TOKEN_DOUBLE) {
						value_tmp.d = 0;
						type_tmp = SYMBOL_DOUBLE;
					    } else {
						error(ERROR_SEMANTIC);
						free(cons_name_tmp);
						syn_free_stack(&stack,
							       stack_data);
						return NULL;
					    }
					    break;
					case TOKEN_DOUBLE:
					    if (operand2->type !=
						TOKEN_STRING) {
						value_tmp.d = 0;
						type_tmp = SYMBOL_DOUBLE;
					    } else {
						error(ERROR_SEMANTIC);
						free(cons_name_tmp);
						syn_free_stack(&stack,
							       stack_data);
						return NULL;
					    }
					    break;
					case TOKEN_STRING:
					    error(ERROR_SEMANTIC);
					    free(cons_name_tmp);
					    syn_free_stack(&stack,
							   stack_data);
					    return NULL;
					default:
					    break;
				    }
				    stack_pop(&stack);
				    stack_data->stoken.token_type =
					TOKEN_SYNEXP_E;
				    avl_insert(symtab, cons_name_tmp,
					       type_tmp, &value_tmp);
				    avl_search_node(*symtab, cons_name_tmp,
						    &SearchSymbol);
				    stack_data->symtab_ptr = SearchSymbol;
				    if (SearchSymbol == NULL) {	// LADENI
					error(ERROR_SYNTAX);
					syn_free_stack(&stack, stack_data);
					return NULL;
				    }
				    ta_insert_last(TA_MUL, &operand1,
						   &operand2,
						   &SearchSymbol, ta);
				    stack_push(&stack,
					       (void *) &stack_data);
				} else {
				    error(ERROR_SYNTAX);
				    syn_free_stack(&stack, stack_data);
				    return NULL;
				}
				break;
			    case TOKEN_OVER:
				str_free(&(stack_data)->stoken.lexeme);
				free(stack_data);
				stack_pop(&stack);
				stack_top(&stack, (void *) &stack_data);
				if (stack_data->stoken.token_type ==
				    TOKEN_SYNEXP_E) {
				    operand1 = stack_data->symtab_ptr;
				    cons_name_tmp =
					syn_next_cons_name(cons_counter);
				    switch (operand1->type) {
					case TOKEN_INT:
					case TOKEN_DOUBLE:
					    if (operand2->type !=
						TOKEN_STRING) {
						value_tmp.d = 0;
						type_tmp = SYMBOL_DOUBLE;
					    } else {
						error(ERROR_SEMANTIC);
						free(cons_name_tmp);
						syn_free_stack(&stack,
							       stack_data);
						return NULL;
					    }
					    break;
					case TOKEN_STRING:
					    error(ERROR_SEMANTIC);
					    free(cons_name_tmp);
					    syn_free_stack(&stack,
							   stack_data);
					    return NULL;
					    break;
					default:
					    break;
				    }
				    stack_pop(&stack);
				    stack_data->stoken.token_type =
					TOKEN_SYNEXP_E;
				    avl_insert(symtab, cons_name_tmp,
					       type_tmp, &value_tmp);
				    avl_search_node(*symtab, cons_name_tmp,
						    &SearchSymbol);
				    if (get_error()) {
					error(ERROR_SYNTAX);
					syn_free_stack(&stack, stack_data);
					return NULL;
				    }
				    stack_data->symtab_ptr = SearchSymbol;
				    ta_insert_last(TA_OVER, &operand1,
						   &operand2,
						   &SearchSymbol, ta);
				    stack_push(&stack,
					       (void *) &stack_data);
				} else {
				    error(ERROR_SYNTAX);
				    syn_free_stack(&stack, stack_data);
				    return NULL;
				}
				break;
			    case TOKEN_PLUS:
				str_free(&(stack_data)->stoken.lexeme);
				free(stack_data);
				stack_pop(&stack);
				stack_top(&stack, (void *) &stack_data);
				if (stack_data->stoken.token_type ==
				    TOKEN_SYNEXP_E) {
				    operand1 = stack_data->symtab_ptr;
				    cons_name_tmp =
					syn_next_cons_name(cons_counter);
				    switch (operand1->type) {
					case TOKEN_INT:
					    if (operand2->type ==
						TOKEN_INT) {
						value_tmp.i = 0;
						type_tmp = SYMBOL_INT;
					    } else if (operand2->type ==
						       TOKEN_DOUBLE) {
						value_tmp.d = 0;
						type_tmp = SYMBOL_DOUBLE;
					    } else {
						error(ERROR_SEMANTIC);
						free(cons_name_tmp);
						syn_free_stack(&stack,
							       stack_data);
						return NULL;
					    }
					    break;
					case TOKEN_DOUBLE:
					    if (operand2->type !=
						TOKEN_STRING) {
						value_tmp.d = 0;
						type_tmp = SYMBOL_DOUBLE;
					    } else {
						error(ERROR_SEMANTIC);
						free(cons_name_tmp);
						syn_free_stack(&stack,
							       stack_data);
						return NULL;
					    }
					    break;
					case TOKEN_STRING:
					    if (operand2->type ==
						TOKEN_STRING) {
						str_init(&value_tmp.s);
						type_tmp = SYMBOL_STRING;
					    } else {
						error(ERROR_SEMANTIC);
						free(cons_name_tmp);
						syn_free_stack(&stack,
							       stack_data);
						return NULL;
					    }
					    break;
					default:
					    break;
				    }
				    stack_pop(&stack);
				    stack_data->stoken.token_type =
					TOKEN_SYNEXP_E;
				    avl_insert(symtab, cons_name_tmp,
					       type_tmp, &value_tmp);
				    avl_search_node(*symtab, cons_name_tmp,
						    &SearchSymbol);
				    if (get_error()) {
					error(ERROR_SYNTAX);
					syn_free_stack(&stack, stack_data);
					return NULL;
				    }
				    stack_data->symtab_ptr = SearchSymbol;
				    ta_insert_last(TA_ADD, &operand1,
						   &operand2,
						   &SearchSymbol, ta);
				    stack_push(&stack,
					       (void *) &stack_data);
				} else {
				    error(ERROR_SYNTAX);
				    syn_free_stack(&stack, stack_data);
				    return NULL;
				}
				break;
			    default:
				error(ERROR_SYNTAX);
				syn_free_stack(&stack, stack_data);
				return NULL;
				break;
			}
			break;
		    default:
			error(ERROR_SYNTAX);
			syn_free_stack(&stack, stack_data);
			return NULL;
			break;
		}
	    case P_Q:		// end of do-while
		break;
	    case P_E:		// continue in default
	    default:		// Unexpected Error, this status will not come. Maybe replace by case P_Q.
		error(ERROR_SYNTAX);
		syn_free_stack(&stack, stack_data);
		return NULL;
		break;
	}
    } while (token->token_type != TOKEN_DOLAR
	     || stack_data->stoken.token_type != TOKEN_DOLAR);

    stack_top(&stack, (void *) &stack_data);
    if (stack_data->symtab_ptr == NULL) {
	error(ERROR_SYNTAX);
	token_free(&(stack_data)->stoken);
	free(stack_data);
	stack_pop(&stack);	// dealloc $ in stack
	token_free(token);	// dealloc $ in buffer
	return NULL;
    }
    Result = stack_data->symtab_ptr;
    free(stack_data);
    stack_pop(&stack);		// dealloc last exp
    stack_top(&stack, (void *) &stack_data);
    token_free(&(stack_data)->stoken);
    free(stack_data);
    stack_pop(&stack);		// dealloc $ in stack
    token_free(token);		// dealloc $ in buffer
    lex(stream, token);		// token for syntax.c
    if (get_error()) {
	return NULL;
    }
    return Result;
}
示例#26
0
static int parse_client_line(const int client_socket, char *msg)
{
  char *token;
  
  /* On récupère le premier mot, s'il est vide, on retourne direct  */
  if (!(token = strtok(msg, " ")))
    return MSG_OK;

  /*****************************************************************************
   *                              CMD_QUIT
   ****************************************************************************/
  if (!strcmp(CMD_QUIT, token))
    {
      send_ok(client_socket, DETAIL_RET_QUIT);
      return MSG_QUIT;
    }
  
  /*****************************************************************************  
   *                          CMD_CREATE_PROCESS 
   ****************************************************************************/
  else if (!strcmp(CMD_CREATE_PROCESS, token))
    {
      char *args[MAX_ARGS];
      char **pc = args;

      /* On récup le nom du prog */
      if (!(token = strtok(NULL, " ")))
	{
	  send_failure(client_socket, DETAIL_RET_CREATE_PROCESS_SYNTAX);
	  return MSG_ERR;
	}
      
      /* strtok renvoie un buffer static, on le copie */
      /* *pc = args[0] = nom du programme */
      if (!(*pc++ = strdup(token))) 
	{
	  perror("strdup");
	  return MSG_ERR;
	}
      
      /* La suite devient optionelle, c'est les arguments */
      while ((token = strtok(NULL, " ")))
	{
	  if ((*pc++ = strdup(token)) == NULL)
	    {
	      perror("strdup");
	      return MSG_ERR;
	    }
	}
      
      *pc = NULL;             /* Fin des arguments */
      
      /* On crée le processus */
      pid_t proc = create_process(args[0], args);

      /* Le processus n'a pas pu être créé */
      if (proc == -1) {
	send_failure(client_socket, DETAIL_RET_CREATE_PROCESS_ERROR);
	return MSG_ERR;
      }

      send_ok(client_socket, itoa(proc));
      return MSG_OK;
    }

  /*****************************************************************************  
   *                          CMD_DESTROY_PROCESS 
   ****************************************************************************/
  else if (!strcmp(CMD_DESTROY_PROCESS, token))
    {
      if ((token = strtok(NULL, " ")) == NULL)
	{
	  send_failure(client_socket, DETAIL_RET_DESTROY_PROCESS_SYNTAX);
	  return MSG_ERR;
	}
      
      pid_t process_to_kill = atoi(token);
      
      if (!process_exists(process_to_kill))
	{
	  send_failure(client_socket, DETAIL_RET_UNKNOWN_PROCESS);
	  return MSG_ERR;
	}
      
      destroy_process(process_to_kill);
      send_ok(client_socket, NULL);
      return MSG_OK;
    }

  /*****************************************************************************  
   *                          CMD_SEND_INPUT      
   ****************************************************************************/
  else if (!strcmp(CMD_SEND_INPUT, token))
    {
      char buffer[MESSAGE_BUFFER_SIZE];
      buffer[0] = '\0';
      
      /* On récup le PID */
      if ((token = strtok(NULL, " ")) == NULL)
	{
	  send_failure(client_socket, DETAIL_RET_SEND_INPUT_SYNTAX);
	  return MSG_ERR;
	}
      
      /* Il existe ? */
      pid_t send_to_process = atoi(token);
      if (!process_exists(send_to_process))
	{
	  send_failure(client_socket, DETAIL_RET_UNKNOWN_PROCESS);
	  return MSG_ERR;
	}
      
      /* Il est déjà terminé ? */
      if (get_return_code(send_to_process) != PROCESS_NOT_TERMINATED)
	{
	  send_failure(client_socket, DETAIL_RET_PROCESS_TERMINATED);
	  return MSG_ERR;
	}

      /* Son stdin est ouvert ? */
      if (!input_open(send_to_process))
	{
	  send_failure(client_socket, DETAIL_RET_INPUT_CLOSE);
	  return MSG_ERR;
	}

      /* On récup' le message à envoyer  */
      /* TODO: Prendre la chaîne telle qu'elle, sans splitter puis merger avec un espace */
      while ((token = strtok(NULL, " ")))
	{
	  strcat(buffer, token);
	  strcat(buffer, " ");
	}
      
      /* Si le message est vide, erreur ! */
      if (strlen(buffer) == 0)
	{
	  send_failure(client_socket, DETAIL_RET_SEND_INPUT_SYNTAX);
	  return MSG_ERR;
        }
      
      /* Sinon on envoie ! */
      send_input(send_to_process, buffer);
      send_ok(client_socket, NULL);
      return MSG_OK;
    }


  /*****************************************************************************  
   *                          CMD_CLOSE_INPUT     
   ****************************************************************************/
  else if (!strcmp(CMD_CLOSE_INPUT, token))
    {
      if ((token = strtok(NULL, " ")) == NULL)
	{
	  send_failure(client_socket, DETAIL_RET_CLOSE_INPUT_SYNTAX);
	  return MSG_ERR;
        }
      
      pid_t process_to_close_input = atoi(token);
      if (!process_exists(process_to_close_input))
	{
	  send_failure(client_socket, DETAIL_RET_UNKNOWN_PROCESS);
	  return MSG_ERR;
	}

      close_input(process_to_close_input);
      send_ok(client_socket, NULL);
      return MSG_OK;
    }
  
  /*****************************************************************************  
   *                          CMD_GET_OUTPUT
   ****************************************************************************/
  else if (!strcmp(CMD_GET_OUTPUT, token))
    {
      if ((token = strtok(NULL, " ")) == NULL)
	{
	  send_failure(client_socket, DETAIL_RET_GET_OUTPUT_SYNTAX);
	  return MSG_ERR;
	}
      
      pid_t process_to_get_output = atoi(token);
      if (!process_exists(process_to_get_output))
	{
	  send_failure(client_socket, DETAIL_RET_UNKNOWN_PROCESS);
	  return MSG_ERR;
        }
     
      get_output(client_socket, process_to_get_output);
      send_ok(client_socket, NULL);
      return MSG_OK;
    }


  /*****************************************************************************  
   *                          CMD_GET_ERROR
   ****************************************************************************/
  else if (!strcmp(CMD_GET_ERROR, token))
    {
      if ((token = strtok(NULL, " ")) == NULL)
	{
	  send_failure(client_socket, DETAIL_RET_GET_ERROR_SYNTAX);
	  return MSG_ERR;
        }
      
      pid_t process_to_get_error = atoi(token);
      if (!process_exists(process_to_get_error))
	{
	  send_failure(client_socket, DETAIL_RET_UNKNOWN_PROCESS);
	  return MSG_ERR;
	}
      
      get_error(client_socket, process_to_get_error);
      send_ok(client_socket, NULL);
      return MSG_OK;
    }


  /*****************************************************************************  
   *                          CMD_GET_RETURN_CODE
   ****************************************************************************/
  else if (!strcmp(CMD_GET_RETURN_CODE, token))
    {
      if ((token = strtok(NULL, " ")) == NULL)
	{
	  send_failure(client_socket, DETAIL_RET_GET_RETURN_CODE_SYNTAX);
	  return MSG_ERR;
        }
      
      pid_t process_to_get_ret = atoi(token);
      if (!process_exists(process_to_get_ret))
	{
	  send_failure(client_socket, DETAIL_RET_UNKNOWN_PROCESS);
	  return MSG_ERR;
	}
      
      int ret = get_return_code(process_to_get_ret);
      if (ret == PROCESS_NOT_TERMINATED)
	{
	  send_failure(client_socket, DETAIL_RET_GET_RETURN_CODE_ERROR);
	  return MSG_ERR;
	}
      
      send_ok(client_socket, itoa(ret));
      return MSG_OK;
    }

  /*****************************************************************************  
   *                          CMD_LIST_PROCESS   
   ****************************************************************************/
  else if (!strcmp(CMD_LIST_PROCESS, token))
    {
      list_process(client_socket);
      send_ok(client_socket, NULL);
      return MSG_OK;
    }

  /*****************************************************************************  
   *                          CMD_GET_HELP
   ****************************************************************************/
  else if (!strcmp(CMD_GET_HELP, token))
    {
      send_basic(client_socket, help, strlen(help));
      return MSG_OK;
    }

  /*****************************************************************************  
   *                        COMMANDE INCONNUE
   ****************************************************************************/
  else
    {
      send_failure(client_socket, DETAIL_RET_UNKNOWN_COMMAND);
      return MSG_UNKNOWN_COMMAND;
    }
}
示例#27
0
void blue_design_fill_check_error(void)
{
  if (get_error(blue_design_fill_parameter_defaults_xml))
    fprintf(stderr, "Parameter Error; defaults-xml\n");
}
示例#28
0
/* ARGSUSED */
int
posix_spawnp(
	pid_t *pidp,
	const char *file,
	const posix_spawn_file_actions_t *file_actions,
	const posix_spawnattr_t *attrp,
	char *const argv[],
	char *const envp[])
{
	spawn_attr_t *sap = attrp? attrp->__spawn_attrp : NULL;
	file_attr_t *fap = file_actions? file_actions->__file_attrp : NULL;
	void *dirbuf = NULL;
	const char *pathstr = (strchr(file, '/') == NULL)? getenv("PATH") : "";
	int xpg4 = libc__xpg4;
	int error = 0;		/* this will be set by the child */
	char path[PATH_MAX+4];
	const char *cp;
	pid_t pid;
	char **newargs;
	int argc;
	int i;

	if (attrp != NULL && sap == NULL)
		return (EINVAL);

	if (*file == '\0')
		return (EACCES);

	if (fap != NULL && fap->fa_need_dirbuf) {
		/*
		 * Preallocate the buffer for the call to getdents64() in
		 * spawn_closefrom() since we can't do it in the vfork() child.
		 */
		if ((dirbuf = lmalloc(DIRBUF)) == NULL)
			return (ENOMEM);
	}

	/*
	 * We may need to invoke the shell with a slightly modified
	 * argv[] array.  To do this we need to preallocate the array.
	 * We must call alloca() before calling vfork() because doing
	 * it after vfork() (in the child) would corrupt the parent.
	 */
	for (argc = 0; argv[argc] != NULL; argc++)
		continue;
	newargs = alloca((argc + 2) * sizeof (char *));

	switch (pid = vforkx(forkflags(sap))) {
	case 0:			/* child */
		break;
	case -1:		/* parent, failure */
		if (dirbuf)
			lfree(dirbuf, DIRBUF);
		return (errno);
	default:		/* parent, success */
		/*
		 * We don't get here until the child exec()s or exit()s
		 */
		if (pidp != NULL && get_error(&error) == 0)
			*pidp = pid;
		if (dirbuf)
			lfree(dirbuf, DIRBUF);
		return (get_error(&error));
	}

	if (sap != NULL)
		if (set_error(&error, perform_flag_actions(sap)) != 0)
			_exit(_EVAPORATE);

	if (fap != NULL)
		if (set_error(&error, perform_file_actions(fap, dirbuf)) != 0)
			_exit(_EVAPORATE);

	if (pathstr == NULL) {
		/*
		 * XPG4:  pathstr is equivalent to _CS_PATH, except that
		 * :/usr/sbin is appended when root, and pathstr must end
		 * with a colon when not root.  Keep these paths in sync
		 * with _CS_PATH in confstr.c.  Note that pathstr must end
		 * with a colon when not root so that when file doesn't
		 * contain '/', the last call to execat() will result in an
		 * attempt to execv file from the current directory.
		 */
		if (geteuid() == 0 || getuid() == 0) {
			if (!xpg4)
				pathstr = "/usr/sbin:/usr/ccs/bin:/usr/bin";
			else
				pathstr = "/usr/xpg4/bin:/usr/ccs/bin:"
				    "/usr/bin:/opt/SUNWspro/bin:/usr/sbin";
		} else {
			if (!xpg4)
				pathstr = "/usr/ccs/bin:/usr/bin:";
			else
				pathstr = "/usr/xpg4/bin:/usr/ccs/bin:"
				    "/usr/bin:/opt/SUNWspro/bin:";
		}
	}

	cp = pathstr;
	do {
		cp = execat(cp, file, path);
		/*
		 * 4025035 and 4038378
		 * if a filename begins with a "-" prepend "./" so that
		 * the shell can't interpret it as an option
		 */
		if (*path == '-') {
			char *s;

			for (s = path; *s != '\0'; s++)
				continue;
			for (; s >= path; s--)
				*(s + 2) = *s;
			path[0] = '.';
			path[1] = '/';
		}
		(void) set_error(&error, 0);
		(void) execve(path, argv, envp);
		if (set_error(&error, errno) == ENOEXEC) {
			newargs[0] = "sh";
			newargs[1] = path;
			for (i = 1; i <= argc; i++)
				newargs[i + 1] = argv[i];
			(void) set_error(&error, 0);
			(void) execve(_PATH_BSHELL, newargs, envp);
			if (sap != NULL &&
			    (sap->sa_psflags & POSIX_SPAWN_NOEXECERR_NP))
				_exit(127);
			(void) set_error(&error, errno);
			_exit(_EVAPORATE);
		}
	} while (cp);

	if (sap != NULL &&
	    (sap->sa_psflags & POSIX_SPAWN_NOEXECERR_NP)) {
		(void) set_error(&error, 0);
		_exit(127);
	}
	_exit(_EVAPORATE);
	return (0);	/* not reached */
}
示例#29
0
int main(int argc, char **argv)
{
    psirp_id_t rid, sid, rid_r, sid_r;
    char *test_str = NULL;
    char *newstr = NULL;
    int expected = 0;
    int result;
    char c;

    while((c = getopt(argc, argv, "e:a:vz")) != EOF) {
        switch(c) {
        case 'e': expected = -1 * atoi(optarg); break;
        case 'a': test_str = optarg; break;
        case 'z': reverse = 1; break;
        case 'v': verbose = 1; break;
        default:
            usage();
        }
    }

    result = psirp_atoids(&sid, &rid, test_str);
    if (reverse) {
        if (result != 0) {
            printf("ERROR: Illegal string: %s\n", test_str);
            return EX_SOFTWARE;
        }
        newstr = psirp_idstoa(&sid, &rid); 
        if (!newstr) {
            printf("ERROR: Could not reverse map IDs of string: %s\n", 
                   test_str);
            return EX_SOFTWARE;
        }
        /* Test that the converted ascii string is the same as argument.
           Requires canonicalization of the strings. We achieve this by
           reconverting the converted ascii string to binary presentation
           and by comparing memory.
           Alternatively, we could have an extra function to "inflate"
           the compressed strings, and that would require extra tests.
        */
        result = psirp_atoids(&sid_r, &rid_r, newstr);
        if (result != 0) {
            printf("ERROR: error: %2d, Converted string illegal: "
                   "%s (original: %s)\n", result, newstr, test_str);
            return EX_SOFTWARE;
        }
        
        if (memcmp(sid.id, sid_r.id, PSIRP_ID_LEN) ||
            memcmp(rid.id, rid_r.id, PSIRP_ID_LEN)) {
            printf("ERROR: Converted IDs do not match the original "
                   "string\n");
            return EX_SOFTWARE;
        }
    }
    
    
    if (result == expected) {
        if (verbose) {
            printf("OK: result=%3d: %67s\n", result, get_error(result));
            return EX_OK;
        }
        return EX_OK;
    }
    printf("ERROR: expected=%3d, result=%3d: %50s\n", expected, result,
           get_error(result));
    return EX_SOFTWARE;
}
示例#30
0
bool		PTnVmon::start	(IOService* provider) {
	bool result=IOService::start(provider);
	int card_number=0;
	
	nvclock.dpy = NULL;
	
	char* key = (char*)IOMalloc(5);
	
	max_card=probe_devices();
	
	if(!max_card){
		char buf[80];
		printf("Error: %s\n", get_error(buf, 80));
		return 0;
	}
	
	for (card_number=0; card_number<max_card; card_number++) {
		/* set the card object to the requested card */
		if(!set_card(card_number)){
			char buf[80];
			printf("Error: %s\n", get_error(buf, 80));
			return 0;
		}
	
		nvbios* bios=read_bios("");
		nvclock.card[card_number].bios=bios;
		
		/* Check if the card is supported, if not print a message. */
		if(nvclock.card[card_number].gpu == UNKNOWN){
			printf("It seems your card isn't officialy supported in FakeSMCnVclockPort yet.\n");
			printf("Please tell the author the pci_id of the card for further investigation.\n");
			printf("Continuing anyway\n");
		}

	
		if(nv_card->caps & (GPU_TEMP_MONITORING)){
			snprintf(key, 5, KEY_FORMAT_GPU_DIODE_TEMPERATURE, card_number);
			tempSensor[card_number]=new TemperatureSensor(key, TYPE_SP78, 2);
		
			if(nv_card->caps & (BOARD_TEMP_MONITORING)) {
				snprintf(key, 5, KEY_FORMAT_GPU_BOARD_TEMPERATURE, card_number);
				boardSensor[card_number]=new TemperatureSensor(key, TYPE_SP78, 2);
			}
		}
		
		
		
		if(nv_card->caps & (I2C_FANSPEED_MONITORING | GPU_FANSPEED_MONITORING)){
			int id=GetNextUnusedKey(KEY_FORMAT_FAN_ID, key);
			int ac=GetNextUnusedKey(KEY_FORMAT_FAN_SPEED, key);
			if (id!=-1 || ac!=-1) {
				int no=id>ac ? id : ac;
				char name[6]; 
				snprintf (name, 6, "GPU %d", card_number);
				snprintf(key, 5, KEY_FORMAT_FAN_ID, no);
				FakeSMCAddKey(key, TYPE_CH8, 4, name);			
				snprintf(key, 5, KEY_FORMAT_FAN_SPEED, no);
				fanSensor[card_number]=new FanSensor(key, TYPE_FPE2, 2);
				UpdateFNum();
			}
		}
		snprintf(key, 5, "FGC%d", card_number);
		gpuFreqSensor[card_number]=new FrequencySensor(key, "freq", 2);
	}
	IOFree(key, 5);
	return result;
}