1

我正在尝试编写自己的代码来连接到 X 服务器。我运行 xauth 来获取我需要的魔法 cookie,并编写了以下代码来尝试测试建立连接:

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>

int main()
{  
  int sockfd = socket(AF_UNIX, SOCK_STREAM, 0);

  struct sockaddr_un serv_addr;
  memset((void*)&serv_addr, 0, sizeof(serv_addr));
  serv_addr.sun_family = AF_UNIX;
  strcpy(serv_addr.sun_path, "/tmp/.X11-unix/X0");
  int servlen = 17 + sizeof(serv_addr.sun_family);

  int err = connect(sockfd, (struct sockaddr*)&serv_addr, servlen);

  char arr[] = {108, 0, // 'l' for little-endian
                11, 0, // X version
                0, 0,  // X minor version
                18, 0, // length of auth protocol name
                16, 0, // length of auth protocol data
                0, 0, // padding
                77, 73, 84, 45, 77, 65, 71, 73, 67, 45, 67, 79, 79, 75, 73, 69, 45, 49, // MIT-MAGIC-COOKIE-1
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
                223, 88, 218, 121, 215, 6, 185, 105, 137, 80, 105, 252, 49, 109, 38,  200, // data from .Xauthority
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

  ssize_t bytes_written = write(sockfd, arr, sizeof(arr));
  printf("%d\n", bytes_written);

  uint8_t buf[5000];
  ssize_t bytes_read = read(sockfd, buf, 5000);
  printf("%d\n", bytes_read);

  unsigned char k;
  for(k = 0; k < 40; k++) {
    printf("%c", buf[k]);
  }
  return 0;
}

X 服务器响应正常,但它给了我一条身份验证失败消息,原因是“无效的 MIT-MAGIC-COOKIE-1 密钥”。我提供的密钥与我的 .Xauthority 文件中的密钥相同(df58da79d706b969895069fc316d26c8,以防有人想检查!)我还缺少什么吗?

4

1 回答 1

0

你有太多的填充零。应该:

  char arr[] = {108, 0, // 'l' for little-endian
                11, 0, // X version
                0, 0,  // X minor version
                18, 0, // length of auth protocol name
                16, 0, // length of auth protocol data
                0, 0, // padding
                77, 73, 84, 45, 77, 65, 71, 73, 67, 45, 67, 79, 79, 75, 73, 69, 45, 49, // MIT-MAGIC-COOKIE-1
                0, 0, // two bytes to pad 18-byte MIT-MAGIC-COOKIE-1 to factor of 4 - 20
                223, 88, 218, 121, 215, 6, 185, 105, 137, 80, 105, 252, 49, 109, 38,  200 // data from .Xauthority
                }; // no need for more padding, auth data is 16 bytes long, factor of 4

X11 协议的第 140 页开始:

Information sent by the client at connection setup:

1 byte-order
 ▶x42 MSB first
 ▶x6C LSB first
 1 unused
 2 CARD16 protocol-major-version
 2 CARD16 protocol-minor-version
 2 n length of authorization-protocol-name
 2 d length of authorization-protocol-data
 2 unused
 n STRING8 authorization-protocol-name
 p unused, p=pad(n)
 d STRING8 authorization-protocol-data
 q unused, q=pad(d)
于 2013-05-17T15:09:04.193 回答