aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


server/native_creation.go (9489B)


      1 package main
      2 
      3 import (
      4 	"ao/server/gamedata"
      5 	"context"
      6 	"crypto/rand"
      7 	"crypto/sha256"
      8 	"encoding/binary"
      9 	"errors"
     10 	"fmt"
     11 	"io"
     12 	"log"
     13 	"net"
     14 	"net/http"
     15 
     16 	"github.com/coder/websocket"
     17 )
     18 
     19 type browserCreationCredentials struct {
     20 	name       string
     21 	salt, hash []byte
     22 }
     23 
     24 var (
     25 	errBrowserCreationRequired = errors.New("Start character creation first.")
     26 	errBrowserCreationEnded    = errors.New("Character creation has ended. Start again to continue.")
     27 )
     28 
     29 func (state *server) prepareBrowserCreation(w http.ResponseWriter, r *http.Request) {
     30 	w.Header().Set("Cache-Control", "no-store")
     31 	r.Body = http.MaxBytesReader(w, r.Body, 4096)
     32 	if err := r.ParseForm(); err != nil {
     33 		http.Error(w, "Invalid account form.", http.StatusBadRequest)
     34 		return
     35 	}
     36 	name, valid := browserPlayerName(r.PostForm.Get("name"))
     37 	password := r.PostForm.Get("password")
     38 	if !valid || len(password) > 1024 {
     39 		http.Error(w, "Use a name of 4-12 letters or digits, with at least four initial letters and digits only at the end, and a password up to 1024 bytes.", http.StatusBadRequest)
     40 		return
     41 	}
     42 	if !validNewPassword(password) {
     43 		http.Error(w, "Use a password of at least 5 characters and at most 1024 bytes.", http.StatusBadRequest)
     44 		return
     45 	}
     46 	credential := browserCredential(r)
     47 	var currentID uint32
     48 	var pending *browserCreationCredentials
     49 	err := state.accountOperation(func(coordinator *worldCoordinator) error {
     50 		var err error
     51 		currentID, err = state.browserPlayerID(credential)
     52 		if err != nil {
     53 			return err
     54 		}
     55 		if currentID == 0 {
     56 			return errBrowserSessionChanged
     57 		}
     58 		pending = coordinator.browserCreations[credential]
     59 		if pending == nil {
     60 			return errBrowserCreationRequired
     61 		}
     62 		return nil
     63 	})
     64 	if err == nil {
     65 		// Derive outside ownership, then recheck the same attempt and identity.
     66 		salt := make([]byte, 16)
     67 		rand.Read(salt)
     68 		hash := state.browserPassword(password, salt)
     69 		err = state.accountOperation(func(coordinator *worldCoordinator) error {
     70 			id, err := state.browserPlayerID(credential)
     71 			if err != nil {
     72 				return err
     73 			}
     74 			if id == 0 || id != currentID {
     75 				return errBrowserSessionChanged
     76 			}
     77 			if coordinator.browserCreations[credential] != pending {
     78 				return errBrowserCreationEnded
     79 			}
     80 			var taken bool
     81 			if err := coordinator.db.QueryRow("SELECT EXISTS(SELECT 1 FROM characters WHERE id<1000000 AND name=? COLLATE NOCASE)", name).Scan(&taken); err != nil {
     82 				return err
     83 			}
     84 			if taken {
     85 				return errBrowserNameTaken
     86 			}
     87 			pending.name, pending.salt, pending.hash = name, salt, hash
     88 			return nil
     89 		})
     90 	}
     91 	if err != nil {
     92 		status := http.StatusInternalServerError
     93 		if errors.Is(err, errBrowserSessionChanged) {
     94 			status = http.StatusUnauthorized
     95 		} else if errors.Is(err, errBrowserCreationRequired) || errors.Is(err, errBrowserCreationEnded) || errors.Is(err, errBrowserNameTaken) {
     96 			status = http.StatusConflict
     97 		}
     98 		http.Error(w, err.Error(), status)
     99 		return
    100 	}
    101 
    102 	w.Header().Set("X-AO-Creation-Name", name)
    103 	w.WriteHeader(http.StatusNoContent)
    104 }
    105 
    106 func (state *server) browserCreate(w http.ResponseWriter, r *http.Request) {
    107 	credential := browserCredential(r)
    108 	var id uint32
    109 	var pending *browserCreationCredentials
    110 	err := state.accountOperation(func(coordinator *worldCoordinator) error {
    111 		var err error
    112 		id, err = state.browserPlayerID(credential)
    113 		if err != nil {
    114 			return err
    115 		}
    116 		if id == 0 {
    117 			return errBrowserSessionChanged
    118 		}
    119 		pending = coordinator.browserCreations[credential]
    120 		if pending == nil {
    121 			return errBrowserCreationRequired
    122 		}
    123 		return nil
    124 	})
    125 	if err != nil {
    126 		status := http.StatusInternalServerError
    127 		if errors.Is(err, errBrowserSessionChanged) {
    128 			status = http.StatusUnauthorized
    129 		} else if errors.Is(err, errBrowserCreationRequired) {
    130 			status = http.StatusConflict
    131 		}
    132 		http.Error(w, err.Error(), status)
    133 		return
    134 	}
    135 
    136 	socket, err := websocket.Accept(w, r, nil)
    137 	if err != nil {
    138 		return
    139 	}
    140 	defer socket.CloseNow()
    141 	finish, accepted := state.tasks.enter(func() { socket.CloseNow() })
    142 	if !accepted {
    143 		return
    144 	}
    145 	defer finish()
    146 	connection := websocket.NetConn(context.Background(), socket, websocket.MessageBinary)
    147 	if err := state.serveNativeCreation(connection, id, credential, pending); err != nil {
    148 		log.Printf("Browser creation connection: %v", err)
    149 	}
    150 }
    151 
    152 func (state *server) serveNativeCreation(conn net.Conn, currentID uint32, credential string, pending *browserCreationCredentials) error {
    153 	var createdID uint32
    154 	for {
    155 		packet, err := readPacket(conn)
    156 		if err == io.EOF {
    157 			return nil
    158 		}
    159 		if err != nil {
    160 			return err
    161 		}
    162 		opcode := binary.BigEndian.Uint32(packet[16:20])
    163 		traceLog.Printf("Creation C2S opcode=0x%02x length=%d", opcode, len(packet))
    164 		var response []byte
    165 		switch opcode {
    166 		case 0x22:
    167 			response = systemPacket(0x24, []byte("0123456789abcdef0123456789abcdef\x00"))
    168 		case 0x25:
    169 			// The browser cookie authenticates this connection, independently of launcher credentials.
    170 			response = systemPacket(0x0e, binary.BigEndian.AppendUint32(nil, 0))
    171 		case 0x55:
    172 			var name string
    173 			if err := state.accountOperation(func(*worldCoordinator) error { name = pending.name; return nil }); err != nil {
    174 				return err
    175 			}
    176 			if name == "" {
    177 				name = randomVisitorName()
    178 			}
    179 			response = systemPacket(0x56, append(binary.BigEndian.AppendUint16(nil, uint16(len(name))), name...))
    180 		case 0x0f:
    181 			var reason uint32
    182 			if createdID == 0 {
    183 				createdID, reason, err = state.createNativeCharacter(currentID, credential, pending, packet[20:])
    184 				if err != nil {
    185 					log.Printf("Creating browser character: %v", err)
    186 					reason = 9
    187 				}
    188 			}
    189 			if reason != 0 {
    190 				response = systemPacket(0x10, binary.BigEndian.AppendUint32(nil, reason))
    191 			} else {
    192 				response = systemPacket(0x11, binary.BigEndian.AppendUint32(nil, createdID))
    193 			}
    194 		case 0x16:
    195 			if len(packet) != 24 || createdID == 0 || binary.BigEndian.Uint32(packet[20:]) != createdID {
    196 				return fmt.Errorf("invalid created character selection")
    197 			}
    198 			body := binary.BigEndian.AppendUint32(nil, createdID)
    199 			body = append(body, 127, 0, 0, 1)
    200 			body = binary.BigEndian.AppendUint16(body, uint16(state.worldPort))
    201 			body = append(body, make([]byte, 8)...)
    202 			response = systemPacket(0x17, body)
    203 		default:
    204 			return fmt.Errorf("unimplemented creation opcode 0x%02x", opcode)
    205 		}
    206 		if _, err := conn.Write(response); err != nil {
    207 			return err
    208 		}
    209 	}
    210 }
    211 
    212 func (state *server) createNativeCharacter(currentID uint32, credential string, pending *browserCreationCredentials, body []byte) (uint32, uint32, error) {
    213 	// nr.dll!CharacterData_t::WriteDataStream and CharacterInfo_c::WriteStream use version 4.
    214 	if len(body) < 89 || binary.BigEndian.Uint32(body) != 4 || body[8] != 'a' || binary.BigEndian.Uint32(body[37:]) != 4 {
    215 		return 0, 9, nil
    216 	}
    217 	length := int(binary.BigEndian.Uint32(body[45:]))
    218 	if length < 4 || length > 12 || len(body) < 89+length {
    219 		return 0, 9, nil
    220 	}
    221 	name, valid := browserPlayerName(string(body[49 : 49+length]))
    222 	if !valid {
    223 		return 0, 0x1f, nil
    224 	}
    225 	fields := body[49+length:]
    226 	breed, sex := binary.BigEndian.Uint32(fields), binary.BigEndian.Uint32(fields[4:])
    227 	profession := binary.BigEndian.Uint32(fields[8:])
    228 	// CharacterInfo writes variable-length area and ban-reason strings before appearance.
    229 	areaLength := int(binary.BigEndian.Uint32(fields[16:]))
    230 	if areaLength > len(fields)-40 {
    231 		return 0, 9, nil
    232 	}
    233 	fields = fields[20+areaLength:]
    234 	reasonLength := int(binary.BigEndian.Uint32(fields[4:]))
    235 	if reasonLength != len(fields)-20 {
    236 		return 0, 9, nil
    237 	}
    238 	fields = fields[8+reasonLength:]
    239 	headIndex, height, build := binary.BigEndian.Uint32(fields), binary.BigEndian.Uint32(fields[4:]), binary.BigEndian.Uint32(fields[8:])
    240 	if profession < 1 || profession > 12 || build > 2 || height != 90 && height != 100 && height != 110 {
    241 		return 0, 9, nil
    242 	}
    243 
    244 	// Native head ordinals are scoped to the selected breed/sex catalog, including Atrox sex 1.
    245 	var mesh uint32
    246 	for _, head := range gamedata.PlayerAppearances.Heads {
    247 		if uint32(head.Breed) == breed && uint32(head.Sex) == sex {
    248 			if headIndex == 0 {
    249 				mesh = head.Mesh
    250 				break
    251 			}
    252 			headIndex--
    253 		}
    254 	}
    255 	if mesh == 0 {
    256 		return 0, 9, nil
    257 	}
    258 	player, err := state.creationCharacter(mesh, uint16(profession), 0, uint16(build), uint16(height))
    259 	if err != nil {
    260 		return 0, 0, err
    261 	}
    262 	player.name = name
    263 	player.playfield, player.position = 4604, [3]float32{190, 1.52, 200}
    264 	player.rotation, player.returnDoor = [4]float32{0, 1, 0, 0}, nil
    265 
    266 	// The coordinator owns pending credentials until commit and publication finish.
    267 	var created, reason uint32
    268 	err = state.accountOperation(func(coordinator *worldCoordinator) error {
    269 		if coordinator.browserCreations[credential] != pending || len(pending.hash) == 0 {
    270 			reason = 2
    271 			return nil
    272 		}
    273 		if name != pending.name {
    274 			reason = 0x1f
    275 			return nil
    276 		}
    277 		change := &browserAccountChange{action: "native", current: currentID, previous: credential,
    278 			credential: credential, abandoned: fmt.Sprintf("%x", sha256.Sum256([]byte(rand.Text()))),
    279 			name: name, salt: pending.salt, hash: pending.hash, created: player}
    280 		err := state.applyBrowserAccountChange(coordinator, change)
    281 		switch {
    282 		case errors.Is(err, errBrowserSessionChanged):
    283 			reason = 2
    284 		case errors.Is(err, errBrowserNameTaken):
    285 			reason = 0x1e
    286 		case errors.Is(err, errPlayerIdentitiesExhausted):
    287 			reason = 8
    288 		case err != nil:
    289 			return err
    290 		default:
    291 			created = change.target
    292 			delete(coordinator.browserCreations, credential)
    293 		}
    294 		return nil
    295 	})
    296 	return created, reason, err
    297 }